From defd9642e7a44829bad053fe5be770e2736b0a3d Mon Sep 17 00:00:00 2001 From: quan Date: Sun, 5 Mar 2017 15:30:55 +0700 Subject: [PATCH] version 1.2 --- .idea/xcode.xml | 2 +- App/Base.lproj/Main.storyboard | 5 + App/Localizable.strings | 8 +- App/addPerson/VCConfirmId.swift | 17 +- App/commons/CellMucChupWithCamera.swift | 82 +- App/commons/VCRoot.swift | 12 +- App/createNew/CellChonMucChup.swift | 2 +- App/createNew/VCChonMucChup.swift | 6 +- App/createNew/VCConfirmMucDaChon.swift | 2 +- App/createNew/VCRootCreateNew.swift | 30 +- App/createNew/VCSettingBienQC.swift | 14 +- App/firstInput/VCInputId.swift | 14 +- App/firstInput/VCNoiDungTraoDoi.swift | 2 +- App/listCtruong/CellCtruong.swift | 11 +- App/listCtruong/VCListCtruong.swift | 5 +- App/listCtruong/VCShootItemList.swift | 17 +- App/model/CongTruong.swift | 23 +- App/model/ImgObj.swift | 26 +- App/model/MucChup.swift | 19 - App/model/ShootItem.swift | 40 + App/utils/AppUtils.swift | 18 +- App/utils/Constants.swift | 16 + App/utils/FileUpload.swift | 110 ++ App/utils/NetWorkUtils.swift | 39 + GeneralUtils/.idea/GeneralUtils.iml | 2 + GeneralUtils/.idea/encodings.xml | 6 + .../.idea/inspectionProfiles/Project_Default.xml | 5 + GeneralUtils/.idea/misc.xml | 96 ++ GeneralUtils/.idea/modules.xml | 8 + GeneralUtils/.idea/vcs.xml | 6 + GeneralUtils/.idea/workspace.xml | 715 ++++++++ GeneralUtils/.idea/xcode.xml | 4 + GeneralUtils/GeneralUtils.podspec | 15 + .../GeneralUtils.xcodeproj/project.pbxproj | 1169 +++++++++++++ .../project.xcworkspace/contents.xcworkspacedata | 7 + .../UserInterfaceState.xcuserstate | Bin 0 -> 56222 bytes .../xcschemes/xcschememanagement.plist | 5 + .../xcschemes/GeneralUtils.xcscheme | 80 + .../xcschemes/xcschememanagement.plist | 22 + .../ic_arrow_back_black.imageset/Contents.json | 23 + .../ic_arrow_back_36pt.png | Bin 0 -> 1111 bytes .../ic_arrow_back_36pt_2x.png | Bin 0 -> 1248 bytes .../ic_arrow_back_36pt_3x.png | Bin 0 -> 1367 bytes .../ic_arrow_drop_down.imageset/Contents.json | 21 + .../ic_arrow_drop_down.png | Bin 0 -> 1186 bytes .../placeholder.imageset/Contents.json | 23 + .../placeholder.imageset/placeholder.png | Bin 0 -> 2442 bytes .../placeholder.imageset/placeholder@2x.png | Bin 0 -> 5674 bytes .../placeholder.imageset/placeholder@3x.png | Bin 0 -> 10314 bytes .../Assets.xcassets/press.imageset/Contents.json | 21 + .../Assets.xcassets/press.imageset/press.png | Bin 0 -> 6530 bytes GeneralUtils/GeneralUtils/GeneralUtils.h | 20 + GeneralUtils/GeneralUtils/Info.plist | 24 + .../GeneralUtils/commonUtils/CacheUtils.swift | 82 + .../GeneralUtils/commonUtils/CommonExtension.swift | 387 +++++ .../GeneralUtils/commonUtils/CommonUtils.swift | 118 ++ .../GeneralUtils/commonUtils/DataTypeUtils.swift | 70 + .../GeneralUtils/commonUtils/DialogUtils.swift | 183 ++ .../GeneralUtils/commonUtils/DownloadTask.swift | 91 + .../GeneralUtils/commonUtils/FileUtils.swift | 233 +++ .../GeneralUtils/commonUtils/NetWorkUtils.swift | 190 +++ .../GeneralUtils/commonUtils/PreferenceUtils.swift | 46 + GeneralUtils/GeneralUtils/commonUtils/Queue.swift | 47 + .../GeneralUtils/commonUtils/RecordUtils.swift | 81 + .../GeneralUtils/commonUtils/SecurityUtils.swift | 41 + .../GeneralUtils/commonUtils/StringExtension.swift | 673 ++++++++ .../GeneralUtils/libs/CryptoSwift/AES.swift | 586 +++++++ .../libs/CryptoSwift/Array+Extension.swift | 47 + .../libs/CryptoSwift/Authenticator.swift | 13 + .../GeneralUtils/libs/CryptoSwift/Bit.swift | 19 + .../libs/CryptoSwift/BlockCipher.swift | 11 + .../libs/CryptoSwift/BlockMode/BlockMode.swift | 47 + .../CryptoSwift/BlockMode/BlockModeOptions.swift | 15 + .../CryptoSwift/BlockMode/BlockModeWorker.swift | 13 + .../libs/CryptoSwift/BlockMode/CBC.swift | 39 + .../libs/CryptoSwift/BlockMode/CFB.swift | 39 + .../libs/CryptoSwift/BlockMode/CTR.swift | 45 + .../libs/CryptoSwift/BlockMode/ECB.swift | 29 + .../libs/CryptoSwift/BlockMode/OFB.swift | 39 + .../libs/CryptoSwift/BlockMode/PCBC.swift | 39 + .../BlockMode/RandomAccessBlockModeWorker.swift | 11 + .../GeneralUtils/libs/CryptoSwift/Blowfish.swift | 506 ++++++ .../libs/CryptoSwift/BytesSequence.swift | 45 + .../libs/CryptoSwift/CSArrayType+Extensions.swift | 86 + .../GeneralUtils/libs/CryptoSwift/ChaCha20.swift | 343 ++++ .../GeneralUtils/libs/CryptoSwift/Checksum.swift | 122 ++ .../GeneralUtils/libs/CryptoSwift/Cipher.swift | 26 + .../libs/CryptoSwift/Collection+Extension.swift | 71 + .../GeneralUtils/libs/CryptoSwift/Cryptors.swift | 40 + .../GeneralUtils/libs/CryptoSwift/Digest.swift | 73 + .../GeneralUtils/libs/CryptoSwift/DigestType.swift | 11 + .../CryptoSwift/Foundation/AES+Foundation.swift | 20 + .../Foundation/Blowfish+Foundation.swift | 20 + .../Foundation/CSArrayType+Foundation.swift | 30 + .../Foundation/ChaCha20+Foundation.swift | 19 + .../CryptoSwift/Foundation/Data+Extension.swift | 82 + .../CryptoSwift/Foundation/HMAC+Foundation.swift | 20 + .../CryptoSwift/Foundation/Rabbit+Foundation.swift | 29 + .../Foundation/String+FoundationExtension.swift | 35 + .../CryptoSwift/Foundation/Utils+Foundation.swift | 20 + .../GeneralUtils/libs/CryptoSwift/Generics.swift | 55 + .../GeneralUtils/libs/CryptoSwift/HMAC.swift | 99 ++ .../libs/CryptoSwift/Int+Extension.swift | 43 + .../libs/CryptoSwift/IntegerConvertible.swift | 43 + .../GeneralUtils/libs/CryptoSwift/MD5.swift | 149 ++ .../GeneralUtils/libs/CryptoSwift/NoPadding.swift | 21 + .../libs/CryptoSwift/PKCS5/PBKDF1.swift | 84 + .../libs/CryptoSwift/PKCS5/PBKDF2.swift | 110 ++ .../libs/CryptoSwift/PKCS5/PKCS5.swift | 14 + .../GeneralUtils/libs/CryptoSwift/PKCS7.swift | 57 + .../GeneralUtils/libs/CryptoSwift/Padding.swift | 12 + .../GeneralUtils/libs/CryptoSwift/Poly1305.swift | 159 ++ .../GeneralUtils/libs/CryptoSwift/Rabbit.swift | 207 +++ .../libs/CryptoSwift/RandomAccessCryptor.swift | 17 + .../libs/CryptoSwift/RandomBytesSequence.swift | 43 + .../GeneralUtils/libs/CryptoSwift/SHA1.swift | 138 ++ .../GeneralUtils/libs/CryptoSwift/SHA2.swift | 331 ++++ .../GeneralUtils/libs/CryptoSwift/SHA3.swift | 281 ++++ .../libs/CryptoSwift/SecureBytes.swift | 68 + .../libs/CryptoSwift/String+Extension.swift | 61 + .../libs/CryptoSwift/UInt16+Extension.swift | 28 + .../libs/CryptoSwift/UInt32+Extension.swift | 39 + .../libs/CryptoSwift/UInt64+Extension.swift | 34 + .../libs/CryptoSwift/UInt8+Extension.swift | 71 + .../GeneralUtils/libs/CryptoSwift/Updatable.swift | 66 + .../GeneralUtils/libs/CryptoSwift/Utils.swift | 85 + .../libs/CryptoSwift/ZeroPadding.swift | 32 + .../libs/Kingfisher/AnimatedImageView.swift | 351 ++++ .../GeneralUtils/libs/Kingfisher/Box.swift | 16 + .../libs/Kingfisher/CacheSerializer.swift | 85 + .../GeneralUtils/libs/Kingfisher/Filter.swift | 145 ++ .../GeneralUtils/libs/Kingfisher/Image.swift | 938 +++++++++++ .../GeneralUtils/libs/Kingfisher/ImageCache.swift | 692 ++++++++ .../libs/Kingfisher/ImageDownloader.swift | 531 ++++++ .../libs/Kingfisher/ImagePrefetcher.swift | 267 +++ .../libs/Kingfisher/ImageProcessor.swift | 370 ++++ .../libs/Kingfisher/ImageTransition.swift | 128 ++ .../libs/Kingfisher/ImageView+Kingfisher.swift | 288 ++++ .../GeneralUtils/libs/Kingfisher/Indicator.swift | 191 +++ .../GeneralUtils/libs/Kingfisher/Kingfisher.h | 37 + .../GeneralUtils/libs/Kingfisher/Kingfisher.swift | 71 + .../libs/Kingfisher/KingfisherManager.swift | 213 +++ .../libs/Kingfisher/KingfisherOptionsInfo.swift | 285 ++++ .../libs/Kingfisher/RequestModifier.swift | 53 + .../GeneralUtils/libs/Kingfisher/Resource.swift | 74 + .../GeneralUtils/libs/Kingfisher/String+MD5.swift | 292 ++++ .../libs/Kingfisher/ThreadHelper.swift | 40 + .../libs/Kingfisher/UIButton+Kingfisher.swift | 407 +++++ .../ObjectMapper/CustomDateFormatTransform.swift | 40 + .../libs/ObjectMapper/DataTransform.swift | 50 + .../libs/ObjectMapper/DateFormatterTransform.swift | 54 + .../libs/ObjectMapper/DateTransform.swift | 55 + .../libs/ObjectMapper/DictionaryTransform.swift | 58 + .../libs/ObjectMapper/EnumOperators.swift | 91 + .../libs/ObjectMapper/EnumTransform.swift | 50 + .../GeneralUtils/libs/ObjectMapper/FromJSON.swift | 181 ++ .../libs/ObjectMapper/HexColorTransform.swift | 115 ++ .../libs/ObjectMapper/ISO8601DateTransform.swift | 41 + .../libs/ObjectMapper/ImmutableMappable.swift | 275 +++ .../GeneralUtils/libs/ObjectMapper/Map.swift | 181 ++ .../GeneralUtils/libs/ObjectMapper/MapError.swift | 68 + .../GeneralUtils/libs/ObjectMapper/Mappable.swift | 139 ++ .../GeneralUtils/libs/ObjectMapper/Mapper.swift | 433 +++++ .../ObjectMapper/NSDecimalNumberTransform.swift | 51 + .../GeneralUtils/libs/ObjectMapper/Operators.swift | 377 +++++ .../GeneralUtils/libs/ObjectMapper/ToJSON.swift | 179 ++ .../libs/ObjectMapper/TransformOf.swift | 48 + .../libs/ObjectMapper/TransformOperators.swift | 606 +++++++ .../libs/ObjectMapper/TransformType.swift | 35 + .../libs/ObjectMapper/URLTransform.swift | 65 + .../libs/SCLAlertView/SCLAlertView.swift | 1133 +++++++++++++ .../libs/SCLAlertView/SCLExtensions.swift | 41 + GeneralUtils/GeneralUtils/libs/SwiftOverlays.swift | 560 +++++++ GeneralUtils/GeneralUtils/libs/SwiftyJSON.swift | 1344 +++++++++++++++ GeneralUtils/GeneralUtils/libs/Toaster/Toast.swift | 169 ++ .../GeneralUtils/libs/Toaster/ToastCenter.swift | 75 + .../GeneralUtils/libs/Toaster/ToastView.swift | 187 +++ .../GeneralUtils/libs/Toaster/ToastWindow.swift | 154 ++ GeneralUtils/GeneralUtils/libs/Toaster/Toaster.h | 21 + GeneralUtils/GeneralUtils/models/Session.swift | 28 + .../ui/DrawerController/AnimatedMenuButton.swift | 139 ++ .../ui/DrawerController/DrawerBarButtonItem.swift | 61 + .../ui/DrawerController/DrawerController.h | 19 + .../ui/DrawerController/DrawerController.swift | 1546 +++++++++++++++++ .../ui/DrawerController/DrawerVisualState.swift | 193 +++ .../DrawerVisualStateManager.swift | 96 ++ .../GeneralUtils/ui/GeneralMenuController.swift | 34 + .../GeneralUtils/ui/IContainerController.swift | 77 + .../AnimatedControllerFromBottom.swift | 75 + .../PresentationDialog/AnimatedTransitioning.swift | 80 + .../BaseUIPresentationController.swift | 114 ++ .../BaseViewControllerShowTransculent.swift | 109 ++ GeneralUtils/GeneralUtils/ui/VCContainer.swift | 32 + .../ui/page/BasePageViewController.swift | 123 ++ .../CollectionView/UICollectionViewLoadData.swift | 220 +++ .../CollectionView/UICollectionViewLoading.swift | 73 + .../GeneralUtils/ui/views/DropDown/ComboBox.swift | 109 ++ .../ui/views/DropDown/DPDConstants.swift | 54 + .../ui/views/DropDown/DPDKeyboardListener.swift | 68 + .../ui/views/DropDown/DPDUIView+Extension.swift | 57 + .../GeneralUtils/ui/views/DropDown/DropDown.swift | 794 +++++++++ .../ui/views/DropDown/DropDownCell.swift | 70 + .../GeneralUtils/ui/views/FloatRatingView.swift | 310 ++++ .../GeneralUtils/ui/views/ISRadioButton.swift | 369 ++++ .../GeneralUtils/ui/views/TableView/BaseCell.swift | 46 + .../ui/views/TableView/BaseTbLoadData.swift | 137 ++ .../ui/views/TableView/CellLoadMore.swift | 46 + .../ui/views/TableView/UITableViewLoadDataBg.swift | 95 ++ .../UITableViewLoadDataFromUIThread.swift | 85 + .../ui/views/TableView/UITableViewLoadMore.swift | 114 ++ .../ui/views/TableView/UITableViewLoading.swift | 98 ++ .../GeneralUtils/ui/views/UIButtonCustom.swift | 129 ++ .../GeneralUtils/ui/views/UIImageViewCustom.swift | 25 + .../GeneralUtils/ui/views/UILabelCustom.swift | 123 ++ .../ui/views/UILableCustomLeftImage.swift | 86 + .../GeneralUtils/ui/views/UITextViewCustom.swift | 25 + .../GeneralUtils/ui/views/UIViewCustom.swift | 94 ++ .../ui/views/UIViewCustomGradientBg.swift | 37 + .../ui/views/UIViewCustomPressHightLight.swift | 19 + .../GeneralUtils/ui/views/VPlayerControl.swift | 172 ++ .../views/VTopNotification/VTopNotification.swift | 45 + .../ui/views/VTopNotification/VTopNotification.xib | 68 + .../GeneralUtils/ui/views/vTopBar/ViewTopBar.swift | 196 +++ .../GeneralUtils/ui/views/vTopBar/ViewTopBar.xib | 81 + GeneralUtils/LICENSE | 21 + GeneralUtils/readme.txt | 10 + Morooka.xcodeproj/project.pbxproj | 150 +- .../UserInterfaceState.xcuserstate | Bin 40506 -> 31059 bytes .../xcschemes/xcschememanagement.plist | 2 +- Morooka.xcworkspace/contents.xcworkspacedata | 10 + .../xcshareddata/Morooka.xcscmblueprint | 30 + .../UserInterfaceState.xcuserstate | Bin 0 -> 12286 bytes .../xcschemes/xcschememanagement.plist | 5 + Podfile | 10 + Podfile.lock | 12 + Pods/Alamofire/LICENSE | 19 + Pods/Alamofire/README.md | 1764 ++++++++++++++++++++ Pods/Alamofire/Source/AFError.swift | 460 +++++ Pods/Alamofire/Source/Alamofire.swift | 465 ++++++ .../Alamofire/Source/DispatchQueue+Alamofire.swift | 37 + Pods/Alamofire/Source/MultipartFormData.swift | 581 +++++++ .../Source/NetworkReachabilityManager.swift | 230 +++ Pods/Alamofire/Source/Notifications.swift | 52 + Pods/Alamofire/Source/ParameterEncoding.swift | 433 +++++ Pods/Alamofire/Source/Request.swift | 647 +++++++ Pods/Alamofire/Source/Response.swift | 345 ++++ Pods/Alamofire/Source/ResponseSerialization.swift | 714 ++++++++ Pods/Alamofire/Source/Result.swift | 102 ++ Pods/Alamofire/Source/ServerTrustPolicy.swift | 307 ++++ Pods/Alamofire/Source/SessionDelegate.swift | 721 ++++++++ Pods/Alamofire/Source/SessionManager.swift | 891 ++++++++++ Pods/Alamofire/Source/TaskDelegate.swift | 453 +++++ Pods/Alamofire/Source/Timeline.swift | 136 ++ Pods/Alamofire/Source/Validation.swift | 309 ++++ Pods/Manifest.lock | 12 + Pods/Pods.xcodeproj/project.pbxproj | 598 +++++++ .../ptran.xcuserdatad/xcschemes/Alamofire.xcscheme | 60 + .../ptran.xcuserdatad/xcschemes/Pods-App.xcscheme | 71 + .../xcschemes/xcschememanagement.plist | 36 + .../Alamofire/Alamofire-dummy.m | 5 + .../Alamofire/Alamofire-prefix.pch | 12 + .../Alamofire/Alamofire-umbrella.h | 16 + .../Alamofire/Alamofire.modulemap | 6 + .../Alamofire/Alamofire.xcconfig | 10 + Pods/Target Support Files/Alamofire/Info.plist | 26 + Pods/Target Support Files/Pods-App/Info.plist | 26 + .../Pods-App/Pods-App-acknowledgements.markdown | 26 + .../Pods-App/Pods-App-acknowledgements.plist | 58 + .../Target Support Files/Pods-App/Pods-App-dummy.m | 5 + .../Pods-App/Pods-App-frameworks.sh | 99 ++ .../Pods-App/Pods-App-resources.sh | 99 ++ .../Pods-App/Pods-App-umbrella.h | 16 + .../Pods-App/Pods-App.debug.xcconfig | 10 + .../Pods-App/Pods-App.modulemap | 6 + .../Pods-App/Pods-App.release.xcconfig | 10 + 275 files changed, 38888 insertions(+), 127 deletions(-) delete mode 100644 App/model/MucChup.swift create mode 100644 App/model/ShootItem.swift create mode 100644 App/utils/Constants.swift create mode 100644 App/utils/FileUpload.swift create mode 100644 App/utils/NetWorkUtils.swift create mode 100644 GeneralUtils/.idea/GeneralUtils.iml create mode 100644 GeneralUtils/.idea/encodings.xml create mode 100644 GeneralUtils/.idea/inspectionProfiles/Project_Default.xml create mode 100644 GeneralUtils/.idea/misc.xml create mode 100644 GeneralUtils/.idea/modules.xml create mode 100644 GeneralUtils/.idea/vcs.xml create mode 100644 GeneralUtils/.idea/workspace.xml create mode 100644 GeneralUtils/.idea/xcode.xml create mode 100644 GeneralUtils/GeneralUtils.podspec create mode 100644 GeneralUtils/GeneralUtils.xcodeproj/project.pbxproj create mode 100644 GeneralUtils/GeneralUtils.xcodeproj/project.xcworkspace/contents.xcworkspacedata create mode 100644 GeneralUtils/GeneralUtils.xcodeproj/project.xcworkspace/xcuserdata/ptran.xcuserdatad/UserInterfaceState.xcuserstate create mode 100644 GeneralUtils/GeneralUtils.xcodeproj/project.xcworkspace/xcuserdata/ptran.xcuserdatad/xcschemes/xcschememanagement.plist create mode 100644 GeneralUtils/GeneralUtils.xcodeproj/xcuserdata/ptran.xcuserdatad/xcschemes/GeneralUtils.xcscheme create mode 100644 GeneralUtils/GeneralUtils.xcodeproj/xcuserdata/ptran.xcuserdatad/xcschemes/xcschememanagement.plist create mode 100644 GeneralUtils/GeneralUtils/Assets.xcassets/ic_arrow_back_black.imageset/Contents.json create mode 100644 GeneralUtils/GeneralUtils/Assets.xcassets/ic_arrow_back_black.imageset/ic_arrow_back_36pt.png create mode 100644 GeneralUtils/GeneralUtils/Assets.xcassets/ic_arrow_back_black.imageset/ic_arrow_back_36pt_2x.png create mode 100644 GeneralUtils/GeneralUtils/Assets.xcassets/ic_arrow_back_black.imageset/ic_arrow_back_36pt_3x.png create mode 100644 GeneralUtils/GeneralUtils/Assets.xcassets/ic_arrow_drop_down.imageset/Contents.json create mode 100644 GeneralUtils/GeneralUtils/Assets.xcassets/ic_arrow_drop_down.imageset/ic_arrow_drop_down.png create mode 100644 GeneralUtils/GeneralUtils/Assets.xcassets/placeholder.imageset/Contents.json create mode 100644 GeneralUtils/GeneralUtils/Assets.xcassets/placeholder.imageset/placeholder.png create mode 100644 GeneralUtils/GeneralUtils/Assets.xcassets/placeholder.imageset/placeholder@2x.png create mode 100644 GeneralUtils/GeneralUtils/Assets.xcassets/placeholder.imageset/placeholder@3x.png create mode 100644 GeneralUtils/GeneralUtils/Assets.xcassets/press.imageset/Contents.json create mode 100644 GeneralUtils/GeneralUtils/Assets.xcassets/press.imageset/press.png create mode 100644 GeneralUtils/GeneralUtils/GeneralUtils.h create mode 100644 GeneralUtils/GeneralUtils/Info.plist create mode 100644 GeneralUtils/GeneralUtils/commonUtils/CacheUtils.swift create mode 100644 GeneralUtils/GeneralUtils/commonUtils/CommonExtension.swift create mode 100644 GeneralUtils/GeneralUtils/commonUtils/CommonUtils.swift create mode 100644 GeneralUtils/GeneralUtils/commonUtils/DataTypeUtils.swift create mode 100644 GeneralUtils/GeneralUtils/commonUtils/DialogUtils.swift create mode 100644 GeneralUtils/GeneralUtils/commonUtils/DownloadTask.swift create mode 100644 GeneralUtils/GeneralUtils/commonUtils/FileUtils.swift create mode 100644 GeneralUtils/GeneralUtils/commonUtils/NetWorkUtils.swift create mode 100644 GeneralUtils/GeneralUtils/commonUtils/PreferenceUtils.swift create mode 100644 GeneralUtils/GeneralUtils/commonUtils/Queue.swift create mode 100644 GeneralUtils/GeneralUtils/commonUtils/RecordUtils.swift create mode 100644 GeneralUtils/GeneralUtils/commonUtils/SecurityUtils.swift create mode 100644 GeneralUtils/GeneralUtils/commonUtils/StringExtension.swift create mode 100644 GeneralUtils/GeneralUtils/libs/CryptoSwift/AES.swift create mode 100644 GeneralUtils/GeneralUtils/libs/CryptoSwift/Array+Extension.swift create mode 100644 GeneralUtils/GeneralUtils/libs/CryptoSwift/Authenticator.swift create mode 100644 GeneralUtils/GeneralUtils/libs/CryptoSwift/Bit.swift create mode 100644 GeneralUtils/GeneralUtils/libs/CryptoSwift/BlockCipher.swift create mode 100644 GeneralUtils/GeneralUtils/libs/CryptoSwift/BlockMode/BlockMode.swift create mode 100644 GeneralUtils/GeneralUtils/libs/CryptoSwift/BlockMode/BlockModeOptions.swift create mode 100644 GeneralUtils/GeneralUtils/libs/CryptoSwift/BlockMode/BlockModeWorker.swift create mode 100644 GeneralUtils/GeneralUtils/libs/CryptoSwift/BlockMode/CBC.swift create mode 100644 GeneralUtils/GeneralUtils/libs/CryptoSwift/BlockMode/CFB.swift create mode 100644 GeneralUtils/GeneralUtils/libs/CryptoSwift/BlockMode/CTR.swift create mode 100644 GeneralUtils/GeneralUtils/libs/CryptoSwift/BlockMode/ECB.swift create mode 100644 GeneralUtils/GeneralUtils/libs/CryptoSwift/BlockMode/OFB.swift create mode 100644 GeneralUtils/GeneralUtils/libs/CryptoSwift/BlockMode/PCBC.swift create mode 100644 GeneralUtils/GeneralUtils/libs/CryptoSwift/BlockMode/RandomAccessBlockModeWorker.swift create mode 100644 GeneralUtils/GeneralUtils/libs/CryptoSwift/Blowfish.swift create mode 100644 GeneralUtils/GeneralUtils/libs/CryptoSwift/BytesSequence.swift create mode 100644 GeneralUtils/GeneralUtils/libs/CryptoSwift/CSArrayType+Extensions.swift create mode 100644 GeneralUtils/GeneralUtils/libs/CryptoSwift/ChaCha20.swift create mode 100644 GeneralUtils/GeneralUtils/libs/CryptoSwift/Checksum.swift create mode 100644 GeneralUtils/GeneralUtils/libs/CryptoSwift/Cipher.swift create mode 100644 GeneralUtils/GeneralUtils/libs/CryptoSwift/Collection+Extension.swift create mode 100644 GeneralUtils/GeneralUtils/libs/CryptoSwift/Cryptors.swift create mode 100644 GeneralUtils/GeneralUtils/libs/CryptoSwift/Digest.swift create mode 100644 GeneralUtils/GeneralUtils/libs/CryptoSwift/DigestType.swift create mode 100644 GeneralUtils/GeneralUtils/libs/CryptoSwift/Foundation/AES+Foundation.swift create mode 100644 GeneralUtils/GeneralUtils/libs/CryptoSwift/Foundation/Blowfish+Foundation.swift create mode 100644 GeneralUtils/GeneralUtils/libs/CryptoSwift/Foundation/CSArrayType+Foundation.swift create mode 100644 GeneralUtils/GeneralUtils/libs/CryptoSwift/Foundation/ChaCha20+Foundation.swift create mode 100644 GeneralUtils/GeneralUtils/libs/CryptoSwift/Foundation/Data+Extension.swift create mode 100644 GeneralUtils/GeneralUtils/libs/CryptoSwift/Foundation/HMAC+Foundation.swift create mode 100644 GeneralUtils/GeneralUtils/libs/CryptoSwift/Foundation/Rabbit+Foundation.swift create mode 100644 GeneralUtils/GeneralUtils/libs/CryptoSwift/Foundation/String+FoundationExtension.swift create mode 100644 GeneralUtils/GeneralUtils/libs/CryptoSwift/Foundation/Utils+Foundation.swift create mode 100644 GeneralUtils/GeneralUtils/libs/CryptoSwift/Generics.swift create mode 100644 GeneralUtils/GeneralUtils/libs/CryptoSwift/HMAC.swift create mode 100644 GeneralUtils/GeneralUtils/libs/CryptoSwift/Int+Extension.swift create mode 100644 GeneralUtils/GeneralUtils/libs/CryptoSwift/IntegerConvertible.swift create mode 100644 GeneralUtils/GeneralUtils/libs/CryptoSwift/MD5.swift create mode 100644 GeneralUtils/GeneralUtils/libs/CryptoSwift/NoPadding.swift create mode 100644 GeneralUtils/GeneralUtils/libs/CryptoSwift/PKCS5/PBKDF1.swift create mode 100644 GeneralUtils/GeneralUtils/libs/CryptoSwift/PKCS5/PBKDF2.swift create mode 100644 GeneralUtils/GeneralUtils/libs/CryptoSwift/PKCS5/PKCS5.swift create mode 100644 GeneralUtils/GeneralUtils/libs/CryptoSwift/PKCS7.swift create mode 100644 GeneralUtils/GeneralUtils/libs/CryptoSwift/Padding.swift create mode 100644 GeneralUtils/GeneralUtils/libs/CryptoSwift/Poly1305.swift create mode 100644 GeneralUtils/GeneralUtils/libs/CryptoSwift/Rabbit.swift create mode 100644 GeneralUtils/GeneralUtils/libs/CryptoSwift/RandomAccessCryptor.swift create mode 100644 GeneralUtils/GeneralUtils/libs/CryptoSwift/RandomBytesSequence.swift create mode 100644 GeneralUtils/GeneralUtils/libs/CryptoSwift/SHA1.swift create mode 100644 GeneralUtils/GeneralUtils/libs/CryptoSwift/SHA2.swift create mode 100644 GeneralUtils/GeneralUtils/libs/CryptoSwift/SHA3.swift create mode 100644 GeneralUtils/GeneralUtils/libs/CryptoSwift/SecureBytes.swift create mode 100644 GeneralUtils/GeneralUtils/libs/CryptoSwift/String+Extension.swift create mode 100644 GeneralUtils/GeneralUtils/libs/CryptoSwift/UInt16+Extension.swift create mode 100644 GeneralUtils/GeneralUtils/libs/CryptoSwift/UInt32+Extension.swift create mode 100644 GeneralUtils/GeneralUtils/libs/CryptoSwift/UInt64+Extension.swift create mode 100644 GeneralUtils/GeneralUtils/libs/CryptoSwift/UInt8+Extension.swift create mode 100644 GeneralUtils/GeneralUtils/libs/CryptoSwift/Updatable.swift create mode 100644 GeneralUtils/GeneralUtils/libs/CryptoSwift/Utils.swift create mode 100644 GeneralUtils/GeneralUtils/libs/CryptoSwift/ZeroPadding.swift create mode 100755 GeneralUtils/GeneralUtils/libs/Kingfisher/AnimatedImageView.swift create mode 100644 GeneralUtils/GeneralUtils/libs/Kingfisher/Box.swift create mode 100644 GeneralUtils/GeneralUtils/libs/Kingfisher/CacheSerializer.swift create mode 100644 GeneralUtils/GeneralUtils/libs/Kingfisher/Filter.swift create mode 100755 GeneralUtils/GeneralUtils/libs/Kingfisher/Image.swift create mode 100755 GeneralUtils/GeneralUtils/libs/Kingfisher/ImageCache.swift create mode 100755 GeneralUtils/GeneralUtils/libs/Kingfisher/ImageDownloader.swift create mode 100755 GeneralUtils/GeneralUtils/libs/Kingfisher/ImagePrefetcher.swift create mode 100644 GeneralUtils/GeneralUtils/libs/Kingfisher/ImageProcessor.swift create mode 100755 GeneralUtils/GeneralUtils/libs/Kingfisher/ImageTransition.swift create mode 100755 GeneralUtils/GeneralUtils/libs/Kingfisher/ImageView+Kingfisher.swift create mode 100644 GeneralUtils/GeneralUtils/libs/Kingfisher/Indicator.swift create mode 100644 GeneralUtils/GeneralUtils/libs/Kingfisher/Kingfisher.h create mode 100644 GeneralUtils/GeneralUtils/libs/Kingfisher/Kingfisher.swift create mode 100755 GeneralUtils/GeneralUtils/libs/Kingfisher/KingfisherManager.swift create mode 100755 GeneralUtils/GeneralUtils/libs/Kingfisher/KingfisherOptionsInfo.swift create mode 100644 GeneralUtils/GeneralUtils/libs/Kingfisher/RequestModifier.swift create mode 100755 GeneralUtils/GeneralUtils/libs/Kingfisher/Resource.swift create mode 100755 GeneralUtils/GeneralUtils/libs/Kingfisher/String+MD5.swift create mode 100755 GeneralUtils/GeneralUtils/libs/Kingfisher/ThreadHelper.swift create mode 100755 GeneralUtils/GeneralUtils/libs/Kingfisher/UIButton+Kingfisher.swift create mode 100644 GeneralUtils/GeneralUtils/libs/ObjectMapper/CustomDateFormatTransform.swift create mode 100644 GeneralUtils/GeneralUtils/libs/ObjectMapper/DataTransform.swift create mode 100644 GeneralUtils/GeneralUtils/libs/ObjectMapper/DateFormatterTransform.swift create mode 100644 GeneralUtils/GeneralUtils/libs/ObjectMapper/DateTransform.swift create mode 100644 GeneralUtils/GeneralUtils/libs/ObjectMapper/DictionaryTransform.swift create mode 100644 GeneralUtils/GeneralUtils/libs/ObjectMapper/EnumOperators.swift create mode 100644 GeneralUtils/GeneralUtils/libs/ObjectMapper/EnumTransform.swift create mode 100644 GeneralUtils/GeneralUtils/libs/ObjectMapper/FromJSON.swift create mode 100644 GeneralUtils/GeneralUtils/libs/ObjectMapper/HexColorTransform.swift create mode 100644 GeneralUtils/GeneralUtils/libs/ObjectMapper/ISO8601DateTransform.swift create mode 100644 GeneralUtils/GeneralUtils/libs/ObjectMapper/ImmutableMappable.swift create mode 100644 GeneralUtils/GeneralUtils/libs/ObjectMapper/Map.swift create mode 100644 GeneralUtils/GeneralUtils/libs/ObjectMapper/MapError.swift create mode 100644 GeneralUtils/GeneralUtils/libs/ObjectMapper/Mappable.swift create mode 100644 GeneralUtils/GeneralUtils/libs/ObjectMapper/Mapper.swift create mode 100644 GeneralUtils/GeneralUtils/libs/ObjectMapper/NSDecimalNumberTransform.swift create mode 100644 GeneralUtils/GeneralUtils/libs/ObjectMapper/Operators.swift create mode 100644 GeneralUtils/GeneralUtils/libs/ObjectMapper/ToJSON.swift create mode 100644 GeneralUtils/GeneralUtils/libs/ObjectMapper/TransformOf.swift create mode 100644 GeneralUtils/GeneralUtils/libs/ObjectMapper/TransformOperators.swift create mode 100644 GeneralUtils/GeneralUtils/libs/ObjectMapper/TransformType.swift create mode 100644 GeneralUtils/GeneralUtils/libs/ObjectMapper/URLTransform.swift create mode 100644 GeneralUtils/GeneralUtils/libs/SCLAlertView/SCLAlertView.swift create mode 100644 GeneralUtils/GeneralUtils/libs/SCLAlertView/SCLExtensions.swift create mode 100644 GeneralUtils/GeneralUtils/libs/SwiftOverlays.swift create mode 100644 GeneralUtils/GeneralUtils/libs/SwiftyJSON.swift create mode 100644 GeneralUtils/GeneralUtils/libs/Toaster/Toast.swift create mode 100644 GeneralUtils/GeneralUtils/libs/Toaster/ToastCenter.swift create mode 100644 GeneralUtils/GeneralUtils/libs/Toaster/ToastView.swift create mode 100644 GeneralUtils/GeneralUtils/libs/Toaster/ToastWindow.swift create mode 100644 GeneralUtils/GeneralUtils/libs/Toaster/Toaster.h create mode 100644 GeneralUtils/GeneralUtils/models/Session.swift create mode 100644 GeneralUtils/GeneralUtils/ui/DrawerController/AnimatedMenuButton.swift create mode 100644 GeneralUtils/GeneralUtils/ui/DrawerController/DrawerBarButtonItem.swift create mode 100644 GeneralUtils/GeneralUtils/ui/DrawerController/DrawerController.h create mode 100644 GeneralUtils/GeneralUtils/ui/DrawerController/DrawerController.swift create mode 100644 GeneralUtils/GeneralUtils/ui/DrawerController/DrawerVisualState.swift create mode 100644 GeneralUtils/GeneralUtils/ui/DrawerController/DrawerVisualStateManager.swift create mode 100644 GeneralUtils/GeneralUtils/ui/GeneralMenuController.swift create mode 100644 GeneralUtils/GeneralUtils/ui/IContainerController.swift create mode 100644 GeneralUtils/GeneralUtils/ui/PresentationDialog/AnimatedControllerFromBottom.swift create mode 100644 GeneralUtils/GeneralUtils/ui/PresentationDialog/AnimatedTransitioning.swift create mode 100644 GeneralUtils/GeneralUtils/ui/PresentationDialog/BaseUIPresentationController.swift create mode 100644 GeneralUtils/GeneralUtils/ui/PresentationDialog/BaseViewControllerShowTransculent.swift create mode 100644 GeneralUtils/GeneralUtils/ui/VCContainer.swift create mode 100644 GeneralUtils/GeneralUtils/ui/page/BasePageViewController.swift create mode 100644 GeneralUtils/GeneralUtils/ui/views/CollectionView/UICollectionViewLoadData.swift create mode 100644 GeneralUtils/GeneralUtils/ui/views/CollectionView/UICollectionViewLoading.swift create mode 100644 GeneralUtils/GeneralUtils/ui/views/DropDown/ComboBox.swift create mode 100644 GeneralUtils/GeneralUtils/ui/views/DropDown/DPDConstants.swift create mode 100644 GeneralUtils/GeneralUtils/ui/views/DropDown/DPDKeyboardListener.swift create mode 100644 GeneralUtils/GeneralUtils/ui/views/DropDown/DPDUIView+Extension.swift create mode 100644 GeneralUtils/GeneralUtils/ui/views/DropDown/DropDown.swift create mode 100644 GeneralUtils/GeneralUtils/ui/views/DropDown/DropDownCell.swift create mode 100644 GeneralUtils/GeneralUtils/ui/views/FloatRatingView.swift create mode 100644 GeneralUtils/GeneralUtils/ui/views/ISRadioButton.swift create mode 100644 GeneralUtils/GeneralUtils/ui/views/TableView/BaseCell.swift create mode 100644 GeneralUtils/GeneralUtils/ui/views/TableView/BaseTbLoadData.swift create mode 100644 GeneralUtils/GeneralUtils/ui/views/TableView/CellLoadMore.swift create mode 100644 GeneralUtils/GeneralUtils/ui/views/TableView/UITableViewLoadDataBg.swift create mode 100644 GeneralUtils/GeneralUtils/ui/views/TableView/UITableViewLoadDataFromUIThread.swift create mode 100644 GeneralUtils/GeneralUtils/ui/views/TableView/UITableViewLoadMore.swift create mode 100644 GeneralUtils/GeneralUtils/ui/views/TableView/UITableViewLoading.swift create mode 100644 GeneralUtils/GeneralUtils/ui/views/UIButtonCustom.swift create mode 100644 GeneralUtils/GeneralUtils/ui/views/UIImageViewCustom.swift create mode 100644 GeneralUtils/GeneralUtils/ui/views/UILabelCustom.swift create mode 100644 GeneralUtils/GeneralUtils/ui/views/UILableCustomLeftImage.swift create mode 100644 GeneralUtils/GeneralUtils/ui/views/UITextViewCustom.swift create mode 100644 GeneralUtils/GeneralUtils/ui/views/UIViewCustom.swift create mode 100644 GeneralUtils/GeneralUtils/ui/views/UIViewCustomGradientBg.swift create mode 100644 GeneralUtils/GeneralUtils/ui/views/UIViewCustomPressHightLight.swift create mode 100644 GeneralUtils/GeneralUtils/ui/views/VPlayerControl.swift create mode 100644 GeneralUtils/GeneralUtils/ui/views/VTopNotification/VTopNotification.swift create mode 100644 GeneralUtils/GeneralUtils/ui/views/VTopNotification/VTopNotification.xib create mode 100644 GeneralUtils/GeneralUtils/ui/views/vTopBar/ViewTopBar.swift create mode 100644 GeneralUtils/GeneralUtils/ui/views/vTopBar/ViewTopBar.xib create mode 100644 GeneralUtils/LICENSE create mode 100644 GeneralUtils/readme.txt create mode 100644 Morooka.xcworkspace/contents.xcworkspacedata create mode 100644 Morooka.xcworkspace/xcshareddata/Morooka.xcscmblueprint create mode 100644 Morooka.xcworkspace/xcuserdata/ptran.xcuserdatad/UserInterfaceState.xcuserstate create mode 100644 Morooka.xcworkspace/xcuserdata/ptran.xcuserdatad/xcschemes/xcschememanagement.plist create mode 100644 Podfile create mode 100644 Podfile.lock create mode 100644 Pods/Alamofire/LICENSE create mode 100644 Pods/Alamofire/README.md create mode 100644 Pods/Alamofire/Source/AFError.swift create mode 100644 Pods/Alamofire/Source/Alamofire.swift create mode 100644 Pods/Alamofire/Source/DispatchQueue+Alamofire.swift create mode 100644 Pods/Alamofire/Source/MultipartFormData.swift create mode 100644 Pods/Alamofire/Source/NetworkReachabilityManager.swift create mode 100644 Pods/Alamofire/Source/Notifications.swift create mode 100644 Pods/Alamofire/Source/ParameterEncoding.swift create mode 100644 Pods/Alamofire/Source/Request.swift create mode 100644 Pods/Alamofire/Source/Response.swift create mode 100644 Pods/Alamofire/Source/ResponseSerialization.swift create mode 100644 Pods/Alamofire/Source/Result.swift create mode 100644 Pods/Alamofire/Source/ServerTrustPolicy.swift create mode 100644 Pods/Alamofire/Source/SessionDelegate.swift create mode 100644 Pods/Alamofire/Source/SessionManager.swift create mode 100644 Pods/Alamofire/Source/TaskDelegate.swift create mode 100644 Pods/Alamofire/Source/Timeline.swift create mode 100644 Pods/Alamofire/Source/Validation.swift create mode 100644 Pods/Manifest.lock create mode 100644 Pods/Pods.xcodeproj/project.pbxproj create mode 100644 Pods/Pods.xcodeproj/xcuserdata/ptran.xcuserdatad/xcschemes/Alamofire.xcscheme create mode 100644 Pods/Pods.xcodeproj/xcuserdata/ptran.xcuserdatad/xcschemes/Pods-App.xcscheme create mode 100644 Pods/Pods.xcodeproj/xcuserdata/ptran.xcuserdatad/xcschemes/xcschememanagement.plist create mode 100644 Pods/Target Support Files/Alamofire/Alamofire-dummy.m create mode 100644 Pods/Target Support Files/Alamofire/Alamofire-prefix.pch create mode 100644 Pods/Target Support Files/Alamofire/Alamofire-umbrella.h create mode 100644 Pods/Target Support Files/Alamofire/Alamofire.modulemap create mode 100644 Pods/Target Support Files/Alamofire/Alamofire.xcconfig create mode 100644 Pods/Target Support Files/Alamofire/Info.plist create mode 100644 Pods/Target Support Files/Pods-App/Info.plist create mode 100644 Pods/Target Support Files/Pods-App/Pods-App-acknowledgements.markdown create mode 100644 Pods/Target Support Files/Pods-App/Pods-App-acknowledgements.plist create mode 100644 Pods/Target Support Files/Pods-App/Pods-App-dummy.m create mode 100755 Pods/Target Support Files/Pods-App/Pods-App-frameworks.sh create mode 100755 Pods/Target Support Files/Pods-App/Pods-App-resources.sh create mode 100644 Pods/Target Support Files/Pods-App/Pods-App-umbrella.h create mode 100644 Pods/Target Support Files/Pods-App/Pods-App.debug.xcconfig create mode 100644 Pods/Target Support Files/Pods-App/Pods-App.modulemap create mode 100644 Pods/Target Support Files/Pods-App/Pods-App.release.xcconfig diff --git a/.idea/xcode.xml b/.idea/xcode.xml index e3905c7..46d81b7 100644 --- a/.idea/xcode.xml +++ b/.idea/xcode.xml @@ -1,4 +1,4 @@ - + \ No newline at end of file diff --git a/App/Base.lproj/Main.storyboard b/App/Base.lproj/Main.storyboard index 9a2e0c6..badcc7d 100644 --- a/App/Base.lproj/Main.storyboard +++ b/App/Base.lproj/Main.storyboard @@ -1435,6 +1435,9 @@ + + + @@ -1464,6 +1467,7 @@ + @@ -1740,6 +1744,7 @@ + diff --git a/App/Localizable.strings b/App/Localizable.strings index e038c87..3d61a4b 100644 --- a/App/Localizable.strings +++ b/App/Localizable.strings @@ -1,5 +1,5 @@ -khong_de_trong = "Không được để trống"; -muc_chup_da_ton_tai = "Mục chụp đã tồn tại"; +khong_de_trong = "Can not be empty"; +muc_chup_da_ton_tai = "existed"; empty_muc_chup = "No item for Shooting"; //co_luu_anh_khong = "Sau khi chụp và sau khi đã chọn ảnh từ list sẽ hiển thị pop up có lưu ảnh không?"; @@ -7,7 +7,11 @@ empty_muc_chup = "No item for Shooting"; //no = "no"; co_chup_lai_khong = "bạn có muốn chụp lại không?"; "OK"= "OK"; +"Loading"= "Loading"; +"Uploading" = "Uploading"; "list_empty"= "Empty"; +"successful"= "successful"; +"Has_Error_occurred" = "Error has occurred, please check internet connection and try again."; //Camera ======= diff --git a/App/addPerson/VCConfirmId.swift b/App/addPerson/VCConfirmId.swift index bb6d33d..660a9ea 100644 --- a/App/addPerson/VCConfirmId.swift +++ b/App/addPerson/VCConfirmId.swift @@ -5,30 +5,35 @@ class VCConfirmId: UIViewController { @IBOutlet weak var topMargin: NSLayoutConstraint! @IBOutlet weak var vTopLogo: VTopLogo! + weak var vcHome: VCHome? + static func openController(_ viewController: UIViewController) { let storyboard: UIStoryboard = UIStoryboard(name: "Main", bundle: nil) let vcOpen = storyboard.instantiateViewController(withIdentifier: "VCConfirmId") as! VCConfirmId + vcOpen.vcHome = viewController as? VCHome viewController.present(vcOpen, animated: true, completion: nil) } + override func viewDidLoad() { + super.viewDidLoad() + vTopLogo.leftBtnClick = { self.dismiss(animated: true) } + edtTitle.text = getIDWork() + } @IBAction func btnLeftClick(_ sender: Any) { dismiss(animated: true) } @IBAction func btnRightClick(_ sender: Any) { + dismiss(animated: true) + self.vcHome?.getVcRoot()?.changeCurrentController(VCInputId.getInstance()) } @IBAction func edtActionTrigerClick(_ sender: Any) { edtTitle.endEditing(true) } - - override func viewDidDisappear(_ animated: Bool) { - super.viewDidDisappear(animated) - } - - override var prefersStatusBarHidden : Bool { + override var prefersStatusBarHidden: Bool { return true } } diff --git a/App/commons/CellMucChupWithCamera.swift b/App/commons/CellMucChupWithCamera.swift index 882721e..e33b98d 100644 --- a/App/commons/CellMucChupWithCamera.swift +++ b/App/commons/CellMucChupWithCamera.swift @@ -1,10 +1,11 @@ import Foundation import UIKit import GeneralUtils +import Alamofire class CellMucChupWithCamera: BaseTableViewCellUI { var tvTitle: UILabel!, imv: UIImageView! - var mucChup: ShootItem! + var shootItem: ShootItem! static func registerClass(tableView: UITableView, forCellReuseIdentifier: String) { tableView.register(CellMucChupWithCamera.self, forCellReuseIdentifier: forCellReuseIdentifier) @@ -50,30 +51,22 @@ class CellMucChupWithCamera: BaseTableViewCellUI { func titleClick() { guard let viewController = self.viewController else { return } if viewController is VCConfirmMucDaChon { return } - var imgObjs = [ImgObj]() - var imgObj = ImgObj() - imgObj.url = "http://thosonnha.nhq.vn/wp-content/uploads/2015/05/son-lot-tuong.jpg" - imgObjs.append(imgObj) - - imgObj = ImgObj() - imgObj.url = "http://media.vietq.vn/files/meo-tay-vet-ban-tren-tuong-1.jpg" - imgObjs.append(imgObj) - - imgObj = ImgObj() - imgObj.url = "http://file1.batdongsan.com.vn/file.396375.jpg" - imgObjs.append(imgObj) - - VCPageImgs.openController(viewController, imgObjs: imgObjs) + if let imgs = shootItem.imgs, imgs.count > 0 { + VCPageImgs.openController(viewController, imgObjs: imgs) + } } func btnImvClick() { guard let viewController = self.viewController else { return } if viewController is VCConfirmMucDaChon { return } - let cameraViewController = CameraViewController(croppingEnabled: false, allowsLibraryAccess: true) { [weak viewController, weak self] image, asset in - viewController?.dismiss(animated: true, completion: nil) + let cameraViewController = CameraViewController(croppingEnabled: false, allowsLibraryAccess: true) { image, asset in + viewController.dismiss(animated: true, completion: nil) guard let image = image else { return } - self?.imv?.image = image - //TODO save image + self.imv?.image = image + guard let id = self.shootItem.id, let data = UIImageJPEGRepresentation(image, 1.0) else { return } + let signboard = self.shootItem?.signboard ?? 1 + + self.uploadImage(id: id, signboard: signboard, data: data) } viewController.present(cameraViewController, animated: true, completion: nil) @@ -81,7 +74,54 @@ class CellMucChupWithCamera: BaseTableViewCellUI { override func configCellWithData(baseObj: Any, index: Int) { super.configCellWithData(baseObj: baseObj, index: index) - mucChup = baseObj as! ShootItem - tvTitle.text = mucChup.name + shootItem = baseObj as! ShootItem + tvTitle.text = shootItem.name + if let imgs = shootItem.imgs, imgs.count > 0, let imgUrl = imgs[0].url { + setImageUrl(imv: imv, imageUrl: imgUrl) + } else { + imv.image = #imageLiteral(resourceName:"camera_black_ic").imageWithInsets(insetDimen: 10) ?? #imageLiteral(resourceName:"camera_black_ic") + } + } + + //region upload ======= + fileprivate func uploadImage(id: Int, signboard: Int, data: Data) { + let tvProgress = SwiftOverlays.showBlockingWaitOverlayWithText(LocalizedString("Uploading") + ".....") + Alamofire.upload(multipartFormData: { (multipartFormData: MultipartFormData) in + multipartFormData.append(data, withName: "file", fileName: "file_\(DataTypeUtils.getCurrentTimeSecond()).jpg", mimeType: "image/jpeg") + multipartFormData.append("\(id)".data(using: String.Encoding.utf8)!, withName: "idShooting") + multipartFormData.append("\(signboard)".data(using: String.Encoding.utf8)!, withName: "signboard") +// if let note = self.shootItem. { +//multipartFormData.append("\(note)".data(using: String.Encoding.utf8)!, withName: "note") +// } + }, to: Constants.PathManager.ROOT_SERVER + "api/board/store", method: .post, encodingCompletion: { (encodingResult: SessionManager.MultipartFormDataEncodingResult) in + switch encodingResult { + case .success(let upload, _, _): + upload.uploadProgress(closure: { progress in + CommonUtils.excuteOnMainThread({tvProgress.text = (LocalizedString("Uploading") + " \(Int(progress.fractionCompleted * 100))%")}) + }) + .responseString { response in + SwiftOverlays.removeAllBlockingOverlays() + debugPrint("SUCCESS RESPONSE: \(response.result.value)") + if let value = response.result.value{ + let json = JSON.parse(value) + if let isSuccess = json["isSuccess"].bool, isSuccess, let url = json["url"].string{ + self.shootItem.addImg(img: ImgObj(url: url, signboard: signboard, date: nil, note: nil)) + CommonUtils.showToastLong(text: LocalizedString("successful")) + return + } + } + self.handleError() + } + case .failure(let encodingError): + SwiftOverlays.removeAllBlockingOverlays() + self.handleError() + print("ERROR RESPONSE: \(encodingError)") + } + }) + } + + fileprivate func handleError() { + //DialogUtils.showQuestion(messageParam: <#T##String?##Swift.String?#>, yesAction: <#T##@escaping () -> Void##@escaping () -> Swift.Void#>) } + //endregion } diff --git a/App/commons/VCRoot.swift b/App/commons/VCRoot.swift index 8c07aee..49e3075 100644 --- a/App/commons/VCRoot.swift +++ b/App/commons/VCRoot.swift @@ -1,5 +1,6 @@ import UIKit import Foundation +import GeneralUtils class VCRoot: VCContainerFullScreen { var id: String? @@ -10,7 +11,14 @@ class VCRoot: VCContainerFullScreen { override func viewDidLoad() { super.viewDidLoad() -// changeCurrentController(VCInputId.getInstance()) //TODO: neu chua co id -> Ra cai nay - changeCurrentController(VCHome.getInstance()) + if let _ = PreferenceUtils.getString(key: Constants.PreferenceKeys.ID) { + changeCurrentController(VCHome.getInstance()) + } else { + changeCurrentController(VCInputId.getInstance()) + } } } + +func getIDWork() -> String { + return PreferenceUtils.getString(key: Constants.PreferenceKeys.ID)! +} diff --git a/App/createNew/CellChonMucChup.swift b/App/createNew/CellChonMucChup.swift index c55f0b6..428087e 100644 --- a/App/createNew/CellChonMucChup.swift +++ b/App/createNew/CellChonMucChup.swift @@ -37,7 +37,7 @@ class CellChonMucChup: BaseTableViewCellUI { mucChup = baseObj as! ShootItem tvTitle.text = mucChup.name - if mucChup.isSelected == true { + if mucChup.willShoot == 1 { self.contentView.backgroundColor = UIColor(hexString: "#1C9CF6") } else { self.contentView.backgroundColor = UIColor.white diff --git a/App/createNew/VCChonMucChup.swift b/App/createNew/VCChonMucChup.swift index bd56aab..a164448 100644 --- a/App/createNew/VCChonMucChup.swift +++ b/App/createNew/VCChonMucChup.swift @@ -55,10 +55,10 @@ class VCChonMucChup: UIViewController, IVCLoadDataTableViewUIThread { func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) { if let mucChup = self.tableView.getItem(indexPath) as? ShootItem { - if mucChup.isSelected == true { - mucChup.isSelected = nil + if mucChup.willShoot == 1 { + mucChup.willShoot = nil } else { - mucChup.isSelected = true + mucChup.willShoot = 1 } self.tableView.reloadRows(at: [indexPath], with: .none) } diff --git a/App/createNew/VCConfirmMucDaChon.swift b/App/createNew/VCConfirmMucDaChon.swift index 4bd5b57..594ba27 100644 --- a/App/createNew/VCConfirmMucDaChon.swift +++ b/App/createNew/VCConfirmMucDaChon.swift @@ -44,7 +44,7 @@ class VCConfirmMucDaChon: UIViewController, IVCLoadDataTableViewUIThread { if let list = getVcRoot()?.mucChups { var mucChups = [ShootItem]() for item in list { - if item.isSelected == true { mucChups.append(item) } + if item.willShoot == 1 { mucChups.append(item) } } complete(mucChups) } else { diff --git a/App/createNew/VCRootCreateNew.swift b/App/createNew/VCRootCreateNew.swift index 683bfa2..d971a85 100644 --- a/App/createNew/VCRootCreateNew.swift +++ b/App/createNew/VCRootCreateNew.swift @@ -1,9 +1,12 @@ import UIKit import Foundation +import GeneralUtils +import Alamofire class VCRootCreateNew: VCContainerFullScreen { var tenCty: String?, tenCtruong: String? var mucChups: [ShootItem]? + var signboard: Int = 1 static func openController(_ viewController: UIViewController) { let vcOpen = VCRootCreateNew() @@ -15,5 +18,30 @@ class VCRootCreateNew: VCContainerFullScreen { changeCurrentController(VCNhapTenCty.getInstance()) } - + func createNewToServer() { + var ShootingItem = [Any]() + if let mucChups = mucChups { + for item in mucChups { + if let name = item.name { + ShootingItem.append(["name": name, "willShoot": (item.willShoot == 1)]) + } + } + } + let parameters: Parameters = [ + "idWorker": getIDWork(), + "signboard": signboard == 1, + "companyName": tenCty ?? "", + "constructionName": tenCtruong ?? "", + "ShootingItem": ShootingItem + ] + NetWorkUtils.excutePostTypeRawJSONEncoding(parameters: parameters, url: Constants.PathManager.ROOT_SERVER + "api/regulations/store", + isShowProgress: true, vc: self, responseStringParam: { response in + if response.result.isSuccess { + CommonUtils.showToastLong(text: LocalizedString("successful")) + self.dismiss(animated: true) + } else { + DialogUtils.builderDialog(showCloseButton: true, showTitle: false).showError("", subTitle: LocalizedString("Has_Error_occurred")) + } + }) + } } diff --git a/App/createNew/VCSettingBienQC.swift b/App/createNew/VCSettingBienQC.swift index 1c013b0..34c80de 100644 --- a/App/createNew/VCSettingBienQC.swift +++ b/App/createNew/VCSettingBienQC.swift @@ -3,6 +3,7 @@ import UIKit class VCSettingBienQC: UIViewController { @IBOutlet weak var topMargin: NSLayoutConstraint! @IBOutlet weak var vTopLogo: VTopLogo! + @IBOutlet weak var swich: UISwitch! static func getInstance() -> VCSettingBienQC { let storyboard: UIStoryboard = UIStoryboard(name: "Main", bundle: nil) @@ -16,17 +17,26 @@ class VCSettingBienQC: UIViewController { self.btnLeftClick(self.vTopLogo) } } + override func viewWillAppear(_ animated: Bool) { super.viewWillAppear(animated) + if getVcRoot()?.signboard == 0{ + swich.isOn = false + }else{ + swich.isOn = true + } } @IBAction func btnLeftClick(_ sender: Any) { _ = getVcRoot()?.changeCurrentController(VCConfirmMucDaChon.getInstance()) } + @IBAction func swichValueChange(_ sender: Any) { + getVcRoot()?.signboard = swich.isOn ? 1 : 0 + } + @IBAction func btnRightClick(_ sender: Any) { - getVcRoot()?.dismiss(animated: true) - //TODO: server + getVcRoot()?.createNewToServer() } func getVcRoot() -> VCRootCreateNew? { diff --git a/App/firstInput/VCInputId.swift b/App/firstInput/VCInputId.swift index e630ba2..9fbafd2 100644 --- a/App/firstInput/VCInputId.swift +++ b/App/firstInput/VCInputId.swift @@ -14,14 +14,24 @@ class VCInputId: UIViewController { override func viewDidLoad() { super.viewDidLoad() registerKeyBoardEvent() - edtId.text = getVcRoot()?.id + if let id = getVcRoot()?.id { + edtId.text = id + } else { + edtId.text = PreferenceUtils.getString(key: Constants.PreferenceKeys.ID) + } } @IBAction func btnUnknowClick(_ sender: Any) { + _ = getVcRoot()?.changeCurrentController(VCSendTraoDoi.getInstance()) } @IBAction func btnNextClick(_ sender: Any) { - _ = getVcRoot()?.changeCurrentController(VCSendTraoDoi.getInstance()) + if let id: String = edtId.text?.trimAndReturn(), id.length > 0 { + PreferenceUtils.saveString(key: Constants.PreferenceKeys.ID, value: id) + _ = getVcRoot()?.changeCurrentController(VCHome.getInstance()) + } else { + CommonUtils.showToastLong(text: LocalizedString("khong_de_trong")) + } } @IBAction func edtActionTrigerClick(_ sender: Any) { diff --git a/App/firstInput/VCNoiDungTraoDoi.swift b/App/firstInput/VCNoiDungTraoDoi.swift index 82c9140..cb101d8 100644 --- a/App/firstInput/VCNoiDungTraoDoi.swift +++ b/App/firstInput/VCNoiDungTraoDoi.swift @@ -13,7 +13,7 @@ class VCNoiDungTraoDoi: UIViewController { } @IBAction func btnBackToTopClick(_ sender: Any) { - _ = getVcRoot()?.changeCurrentController(VCHome.getInstance()) + _ = getVcRoot()?.changeCurrentController(VCInputId.getInstance()) } func getVcRoot() -> VCRoot? { diff --git a/App/listCtruong/CellCtruong.swift b/App/listCtruong/CellCtruong.swift index 53e3f8c..4ed52d6 100644 --- a/App/listCtruong/CellCtruong.swift +++ b/App/listCtruong/CellCtruong.swift @@ -9,12 +9,17 @@ class CellCtruong: BaseTableViewCellUI { var ctruong: CongTruong! + override func awakeFromNib() { + super.awakeFromNib() + self.selectionStyle = .none + } + override func configCellWithData(baseObj: Any, index: Int) { super.configCellWithData(baseObj: baseObj, index: index) ctruong = baseObj as! CongTruong - tvTitle.text = ctruong.tenCtuong - tvCatured.text = String(ctruong.daChup ?? 0) - tvRemaining.text = String(ctruong.conLai ?? 0) + tvTitle.text = ctruong.companyName + tvCatured.text = String(ctruong.noCaptured ?? 0) + tvRemaining.text = String(ctruong.noRemain ?? 0) } } diff --git a/App/listCtruong/VCListCtruong.swift b/App/listCtruong/VCListCtruong.swift index 50fdfda..0b38f5e 100644 --- a/App/listCtruong/VCListCtruong.swift +++ b/App/listCtruong/VCListCtruong.swift @@ -24,7 +24,10 @@ class VCListCtruong: UIViewController, IVCLoadDataTableViewUIThread { } //region TableView ======== func loadDataOnUI(complete: @escaping ([Any]?) -> ()) { - complete(AppUtils.getListCtruong()) +// complete(AppUtils.getListCtruong()) + NetWorkUtils.excuteHttpGet(urlStr: Constants.PathManager.ROOT_SERVER + "api/regulations/get/" + getIDWork(), completeArray: { (result: [CongTruong]?, errorText: String?) in + complete(result) + }) } func getAllCell() -> [BaseCell] { diff --git a/App/listCtruong/VCShootItemList.swift b/App/listCtruong/VCShootItemList.swift index cb4ad35..ec0c565 100644 --- a/App/listCtruong/VCShootItemList.swift +++ b/App/listCtruong/VCShootItemList.swift @@ -5,6 +5,7 @@ class VCShootItemList: UIViewController, IVCLoadDataTableViewUIThread { @IBOutlet weak var topMargin: NSLayoutConstraint! @IBOutlet weak var tableView: UITableViewLoadDataFromUIThread! @IBOutlet weak var imvLogo: UIImageView! + @IBOutlet weak var tvTitle: UILabel! var cTruong: CongTruong! @@ -17,7 +18,7 @@ class VCShootItemList: UIViewController, IVCLoadDataTableViewUIThread { override func viewDidLoad() { super.viewDidLoad() - tableView.emptyText = localizedString("empty_muc_chup") + tableView.emptyText = LocalizedString("empty_muc_chup") CellMucChupWithCamera.registerClass(tableView: tableView, forCellReuseIdentifier: "CellMucChupWithCamera") self.tableView.separatorStyle = UITableViewCellSeparatorStyle.singleLine self.tableView.rowHeight = UITableViewAutomaticDimension @@ -25,6 +26,7 @@ class VCShootItemList: UIViewController, IVCLoadDataTableViewUIThread { let tap = UITapGestureRecognizer.init(target: self, action: #selector(VCShootItemList.logoClick)) imvLogo.addGestureRecognizer(tap) tableView.initAndLoadData(self) + tvTitle.text = cTruong.constructionName } @IBAction func btnEditClick(_ sender: Any) { @@ -34,8 +36,17 @@ class VCShootItemList: UIViewController, IVCLoadDataTableViewUIThread { //region ============== TableView Data ========= func loadDataOnUI(complete: @escaping ([Any]?) -> ()) { - print("VCListCtruong: Load data UI") - complete(cTruong.shootItems) + guard let shootItems = cTruong.shootItems else { + complete(nil) + return + } + var shootItemsWillShoot = [ShootItem]() + for item in shootItems { + if let willShoot = item.willShoot, willShoot > 0 { + shootItemsWillShoot.append(item) + } + } + complete(shootItemsWillShoot) } func getAllCell() -> [BaseCell] { diff --git a/App/model/CongTruong.swift b/App/model/CongTruong.swift index 90fef33..0f1d410 100644 --- a/App/model/CongTruong.swift +++ b/App/model/CongTruong.swift @@ -1,10 +1,25 @@ import Foundation +import GeneralUtils -class CongTruong { - var tenCtuong: String? - var tenCty: String? - var daChup: Int?, conLai: Int? +class CongTruong: Mappable { + var id: Int? + var companyName: String? + var constructionName: String? + var noCaptured: Int?, noRemain: Int? var shootItems: [ShootItem]? + var signboard: Int? + // region: ========== Mappable + init() {} + required init?(map: Map) {} + func mapping(map: Map) { + companyName <- map["companyName"] + constructionName <- map["constructionName"] + noCaptured <- map["noCaptured"] + noRemain <- map["noRemain"] + shootItems <- map["shootingItems"] + signboard <- map["signboard"] + } + //endregion } diff --git a/App/model/ImgObj.swift b/App/model/ImgObj.swift index d28ddd0..4c82e2b 100644 --- a/App/model/ImgObj.swift +++ b/App/model/ImgObj.swift @@ -1,8 +1,28 @@ import Foundation +import GeneralUtils -class ImgObj { - var url: String! - var signboard: Bool? +class ImgObj: Mappable { + var url: String? + var signboard: Int? var date: Int64? var note: String? + + init() {} + init(url: String, signboard: Int?, date: Int64?, note: String?) { + self.url = url + self.signboard = signboard + self.date = date + self.note = note + } + + // region: ========== Mappable + required init?(map: Map) {} + + func mapping(map: Map) { + url <- map["url"] + signboard <- map["signboard"] + date <- map["date"] + note <- map["note"] + } + //endregion } diff --git a/App/model/MucChup.swift b/App/model/MucChup.swift deleted file mode 100644 index e384740..0000000 --- a/App/model/MucChup.swift +++ /dev/null @@ -1,19 +0,0 @@ -import Foundation - -class ShootItem: Equatable { - var id: Int? - var name: String? - var isSelected: Bool? - - init(id: Int? = nil, name: String? = nil) { - self.id = id - self.name = name - } -} - -func ==(lhs: ShootItem, rhs: ShootItem) -> Bool { - if let lhsName = lhs.name, let rhsName = rhs.name { - return lhsName == rhsName - } - return ObjectIdentifier(lhs) == ObjectIdentifier(rhs) -} diff --git a/App/model/ShootItem.swift b/App/model/ShootItem.swift new file mode 100644 index 0000000..dd8648c --- /dev/null +++ b/App/model/ShootItem.swift @@ -0,0 +1,40 @@ +import Foundation +import GeneralUtils + +class ShootItem: Equatable, Mappable { + var id: Int? + var name: String? + var willShoot: Int? + var signboard: Int? + var imgs: [ImgObj]? + + init(id: Int? = nil, name: String? = nil) { + self.id = id + self.name = name + } + + func addImg(img: ImgObj) { + if imgs == nil { imgs = [ImgObj]() } + imgs?.append(img) + } + + // region: ========== Mappable + init() {} + required init?(map: Map) {} + + func mapping(map: Map) { + id <- map["id"] + name <- map["name"] + willShoot <- map["willShoot"] + imgs <- map["imgs"] + } + //endregion +} + +func ==(lhs: ShootItem, rhs: ShootItem) -> Bool { + if let lhsName = lhs.name, let rhsName = rhs.name { + return lhsName == rhsName + } + return ObjectIdentifier(lhs) == ObjectIdentifier(rhs) +} + diff --git a/App/utils/AppUtils.swift b/App/utils/AppUtils.swift index 9348fe6..703bc38 100644 --- a/App/utils/AppUtils.swift +++ b/App/utils/AppUtils.swift @@ -14,23 +14,23 @@ class AppUtils { shootItems.append(ShootItem(id: nil, name: "仕上げ")) var ctruong = CongTruong() - ctruong.tenCtuong = "山田 花子様" - ctruong.daChup = 1 - ctruong.conLai = 4 + ctruong.companyName = "山田 花子様" + ctruong.noCaptured = 1 + ctruong.noRemain = 4 ctruong.shootItems = shootItems result.append(ctruong) ctruong = CongTruong() - ctruong.tenCtuong = "鈴木 一郎様" - ctruong.daChup = 12 - ctruong.conLai = 1 + ctruong.companyName = "鈴木 一郎様" + ctruong.noCaptured = 12 + ctruong.noRemain = 1 ctruong.shootItems = shootItems result.append(ctruong) ctruong = CongTruong() - ctruong.tenCtuong = "斎藤 太郎様" - ctruong.daChup = 0 - ctruong.conLai = 24 + ctruong.companyName = "斎藤 太郎様" + ctruong.noCaptured = 0 + ctruong.noRemain = 24 ctruong.shootItems = shootItems result.append(ctruong) diff --git a/App/utils/Constants.swift b/App/utils/Constants.swift new file mode 100644 index 0000000..77d4652 --- /dev/null +++ b/App/utils/Constants.swift @@ -0,0 +1,16 @@ +// +// Created by Philip Tran on 3/4/17. +// + +import Foundation + +struct Constants { + + struct PreferenceKeys { + static let ID = "ID"; + } + + struct PathManager{ + static let ROOT_SERVER = "https://api-morooka.herokuapp.com/" + } +} diff --git a/App/utils/FileUpload.swift b/App/utils/FileUpload.swift new file mode 100644 index 0000000..bfc141c --- /dev/null +++ b/App/utils/FileUpload.swift @@ -0,0 +1,110 @@ +import Foundation +import Alamofire + +private struct FileUploadInfo { + var name: String + var mimeType: String + var fileName: String + var url: URL? + var data: Data? + + init(name: String, withFileURL url: URL, withMimeType mimeType: String? = nil) { + self.name = name + self.url = url + self.fileName = name + self.mimeType = "application/octet-stream" + if mimeType != nil { + self.mimeType = mimeType! + } + fileName = url.lastPathComponent + if mimeType == nil { + let _extension = url.pathExtension + switch _extension.lowercased() { + case "jpeg", "jpg": + self.mimeType = "image/jpeg" + + case "png": + self.mimeType = "image/png" + + default: + self.mimeType = "application/octet-stream" + } + } + } + + init(name: String, withData data: Data, withMimeType mimeType: String) { + self.name = name + self.data = data + self.fileName = name + self.mimeType = mimeType + } +} + +class FileUploader { + + private var parameters = [String: String]() + private var files = [FileUploadInfo]() + private var headers = [String: String]() + + func setValue(value: String, forParameter parameter: String) { + parameters[parameter] = value + } + + func setValue(value: String, forHeader header: String) { + headers[header] = value + } + + func addParametersFrom(_ map: [String: String]) { + for (key, value) in map { + parameters[key] = value + } + } + + func addHeadersFrom(_ map: [String: String]) { + for (key, value) in map { + headers[key] = value + } + } + + func addFileURL(url: URL, withName name: String, withMimeType mimeType: String? = nil) { + files.append(FileUploadInfo(name: name, withFileURL: url, withMimeType: mimeType)) + } + + func addFileData(data: Data, withName name: String, withMimeType mimeType: String = "application/octet-stream") { + files.append(FileUploadInfo(name: name, withData: data, withMimeType: mimeType)) + } + + func uploadFile(to: String, method: HTTPMethod) -> UploadRequest? { + let data = NSMutableData() + let boundary = "FileUploader-boundary-\(arc4random())-\(arc4random())" + // Amazon S3 (probably others) wont take parameters after files, so we put them first + for (key, value) in parameters { + data.append("\r\n--\(boundary)\r\n".data(using: String.Encoding.utf8)!) + data.append("Content-Disposition: form-data; name=\"\(key)\"\r\n\r\n\(value)".data(using: String.Encoding.utf8)!) + } + + for fileUploadInfo in files { + data.append("\r\n--\(boundary)\r\n".data(using: String.Encoding.utf8)!) + data.append("Content-Disposition: form-data; name=\"\(fileUploadInfo.name)\"; filename=\"\(fileUploadInfo.fileName)\"\r\n".data(using: String.Encoding.utf8)!) + data.append("Content-Type: \(fileUploadInfo.mimeType)\r\n\r\n".data(using: String.Encoding.utf8)!) + if fileUploadInfo.data != nil { + data.append(fileUploadInfo.data!) + } else if fileUploadInfo.url != nil, let fileData = try? Data(contentsOf: fileUploadInfo.url!) { + data.append(fileData) + } else { + // ToDo: report error + return nil + } + } + data.append("\r\n--\(boundary)--\r\n".data(using: String.Encoding.utf8)!) + + var headerParam = HTTPHeaders() + headerParam["multipart/form-data;boundary=\(boundary)"] = "Content-Type" + for (name, value) in headers { + headerParam[value] = name + } + + return Alamofire.upload(Data(referencing: data), to: to, method: method, headers: headerParam) + } + +} \ No newline at end of file diff --git a/App/utils/NetWorkUtils.swift b/App/utils/NetWorkUtils.swift new file mode 100644 index 0000000..4468e99 --- /dev/null +++ b/App/utils/NetWorkUtils.swift @@ -0,0 +1,39 @@ +import GeneralUtils +import Foundation +import Alamofire + +extension NetWorkUtils { + + /** + The JSONEncoding type creates a JSON representation of the parameters object, which is set as the HTTP body of the request. The Content-Type HTTP header field of an encoded request is set to application/json. + + */ + public static func excutePostTypeRawJSONEncoding(parameters: Parameters, url: String, isShowProgress: Bool? = nil, vc: UIViewController? = nil, + responseStringParam: @escaping (DataResponse) -> Void) { + NetWorkUtils.excutePost(parameters: parameters, url: url, isShowProgress: isShowProgress, vc: vc, encoding: JSONEncoding.default, responseStringParam: responseStringParam) + } + + public static func excutePostTypeFormURLEncoded(parameters: Parameters, url: String, isShowProgress: Bool? = nil, vc: UIViewController? = nil, + responseStringParam: @escaping (DataResponse) -> Void) { + NetWorkUtils.excutePost(parameters: parameters, url: url, isShowProgress: isShowProgress, vc: vc, encoding: URLEncoding.default, responseStringParam: responseStringParam) + } + + public static func excutePostTypePropertyListEncoding(parameters: Parameters, url: String, isShowProgress: Bool? = nil, vc: UIViewController? = nil, + responseStringParam: @escaping (DataResponse) -> Void) { + NetWorkUtils.excutePost(parameters: parameters, url: url, isShowProgress: isShowProgress, vc: vc, encoding: PropertyListEncoding.default, responseStringParam: responseStringParam) + } + + public static func excutePost(parameters: Parameters, url: String, isShowProgress: Bool? = nil, vc: UIViewController? = nil, encoding: ParameterEncoding, + responseStringParam: @escaping (DataResponse) -> Void) { + if isShowProgress == true { + vc?.showWaitOverlay(isBlockTouch: true) + } + Alamofire.request(url, method: .post, parameters: parameters, encoding: encoding) + .responseString { response in + if isShowProgress == true { + vc?.removeAllOverlays() + } + responseStringParam(response) + } + } +} \ No newline at end of file diff --git a/GeneralUtils/.idea/GeneralUtils.iml b/GeneralUtils/.idea/GeneralUtils.iml new file mode 100644 index 0000000..74121dc --- /dev/null +++ b/GeneralUtils/.idea/GeneralUtils.iml @@ -0,0 +1,2 @@ + + \ No newline at end of file diff --git a/GeneralUtils/.idea/encodings.xml b/GeneralUtils/.idea/encodings.xml new file mode 100644 index 0000000..97626ba --- /dev/null +++ b/GeneralUtils/.idea/encodings.xml @@ -0,0 +1,6 @@ + + + + + + \ No newline at end of file diff --git a/GeneralUtils/.idea/inspectionProfiles/Project_Default.xml b/GeneralUtils/.idea/inspectionProfiles/Project_Default.xml new file mode 100644 index 0000000..8d66637 --- /dev/null +++ b/GeneralUtils/.idea/inspectionProfiles/Project_Default.xml @@ -0,0 +1,5 @@ + + + + \ No newline at end of file diff --git a/GeneralUtils/.idea/misc.xml b/GeneralUtils/.idea/misc.xml new file mode 100644 index 0000000..e1f8477 --- /dev/null +++ b/GeneralUtils/.idea/misc.xml @@ -0,0 +1,96 @@ + + + + + + + + + + + + + + + + + + + + + + Objective-C + + + RELAX NG + + + Spelling + + + Swift + + + TypeScript + + + + + Objective-C + + + + + + + + + + 1.7 + + + + + + + + \ No newline at end of file diff --git a/GeneralUtils/.idea/modules.xml b/GeneralUtils/.idea/modules.xml new file mode 100644 index 0000000..a48e046 --- /dev/null +++ b/GeneralUtils/.idea/modules.xml @@ -0,0 +1,8 @@ + + + + + + + + \ No newline at end of file diff --git a/GeneralUtils/.idea/vcs.xml b/GeneralUtils/.idea/vcs.xml new file mode 100644 index 0000000..94a25f7 --- /dev/null +++ b/GeneralUtils/.idea/vcs.xml @@ -0,0 +1,6 @@ + + + + + + \ No newline at end of file diff --git a/GeneralUtils/.idea/workspace.xml b/GeneralUtils/.idea/workspace.xml new file mode 100644 index 0000000..10a7426 --- /dev/null +++ b/GeneralUtils/.idea/workspace.xml @@ -0,0 +1,715 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + true + DEFINITION_ORDER + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + project + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + 1488469363911 + + + 1488469537760 + + + 1488470556293 + + + 1488471395256 + + + 1488508151673 + + + 1488508233306 + + + 1488509320246 + + + 1488510219152 + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + \ No newline at end of file diff --git a/GeneralUtils/.idea/xcode.xml b/GeneralUtils/.idea/xcode.xml new file mode 100644 index 0000000..60e5770 --- /dev/null +++ b/GeneralUtils/.idea/xcode.xml @@ -0,0 +1,4 @@ + + + + \ No newline at end of file diff --git a/GeneralUtils/GeneralUtils.podspec b/GeneralUtils/GeneralUtils.podspec new file mode 100644 index 0000000..afac799 --- /dev/null +++ b/GeneralUtils/GeneralUtils.podspec @@ -0,0 +1,15 @@ +Pod::Spec.new do |s| + s.platform = :ios + s.ios.deployment_target = '9.0' + s.name = "GeneralUtils" + s.summary = "GeneralUtils is network manager" + s.requires_arc = true + s.version = "1.1" + s.license = { :type => "MIT", :file => "LICENSE" } + s.author = { "Quan Trinh" => "quanptit410@gmail.com" } + s.homepage = "https://github.com/quanptit/GeneralUtils" + s.source = { :git => "https://github.com/quanptit/GeneralUtils.git", :tag => "#{s.version}"} + s.framework = "UIKit" + s.source_files = "GeneralUtils/**/*.{swift,h,m}" + #s.resources = "GeneralUtils/**/*.{png,jpeg,jpg,storyboard,xib}" +end \ No newline at end of file diff --git a/GeneralUtils/GeneralUtils.xcodeproj/project.pbxproj b/GeneralUtils/GeneralUtils.xcodeproj/project.pbxproj new file mode 100644 index 0000000..f4370f4 --- /dev/null +++ b/GeneralUtils/GeneralUtils.xcodeproj/project.pbxproj @@ -0,0 +1,1169 @@ +// !$*UTF8*$! +{ + archiveVersion = 1; + classes = { + }; + objectVersion = 46; + objects = { + +/* Begin PBXBuildFile section */ + 660BB017307C97835E430B85 /* Generics.swift in Sources */ = {isa = PBXBuildFile; fileRef = 660BB7C469F3295449B48747 /* Generics.swift */; }; + 660BB02813284FF82C9A5C68 /* RandomBytesSequence.swift in Sources */ = {isa = PBXBuildFile; fileRef = 660BB176F48EC804605D945A /* RandomBytesSequence.swift */; }; + 660BB05547B110F273DFEBFE /* UIButtonCustom.swift in Sources */ = {isa = PBXBuildFile; fileRef = 660BB810558E7D7420EF7BE0 /* UIButtonCustom.swift */; }; + 660BB09490F2E44D8A54B835 /* SCLAlertView.swift in Sources */ = {isa = PBXBuildFile; fileRef = 660BB0E5F9ECF184D4433074 /* SCLAlertView.swift */; }; + 660BB096980E50195EC9E6C4 /* ToastWindow.swift in Sources */ = {isa = PBXBuildFile; fileRef = 660BB6C6DEBAEE62102CED69 /* ToastWindow.swift */; }; + 660BB0AB7BCC0CD54BC3F694 /* Data+Extension.swift in Sources */ = {isa = PBXBuildFile; fileRef = 660BBDD6CA2B01B39EEE98F0 /* Data+Extension.swift */; }; + 660BB0CDC8E38699F67BDCDF /* Padding.swift in Sources */ = {isa = PBXBuildFile; fileRef = 660BB56D86EA67C397D97E4E /* Padding.swift */; }; + 660BB10AC416E1F583DB5781 /* ToastCenter.swift in Sources */ = {isa = PBXBuildFile; fileRef = 660BB9A0DFB90DDB7F1BD9A2 /* ToastCenter.swift */; }; + 660BB1470B2BD1017A147821 /* UILabelCustom.swift in Sources */ = {isa = PBXBuildFile; fileRef = 660BBE857B2FF54AFC7F5CC6 /* UILabelCustom.swift */; }; + 660BB195A1D42FC892A02A44 /* String+FoundationExtension.swift in Sources */ = {isa = PBXBuildFile; fileRef = 660BBA5731B2425A91A7B7C4 /* String+FoundationExtension.swift */; }; + 660BB1A4E46E2C1130AD3978 /* BaseUIPresentationController.swift in Sources */ = {isa = PBXBuildFile; fileRef = 660BBD62C125875A7D977481 /* BaseUIPresentationController.swift */; }; + 660BB1CED2484BBB77382C52 /* TransformType.swift in Sources */ = {isa = PBXBuildFile; fileRef = 660BB5012299257B8EA4C3DF /* TransformType.swift */; }; + 660BB1E7887AA04473643D5E /* VCContainer.swift in Sources */ = {isa = PBXBuildFile; fileRef = 660BBD1E3926FDFEEA4C3E9B /* VCContainer.swift */; }; + 660BB211B3285CA16F2CC432 /* PBKDF1.swift in Sources */ = {isa = PBXBuildFile; fileRef = 660BB7C6CB72E9D07866674F /* PBKDF1.swift */; }; + 660BB214E6EFB96A34FBBA3E /* Checksum.swift in Sources */ = {isa = PBXBuildFile; fileRef = 660BBC70A8038A3A8EF66430 /* Checksum.swift */; }; + 660BB22A39A192A41D4F3344 /* VPlayerControl.swift in Sources */ = {isa = PBXBuildFile; fileRef = 660BBBB6BD143E05E992EDA8 /* VPlayerControl.swift */; }; + 660BB23BB6D055996A8BF62B /* BlockModeOptions.swift in Sources */ = {isa = PBXBuildFile; fileRef = 660BB604C1941534593A1C44 /* BlockModeOptions.swift */; }; + 660BB271F8FC8E5BA195C74E /* Authenticator.swift in Sources */ = {isa = PBXBuildFile; fileRef = 660BB961FF0DD677BD299896 /* Authenticator.swift */; }; + 660BB275D72E072967319D3C /* DateFormatterTransform.swift in Sources */ = {isa = PBXBuildFile; fileRef = 660BBC4B54E57DC9FF98302D /* DateFormatterTransform.swift */; }; + 660BB28A34746B71F32CBFA2 /* FromJSON.swift in Sources */ = {isa = PBXBuildFile; fileRef = 660BB0C57701B0E930D621DE /* FromJSON.swift */; }; + 660BB28C653560033F478E62 /* Array+Extension.swift in Sources */ = {isa = PBXBuildFile; fileRef = 660BB4D5825BC7F02DB04003 /* Array+Extension.swift */; }; + 660BB296CC86AD7275DD7EBF /* UIViewCustomGradientBg.swift in Sources */ = {isa = PBXBuildFile; fileRef = 660BB2DDB3FBB3B88F726D55 /* UIViewCustomGradientBg.swift */; }; + 660BB29A28A9512DE1B658A1 /* UInt32+Extension.swift in Sources */ = {isa = PBXBuildFile; fileRef = 660BBD3C1756EAE55528C2A3 /* UInt32+Extension.swift */; }; + 660BB29C372A958C0B86C416 /* Queue.swift in Sources */ = {isa = PBXBuildFile; fileRef = 660BBDE96B42528FE255B5C5 /* Queue.swift */; }; + 660BB2B063B9EEB6BAE10A4D /* CSArrayType+Foundation.swift in Sources */ = {isa = PBXBuildFile; fileRef = 660BBBA0B59200A63CC5C49F /* CSArrayType+Foundation.swift */; }; + 660BB2B2F6151FFF78E72CC8 /* UITableViewLoadDataBg.swift in Sources */ = {isa = PBXBuildFile; fileRef = 660BBDDA727C4F10116C6DF3 /* UITableViewLoadDataBg.swift */; }; + 660BB3029621648615E3E9E1 /* FileUtils.swift in Sources */ = {isa = PBXBuildFile; fileRef = 660BBB47A50033D64F099A59 /* FileUtils.swift */; }; + 660BB3149D2BBC2BEF0E2CA7 /* RecordUtils.swift in Sources */ = {isa = PBXBuildFile; fileRef = 660BB1D9E1D3F3A4CA67C287 /* RecordUtils.swift */; }; + 660BB3171CAED790D4BE5B12 /* CommonUtils.swift in Sources */ = {isa = PBXBuildFile; fileRef = 660BB091EE4A5B55273D74C2 /* CommonUtils.swift */; }; + 660BB31B77CEBBF559611F63 /* Operators.swift in Sources */ = {isa = PBXBuildFile; fileRef = 660BB53A77A128D39D246C80 /* Operators.swift */; }; + 660BB33A23DDEC11377AFBC6 /* UITableViewLoadDataFromUIThread.swift in Sources */ = {isa = PBXBuildFile; fileRef = 660BB06AB76AC8C25F03C45E /* UITableViewLoadDataFromUIThread.swift */; }; + 660BB34B0E661054F3EE3F24 /* AES+Foundation.swift in Sources */ = {isa = PBXBuildFile; fileRef = 660BBAD1B1ECD02481A86166 /* AES+Foundation.swift */; }; + 660BB368E7B84778781FCE3C /* NetWorkUtils.swift in Sources */ = {isa = PBXBuildFile; fileRef = 660BBE4C5CC8638788123CFC /* NetWorkUtils.swift */; }; + 660BB36DCF3F46251B8EE3FB /* OFB.swift in Sources */ = {isa = PBXBuildFile; fileRef = 660BB63FA48D20F64E7601EB /* OFB.swift */; }; + 660BB3747F292ACB52E42079 /* CBC.swift in Sources */ = {isa = PBXBuildFile; fileRef = 660BB2997837FA6B1C43C043 /* CBC.swift */; }; + 660BB38A40811060B4268DDF /* TransformOperators.swift in Sources */ = {isa = PBXBuildFile; fileRef = 660BBF8A846AE94CA97F1325 /* TransformOperators.swift */; }; + 660BB39B8103E48A8CCD11E4 /* RandomAccessBlockModeWorker.swift in Sources */ = {isa = PBXBuildFile; fileRef = 660BB37E485037901CB53692 /* RandomAccessBlockModeWorker.swift */; }; + 660BB39E46E69ABBE1766E3A /* NoPadding.swift in Sources */ = {isa = PBXBuildFile; fileRef = 660BB5FBB1FC126C8B5DFDE0 /* NoPadding.swift */; }; + 660BB3B75EE3FD06FCEA216B /* VTopNotification.xib in Resources */ = {isa = PBXBuildFile; fileRef = 660BBBAC2F5E734910E2F1FC /* VTopNotification.xib */; }; + 660BB3BDAECA7622691BAA71 /* UICollectionViewLoadData.swift in Sources */ = {isa = PBXBuildFile; fileRef = 660BBD0E2B7CF1AD7818CCB3 /* UICollectionViewLoadData.swift */; }; + 660BB3D0D6B9F632CA86D222 /* Collection+Extension.swift in Sources */ = {isa = PBXBuildFile; fileRef = 660BBB9583DB947DB3A048A0 /* Collection+Extension.swift */; }; + 660BB3DEB8563F6C19997C46 /* Utils.swift in Sources */ = {isa = PBXBuildFile; fileRef = 660BB50FFF818E312491F252 /* Utils.swift */; }; + 660BB3F33AF55AE1AB398817 /* PKCS5.swift in Sources */ = {isa = PBXBuildFile; fileRef = 660BBA8B1C7C6962F1F225CD /* PKCS5.swift */; }; + 660BB401D73E4F771BE53A63 /* FloatRatingView.swift in Sources */ = {isa = PBXBuildFile; fileRef = 660BB022BC1FB91F190D27B9 /* FloatRatingView.swift */; }; + 660BB47326AA4D3CEB5D959F /* SwiftOverlays.swift in Sources */ = {isa = PBXBuildFile; fileRef = 660BB1D131D0294D71F457F6 /* SwiftOverlays.swift */; }; + 660BB4C4C7B206E20897C273 /* ViewTopBar.swift in Sources */ = {isa = PBXBuildFile; fileRef = 660BBC8A059E90CD7DB470CC /* ViewTopBar.swift */; }; + 660BB4DB26E542023BE791A3 /* Cryptors.swift in Sources */ = {isa = PBXBuildFile; fileRef = 660BBDEFCF681709EAD2FB6A /* Cryptors.swift */; }; + 660BB4E07507BBD9FFD59844 /* UILableCustomLeftImage.swift in Sources */ = {isa = PBXBuildFile; fileRef = 660BB69DA413B6B970E70694 /* UILableCustomLeftImage.swift */; }; + 660BB4EB34BB99E2AEFA0329 /* Blowfish.swift in Sources */ = {isa = PBXBuildFile; fileRef = 660BB0AA9740EF11D34188AB /* Blowfish.swift */; }; + 660BB509C00D339853CD3516 /* URLTransform.swift in Sources */ = {isa = PBXBuildFile; fileRef = 660BB06D9754DB8833DE8B43 /* URLTransform.swift */; }; + 660BB52A9CABD5BF9FAB9D37 /* CommonExtension.swift in Sources */ = {isa = PBXBuildFile; fileRef = 660BB459F7FFFE9742A3B38E /* CommonExtension.swift */; }; + 660BB534E53CE88CE12E5BE5 /* PBKDF2.swift in Sources */ = {isa = PBXBuildFile; fileRef = 660BB530DC81A2B7D4D6A075 /* PBKDF2.swift */; }; + 660BB53FAFFF909C2E1C9BCB /* ChaCha20+Foundation.swift in Sources */ = {isa = PBXBuildFile; fileRef = 660BB0282AEE873F45A0BEEE /* ChaCha20+Foundation.swift */; }; + 660BB5500B0E8B28CFBD0AA3 /* DigestType.swift in Sources */ = {isa = PBXBuildFile; fileRef = 660BB8D43009ACE8FA90B51D /* DigestType.swift */; }; + 660BB564D493CC0EA4F7E80D /* ToJSON.swift in Sources */ = {isa = PBXBuildFile; fileRef = 660BB3DED3B6A0EA1658B82D /* ToJSON.swift */; }; + 660BB567122A08A7880178BE /* Updatable.swift in Sources */ = {isa = PBXBuildFile; fileRef = 660BB9F128FBFECA116F838E /* Updatable.swift */; }; + 660BB598C593836339B1EBC0 /* DateTransform.swift in Sources */ = {isa = PBXBuildFile; fileRef = 660BB2FF8D5B2F0D39DAF74D /* DateTransform.swift */; }; + 660BB5A0E9B5F854773C2B7C /* CacheUtils.swift in Sources */ = {isa = PBXBuildFile; fileRef = 660BB329CCA6116DC566C7EC /* CacheUtils.swift */; }; + 660BB5EDEC866BD4D755F3F6 /* UIImageViewCustom.swift in Sources */ = {isa = PBXBuildFile; fileRef = 660BB9862858C648E7A2913D /* UIImageViewCustom.swift */; }; + 660BB5F6F9E8243D2BDC44F4 /* SHA2.swift in Sources */ = {isa = PBXBuildFile; fileRef = 660BBE36EA589E9A87A6CA7A /* SHA2.swift */; }; + 660BB62EEC22830D63048FE8 /* ECB.swift in Sources */ = {isa = PBXBuildFile; fileRef = 660BB4F148620A46352C8BFE /* ECB.swift */; }; + 660BB63DEC21DA281E71D7FB /* AES.swift in Sources */ = {isa = PBXBuildFile; fileRef = 660BB36713CCEF1025DAA864 /* AES.swift */; }; + 660BB6418F3B36DB8CAB963E /* UIViewCustomPressHightLight.swift in Sources */ = {isa = PBXBuildFile; fileRef = 660BB2D9306FF40787602A43 /* UIViewCustomPressHightLight.swift */; }; + 660BB6623229B3104AC3F530 /* DropDown.swift in Sources */ = {isa = PBXBuildFile; fileRef = 660BB83C13A6BF8C70DA02FD /* DropDown.swift */; }; + 660BB674657F1FBF15DDABE5 /* String+Extension.swift in Sources */ = {isa = PBXBuildFile; fileRef = 660BBC24E9C194110A5ADED4 /* String+Extension.swift */; }; + 660BB6A863BAE2C92F215CF9 /* DialogUtils.swift in Sources */ = {isa = PBXBuildFile; fileRef = 660BB183616C474DA865EF52 /* DialogUtils.swift */; }; + 660BB6B4930C9C9A68A23238 /* SwiftyJSON.swift in Sources */ = {isa = PBXBuildFile; fileRef = 660BB259BD12F23C07D28B6A /* SwiftyJSON.swift */; }; + 660BB6D1CEC505522F484BE3 /* AnimatedControllerFromBottom.swift in Sources */ = {isa = PBXBuildFile; fileRef = 660BB75B3BFD437D420BEC71 /* AnimatedControllerFromBottom.swift */; }; + 660BB6E884453AC44D47C904 /* EnumTransform.swift in Sources */ = {isa = PBXBuildFile; fileRef = 660BB47302AD40CB9B0040A9 /* EnumTransform.swift */; }; + 660BB6EB1178785DF70C6083 /* HexColorTransform.swift in Sources */ = {isa = PBXBuildFile; fileRef = 660BB8097091C9DE74926BE5 /* HexColorTransform.swift */; }; + 660BB702C71DEECC871DBCE8 /* Int+Extension.swift in Sources */ = {isa = PBXBuildFile; fileRef = 660BBFE2105C6A1EDFD52F1B /* Int+Extension.swift */; }; + 660BB70E3CD72CAF4737F3F6 /* TransformOf.swift in Sources */ = {isa = PBXBuildFile; fileRef = 660BB9327F1A29A238848D02 /* TransformOf.swift */; }; + 660BB722BC16861C5A13A71C /* Rabbit.swift in Sources */ = {isa = PBXBuildFile; fileRef = 660BB5350E970DF5E9C640CA /* Rabbit.swift */; }; + 660BB7348DC81863AC0B7D69 /* CellLoadMore.swift in Sources */ = {isa = PBXBuildFile; fileRef = 660BB105FA331EE64030B3DF /* CellLoadMore.swift */; }; + 660BB73DAF74E5D158619545 /* ZeroPadding.swift in Sources */ = {isa = PBXBuildFile; fileRef = 660BB521E5B40346D865AF79 /* ZeroPadding.swift */; }; + 660BB763F29C94A0DFB810B9 /* UInt16+Extension.swift in Sources */ = {isa = PBXBuildFile; fileRef = 660BB7837AC018AB4F02088D /* UInt16+Extension.swift */; }; + 660BB7A6680B8DC96970636D /* ISRadioButton.swift in Sources */ = {isa = PBXBuildFile; fileRef = 660BBBF9DBE36AD64EF7A088 /* ISRadioButton.swift */; }; + 660BB7B90D211A04BE805BCA /* SHA3.swift in Sources */ = {isa = PBXBuildFile; fileRef = 660BB0EDACEF4F3A11D45AA9 /* SHA3.swift */; }; + 660BB7C0931100C45D2A4709 /* GeneralMenuController.swift in Sources */ = {isa = PBXBuildFile; fileRef = 660BB002E1E06FBF9C7EE8A6 /* GeneralMenuController.swift */; }; + 660BB7FEF1D1C33D574AD39F /* UIViewCustom.swift in Sources */ = {isa = PBXBuildFile; fileRef = 660BBD58BF51A8CF5A05BFAF /* UIViewCustom.swift */; }; + 660BB876DDFD2B33CC105757 /* ImmutableMappable.swift in Sources */ = {isa = PBXBuildFile; fileRef = 660BB3F05127AE28636B07EC /* ImmutableMappable.swift */; }; + 660BB87ADEE46A00BFB1E2AD /* SCLExtensions.swift in Sources */ = {isa = PBXBuildFile; fileRef = 660BBDA6244648043A2EACB9 /* SCLExtensions.swift */; }; + 660BB883A116CE74CC9EE7D8 /* CTR.swift in Sources */ = {isa = PBXBuildFile; fileRef = 660BBB61A48A134AD3049B36 /* CTR.swift */; }; + 660BB8FE9365F2F946AD9FCA /* UInt8+Extension.swift in Sources */ = {isa = PBXBuildFile; fileRef = 660BBCDEFE5560B4C4239FAA /* UInt8+Extension.swift */; }; + 660BB90C319A5DAEAD289D9D /* DataTypeUtils.swift in Sources */ = {isa = PBXBuildFile; fileRef = 660BBDD1799055BEC5CE5940 /* DataTypeUtils.swift */; }; + 660BB922FAB4EFFC6DA16A90 /* RandomAccessCryptor.swift in Sources */ = {isa = PBXBuildFile; fileRef = 660BBB074D45462CB8D6D086 /* RandomAccessCryptor.swift */; }; + 660BB9320EDFA44DB9E76A5A /* DropDownCell.swift in Sources */ = {isa = PBXBuildFile; fileRef = 660BB8B80EDDDC9F6FB6618B /* DropDownCell.swift */; }; + 660BB94B68EB2F4D5EBFF98D /* PCBC.swift in Sources */ = {isa = PBXBuildFile; fileRef = 660BB7D1246730E3C0A10755 /* PCBC.swift */; }; + 660BB9566076EE2DDC7CE2E8 /* Bit.swift in Sources */ = {isa = PBXBuildFile; fileRef = 660BBE903D7FF61A49962895 /* Bit.swift */; }; + 660BB977B861049752788962 /* DPDKeyboardListener.swift in Sources */ = {isa = PBXBuildFile; fileRef = 660BBD820E5BE874917E8EB4 /* DPDKeyboardListener.swift */; }; + 660BB99342616A64D8779A24 /* UInt64+Extension.swift in Sources */ = {isa = PBXBuildFile; fileRef = 660BB5B239E1B2BC3BDA47A0 /* UInt64+Extension.swift */; }; + 660BB9A6AE5DC32DE19DBABF /* ViewTopBar.xib in Resources */ = {isa = PBXBuildFile; fileRef = 660BB3C4D28B44FD15017017 /* ViewTopBar.xib */; }; + 660BB9F302854FD3B6394FB0 /* DrawerController.swift in Sources */ = {isa = PBXBuildFile; fileRef = 660BB6585B2B229B4CD64794 /* DrawerController.swift */; }; + 660BB9F41D77949A45917C40 /* CFB.swift in Sources */ = {isa = PBXBuildFile; fileRef = 660BB53576D9837788B89B16 /* CFB.swift */; }; + 660BBA04490927989BAE074E /* BlockModeWorker.swift in Sources */ = {isa = PBXBuildFile; fileRef = 660BB27373A195C8F1FEA5ED /* BlockModeWorker.swift */; }; + 660BBA0B4A44F77A7231535B /* HMAC.swift in Sources */ = {isa = PBXBuildFile; fileRef = 660BBCFC470D2DB341A5B5AD /* HMAC.swift */; }; + 660BBA1E335DD4E71931DDF8 /* PreferenceUtils.swift in Sources */ = {isa = PBXBuildFile; fileRef = 660BBC8645A4F542EB45CB99 /* PreferenceUtils.swift */; }; + 660BBA307B2FAAC75FAB932C /* MapError.swift in Sources */ = {isa = PBXBuildFile; fileRef = 660BB2950BC5B3B32EE27C48 /* MapError.swift */; }; + 660BBA43A564BC8CDD6F4B1D /* IContainerController.swift in Sources */ = {isa = PBXBuildFile; fileRef = 660BBB5C8436A73A79FC944B /* IContainerController.swift */; }; + 660BBA5A1887353812391145 /* Blowfish+Foundation.swift in Sources */ = {isa = PBXBuildFile; fileRef = 660BBF18BB7037C2ACE44AC8 /* Blowfish+Foundation.swift */; }; + 660BBA78A2FB3117F3F0F105 /* DataTransform.swift in Sources */ = {isa = PBXBuildFile; fileRef = 660BBF2E4D60371CFCA8DC8D /* DataTransform.swift */; }; + 660BBA8F2D1E0B38B941AA5D /* SecurityUtils.swift in Sources */ = {isa = PBXBuildFile; fileRef = 660BB972E0E2D74CE8074DDF /* SecurityUtils.swift */; }; + 660BBAA747957EEF9193D5D1 /* HMAC+Foundation.swift in Sources */ = {isa = PBXBuildFile; fileRef = 660BB595A76E4789432D15C2 /* HMAC+Foundation.swift */; }; + 660BBB256B6DBCE6A136D1D8 /* UITextViewCustom.swift in Sources */ = {isa = PBXBuildFile; fileRef = 660BB343E55D2B9B85CA01FF /* UITextViewCustom.swift */; }; + 660BBB4946D8F14B33D7B434 /* EnumOperators.swift in Sources */ = {isa = PBXBuildFile; fileRef = 660BB6F58D44898F9AFD8D42 /* EnumOperators.swift */; }; + 660BBB7A0F35D6324DE5FCA5 /* DPDConstants.swift in Sources */ = {isa = PBXBuildFile; fileRef = 660BB41E63AE5F14D2FAB0C2 /* DPDConstants.swift */; }; + 660BBBA4C085D12BC882B01B /* Mappable.swift in Sources */ = {isa = PBXBuildFile; fileRef = 660BB143B094DFEE1DEB6308 /* Mappable.swift */; }; + 660BBBAF48437D32BC2E9ED6 /* Cipher.swift in Sources */ = {isa = PBXBuildFile; fileRef = 660BB71E69B75077967CE687 /* Cipher.swift */; }; + 660BBBC1CC0A02BE671BC7C2 /* VTopNotification.swift in Sources */ = {isa = PBXBuildFile; fileRef = 660BB14B1226E5D778D9EFB2 /* VTopNotification.swift */; }; + 660BBBDACD3534EB52AEC32F /* DictionaryTransform.swift in Sources */ = {isa = PBXBuildFile; fileRef = 660BB309E5CABE571009195A /* DictionaryTransform.swift */; }; + 660BBBDF4CE07E9369B7A0BE /* Rabbit+Foundation.swift in Sources */ = {isa = PBXBuildFile; fileRef = 660BB29F9B379AC3DE165B5D /* Rabbit+Foundation.swift */; }; + 660BBC1564A61534A95EE11F /* ComboBox.swift in Sources */ = {isa = PBXBuildFile; fileRef = 660BB1E8D21904BC23E8A988 /* ComboBox.swift */; }; + 660BBC1AD7840540E6234A84 /* NSDecimalNumberTransform.swift in Sources */ = {isa = PBXBuildFile; fileRef = 660BBFBFBE49D2DF93ED1409 /* NSDecimalNumberTransform.swift */; }; + 660BBC24B162B9D0627A204B /* PKCS7.swift in Sources */ = {isa = PBXBuildFile; fileRef = 660BB357ABC9D61A4FE9FC40 /* PKCS7.swift */; }; + 660BBC4099897B2D268FD716 /* CSArrayType+Extensions.swift in Sources */ = {isa = PBXBuildFile; fileRef = 660BBC3CD49C6DB102DBDA73 /* CSArrayType+Extensions.swift */; }; + 660BBC4AF5B23D206515241F /* BaseTbLoadData.swift in Sources */ = {isa = PBXBuildFile; fileRef = 660BB0EE87A69672537B1730 /* BaseTbLoadData.swift */; }; + 660BBC607B7C9EEC7AA35F56 /* Toaster.h in Headers */ = {isa = PBXBuildFile; fileRef = 660BBC557EB1233B301FC676 /* Toaster.h */; }; + 660BBC6872E19063EAB297C1 /* AnimatedTransitioning.swift in Sources */ = {isa = PBXBuildFile; fileRef = 660BB76CDA9432C229F6D293 /* AnimatedTransitioning.swift */; }; + 660BBC9CC373AAB73C6C74E2 /* GeneralUtils.podspec in Resources */ = {isa = PBXBuildFile; fileRef = 660BB40C90C48543A4A5D098 /* GeneralUtils.podspec */; }; + 660BBCBA4021E9807BC26C44 /* SecureBytes.swift in Sources */ = {isa = PBXBuildFile; fileRef = 660BB52399A43573D51E26E6 /* SecureBytes.swift */; }; + 660BBCFB13F7C0980EF8844A /* ToastView.swift in Sources */ = {isa = PBXBuildFile; fileRef = 660BB72FB5E47C4EA0CE02E3 /* ToastView.swift */; }; + 660BBD0FE3DB483CBF87B2DD /* DrawerBarButtonItem.swift in Sources */ = {isa = PBXBuildFile; fileRef = 660BB282901996CBE32F18AE /* DrawerBarButtonItem.swift */; }; + 660BBD38F499BDC8FD830503 /* Utils+Foundation.swift in Sources */ = {isa = PBXBuildFile; fileRef = 660BB92A63F2195321CF86D0 /* Utils+Foundation.swift */; }; + 660BBD3D9677DACCF050D2A6 /* BasePageViewController.swift in Sources */ = {isa = PBXBuildFile; fileRef = 660BB3C988109B8EF4492314 /* BasePageViewController.swift */; }; + 660BBD46DC6D3DF2DF46EEC4 /* BaseCell.swift in Sources */ = {isa = PBXBuildFile; fileRef = 660BBEFDB0C6C51E324BE954 /* BaseCell.swift */; }; + 660BBD6EA511BF216FFE9807 /* BytesSequence.swift in Sources */ = {isa = PBXBuildFile; fileRef = 660BB1DD713B75A8245F77A3 /* BytesSequence.swift */; }; + 660BBDC2F499F5A06289EDA4 /* DPDUIView+Extension.swift in Sources */ = {isa = PBXBuildFile; fileRef = 660BB3DBE117B9C5E1CFA072 /* DPDUIView+Extension.swift */; }; + 660BBDCD6C885D47F48F2711 /* Toast.swift in Sources */ = {isa = PBXBuildFile; fileRef = 660BBE566526783A34B92E56 /* Toast.swift */; }; + 660BBDE6B9635AA67A47C6C3 /* Map.swift in Sources */ = {isa = PBXBuildFile; fileRef = 660BBBB9740469B8D8B93A31 /* Map.swift */; }; + 660BBE0EA3C641CAB4E13722 /* AnimatedMenuButton.swift in Sources */ = {isa = PBXBuildFile; fileRef = 660BB6F91F29724BEB82A0A6 /* AnimatedMenuButton.swift */; }; + 660BBE32F64C4A63C38A2A33 /* BlockCipher.swift in Sources */ = {isa = PBXBuildFile; fileRef = 660BBF10747F6743A335F6D9 /* BlockCipher.swift */; }; + 660BBE3884FAF5A6041108D2 /* DrawerVisualStateManager.swift in Sources */ = {isa = PBXBuildFile; fileRef = 660BBF64A961C03D9A68FC8F /* DrawerVisualStateManager.swift */; }; + 660BBE6D5D83B258C173D089 /* Mapper.swift in Sources */ = {isa = PBXBuildFile; fileRef = 660BBC7ADEFEBAFF39A487C9 /* Mapper.swift */; }; + 660BBE6E74262696D06D3396 /* Digest.swift in Sources */ = {isa = PBXBuildFile; fileRef = 660BBFB61C5945D61F956A86 /* Digest.swift */; }; + 660BBE969598871ADCCC5A46 /* UITableViewLoadMore.swift in Sources */ = {isa = PBXBuildFile; fileRef = 660BBADD9397444A4D0AE48D /* UITableViewLoadMore.swift */; }; + 660BBE9717148FD1FD0A6B53 /* ISO8601DateTransform.swift in Sources */ = {isa = PBXBuildFile; fileRef = 660BB476D80C5BC75D17D120 /* ISO8601DateTransform.swift */; }; + 660BBE9AEB71901AB0FB1FD6 /* DrawerVisualState.swift in Sources */ = {isa = PBXBuildFile; fileRef = 660BB6297DE7449544B9F1E2 /* DrawerVisualState.swift */; }; + 660BBEAFEE4B7074195BB228 /* BlockMode.swift in Sources */ = {isa = PBXBuildFile; fileRef = 660BBC38F01F8727031A1E1F /* BlockMode.swift */; }; + 660BBEB5FF4B1440CBE3ED42 /* DrawerController.h in Headers */ = {isa = PBXBuildFile; fileRef = 660BB0449C844F79AECE464A /* DrawerController.h */; }; + 660BBEB72FD420C5370241FF /* MD5.swift in Sources */ = {isa = PBXBuildFile; fileRef = 660BB22E32E7867182F932AD /* MD5.swift */; }; + 660BBED47DCF543CFF09130A /* UITableViewLoading.swift in Sources */ = {isa = PBXBuildFile; fileRef = 660BBA587C4EB16F5C7B6F72 /* UITableViewLoading.swift */; }; + 660BBED8076643223A1A1F9F /* SHA1.swift in Sources */ = {isa = PBXBuildFile; fileRef = 660BBD53861230A02DEBFD95 /* SHA1.swift */; }; + 660BBEE0871750BFEFD26E3E /* CustomDateFormatTransform.swift in Sources */ = {isa = PBXBuildFile; fileRef = 660BB5723BD2238D62A5DB0A /* CustomDateFormatTransform.swift */; }; + 660BBEE19174C58FC617F9F0 /* BaseViewControllerShowTransculent.swift in Sources */ = {isa = PBXBuildFile; fileRef = 660BB3CCB355725DF41E9F50 /* BaseViewControllerShowTransculent.swift */; }; + 660BBF1814F172D685CDDFB0 /* Poly1305.swift in Sources */ = {isa = PBXBuildFile; fileRef = 660BB6DBA145E5AAB587B78A /* Poly1305.swift */; }; + 660BBF78048DEF820E87FC3E /* UICollectionViewLoading.swift in Sources */ = {isa = PBXBuildFile; fileRef = 660BB2454201E512E17C80C1 /* UICollectionViewLoading.swift */; }; + 660BBFB98C0904C89DCFD491 /* DownloadTask.swift in Sources */ = {isa = PBXBuildFile; fileRef = 660BBF3465EB342B13F54876 /* DownloadTask.swift */; }; + 660BBFDE1C1F2729DA32D9A3 /* IntegerConvertible.swift in Sources */ = {isa = PBXBuildFile; fileRef = 660BB84ECDAC06DF8A370C00 /* IntegerConvertible.swift */; }; + 660BBFDEFD7AA2DFDBF25937 /* StringExtension.swift in Sources */ = {isa = PBXBuildFile; fileRef = 660BB639F6E0051D120BD08A /* StringExtension.swift */; }; + 660BBFF1A3DE36950FF834FA /* ChaCha20.swift in Sources */ = {isa = PBXBuildFile; fileRef = 660BBBE5553388AA439B36DA /* ChaCha20.swift */; }; + F976D50B1E68747800708D6A /* GeneralUtils.h in Headers */ = {isa = PBXBuildFile; fileRef = F976D5091E68747800708D6A /* GeneralUtils.h */; settings = {ATTRIBUTES = (Public, ); }; }; + F976D5171E69025200708D6A /* Session.swift in Sources */ = {isa = PBXBuildFile; fileRef = F976D5161E69025200708D6A /* Session.swift */; }; + F976D52D1E6902DC00708D6A /* AnimatedImageView.swift in Sources */ = {isa = PBXBuildFile; fileRef = F976D5181E6902DC00708D6A /* AnimatedImageView.swift */; }; + F976D52E1E6902DC00708D6A /* Box.swift in Sources */ = {isa = PBXBuildFile; fileRef = F976D5191E6902DC00708D6A /* Box.swift */; }; + F976D52F1E6902DC00708D6A /* CacheSerializer.swift in Sources */ = {isa = PBXBuildFile; fileRef = F976D51A1E6902DC00708D6A /* CacheSerializer.swift */; }; + F976D5301E6902DC00708D6A /* Filter.swift in Sources */ = {isa = PBXBuildFile; fileRef = F976D51B1E6902DC00708D6A /* Filter.swift */; }; + F976D5311E6902DC00708D6A /* Image.swift in Sources */ = {isa = PBXBuildFile; fileRef = F976D51C1E6902DC00708D6A /* Image.swift */; }; + F976D5321E6902DC00708D6A /* ImageCache.swift in Sources */ = {isa = PBXBuildFile; fileRef = F976D51D1E6902DC00708D6A /* ImageCache.swift */; }; + F976D5331E6902DC00708D6A /* ImageDownloader.swift in Sources */ = {isa = PBXBuildFile; fileRef = F976D51E1E6902DC00708D6A /* ImageDownloader.swift */; }; + F976D5341E6902DC00708D6A /* ImagePrefetcher.swift in Sources */ = {isa = PBXBuildFile; fileRef = F976D51F1E6902DC00708D6A /* ImagePrefetcher.swift */; }; + F976D5351E6902DC00708D6A /* ImageProcessor.swift in Sources */ = {isa = PBXBuildFile; fileRef = F976D5201E6902DC00708D6A /* ImageProcessor.swift */; }; + F976D5361E6902DC00708D6A /* ImageTransition.swift in Sources */ = {isa = PBXBuildFile; fileRef = F976D5211E6902DC00708D6A /* ImageTransition.swift */; }; + F976D5371E6902DC00708D6A /* ImageView+Kingfisher.swift in Sources */ = {isa = PBXBuildFile; fileRef = F976D5221E6902DC00708D6A /* ImageView+Kingfisher.swift */; }; + F976D5381E6902DC00708D6A /* Indicator.swift in Sources */ = {isa = PBXBuildFile; fileRef = F976D5231E6902DC00708D6A /* Indicator.swift */; }; + F976D5391E6902DC00708D6A /* Kingfisher.h in Headers */ = {isa = PBXBuildFile; fileRef = F976D5241E6902DC00708D6A /* Kingfisher.h */; }; + F976D53A1E6902DC00708D6A /* Kingfisher.swift in Sources */ = {isa = PBXBuildFile; fileRef = F976D5251E6902DC00708D6A /* Kingfisher.swift */; }; + F976D53B1E6902DC00708D6A /* KingfisherManager.swift in Sources */ = {isa = PBXBuildFile; fileRef = F976D5261E6902DC00708D6A /* KingfisherManager.swift */; }; + F976D53C1E6902DC00708D6A /* KingfisherOptionsInfo.swift in Sources */ = {isa = PBXBuildFile; fileRef = F976D5271E6902DC00708D6A /* KingfisherOptionsInfo.swift */; }; + F976D53D1E6902DC00708D6A /* RequestModifier.swift in Sources */ = {isa = PBXBuildFile; fileRef = F976D5281E6902DC00708D6A /* RequestModifier.swift */; }; + F976D53E1E6902DC00708D6A /* Resource.swift in Sources */ = {isa = PBXBuildFile; fileRef = F976D5291E6902DC00708D6A /* Resource.swift */; }; + F976D53F1E6902DC00708D6A /* String+MD5.swift in Sources */ = {isa = PBXBuildFile; fileRef = F976D52A1E6902DC00708D6A /* String+MD5.swift */; }; + F976D5401E6902DC00708D6A /* ThreadHelper.swift in Sources */ = {isa = PBXBuildFile; fileRef = F976D52B1E6902DC00708D6A /* ThreadHelper.swift */; }; + F976D5411E6902DC00708D6A /* UIButton+Kingfisher.swift in Sources */ = {isa = PBXBuildFile; fileRef = F976D52C1E6902DC00708D6A /* UIButton+Kingfisher.swift */; }; + F983E1261E69ADF4008FEC23 /* Assets.xcassets in Resources */ = {isa = PBXBuildFile; fileRef = F983E1251E69ADF4008FEC23 /* Assets.xcassets */; }; +/* End PBXBuildFile section */ + +/* Begin PBXFileReference section */ + 660BB002E1E06FBF9C7EE8A6 /* GeneralMenuController.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = GeneralMenuController.swift; sourceTree = ""; }; + 660BB022BC1FB91F190D27B9 /* FloatRatingView.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = FloatRatingView.swift; sourceTree = ""; }; + 660BB0282AEE873F45A0BEEE /* ChaCha20+Foundation.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = "ChaCha20+Foundation.swift"; sourceTree = ""; }; + 660BB0449C844F79AECE464A /* DrawerController.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = DrawerController.h; sourceTree = ""; }; + 660BB06AB76AC8C25F03C45E /* UITableViewLoadDataFromUIThread.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = UITableViewLoadDataFromUIThread.swift; sourceTree = ""; }; + 660BB06D9754DB8833DE8B43 /* URLTransform.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = URLTransform.swift; sourceTree = ""; }; + 660BB091EE4A5B55273D74C2 /* CommonUtils.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = CommonUtils.swift; sourceTree = ""; }; + 660BB0AA9740EF11D34188AB /* Blowfish.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = Blowfish.swift; sourceTree = ""; }; + 660BB0C57701B0E930D621DE /* FromJSON.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = FromJSON.swift; sourceTree = ""; }; + 660BB0E5F9ECF184D4433074 /* SCLAlertView.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = SCLAlertView.swift; sourceTree = ""; }; + 660BB0EDACEF4F3A11D45AA9 /* SHA3.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = SHA3.swift; sourceTree = ""; }; + 660BB0EE87A69672537B1730 /* BaseTbLoadData.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = BaseTbLoadData.swift; sourceTree = ""; }; + 660BB105FA331EE64030B3DF /* CellLoadMore.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = CellLoadMore.swift; sourceTree = ""; }; + 660BB143B094DFEE1DEB6308 /* Mappable.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = Mappable.swift; sourceTree = ""; }; + 660BB14B1226E5D778D9EFB2 /* VTopNotification.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = VTopNotification.swift; sourceTree = ""; }; + 660BB176F48EC804605D945A /* RandomBytesSequence.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = RandomBytesSequence.swift; sourceTree = ""; }; + 660BB183616C474DA865EF52 /* DialogUtils.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = DialogUtils.swift; sourceTree = ""; }; + 660BB1D131D0294D71F457F6 /* SwiftOverlays.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = SwiftOverlays.swift; sourceTree = ""; }; + 660BB1D9E1D3F3A4CA67C287 /* RecordUtils.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = RecordUtils.swift; sourceTree = ""; }; + 660BB1DD713B75A8245F77A3 /* BytesSequence.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = BytesSequence.swift; sourceTree = ""; }; + 660BB1E8D21904BC23E8A988 /* ComboBox.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = ComboBox.swift; sourceTree = ""; }; + 660BB22E32E7867182F932AD /* MD5.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = MD5.swift; sourceTree = ""; }; + 660BB2454201E512E17C80C1 /* UICollectionViewLoading.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = UICollectionViewLoading.swift; sourceTree = ""; }; + 660BB259BD12F23C07D28B6A /* SwiftyJSON.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = SwiftyJSON.swift; sourceTree = ""; }; + 660BB27373A195C8F1FEA5ED /* BlockModeWorker.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = BlockModeWorker.swift; sourceTree = ""; }; + 660BB282901996CBE32F18AE /* DrawerBarButtonItem.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = DrawerBarButtonItem.swift; sourceTree = ""; }; + 660BB2950BC5B3B32EE27C48 /* MapError.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = MapError.swift; sourceTree = ""; }; + 660BB2997837FA6B1C43C043 /* CBC.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = CBC.swift; sourceTree = ""; }; + 660BB29F9B379AC3DE165B5D /* Rabbit+Foundation.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = "Rabbit+Foundation.swift"; sourceTree = ""; }; + 660BB2D9306FF40787602A43 /* UIViewCustomPressHightLight.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = UIViewCustomPressHightLight.swift; sourceTree = ""; }; + 660BB2DDB3FBB3B88F726D55 /* UIViewCustomGradientBg.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = UIViewCustomGradientBg.swift; sourceTree = ""; }; + 660BB2FF8D5B2F0D39DAF74D /* DateTransform.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = DateTransform.swift; sourceTree = ""; }; + 660BB309E5CABE571009195A /* DictionaryTransform.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = DictionaryTransform.swift; sourceTree = ""; }; + 660BB329CCA6116DC566C7EC /* CacheUtils.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = CacheUtils.swift; sourceTree = ""; }; + 660BB343E55D2B9B85CA01FF /* UITextViewCustom.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = UITextViewCustom.swift; sourceTree = ""; }; + 660BB357ABC9D61A4FE9FC40 /* PKCS7.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = PKCS7.swift; sourceTree = ""; }; + 660BB36713CCEF1025DAA864 /* AES.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = AES.swift; sourceTree = ""; }; + 660BB37E485037901CB53692 /* RandomAccessBlockModeWorker.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = RandomAccessBlockModeWorker.swift; sourceTree = ""; }; + 660BB3C4D28B44FD15017017 /* ViewTopBar.xib */ = {isa = PBXFileReference; lastKnownFileType = file.xib; path = ViewTopBar.xib; sourceTree = ""; }; + 660BB3C988109B8EF4492314 /* BasePageViewController.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = BasePageViewController.swift; sourceTree = ""; }; + 660BB3CCB355725DF41E9F50 /* BaseViewControllerShowTransculent.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = BaseViewControllerShowTransculent.swift; sourceTree = ""; }; + 660BB3DBE117B9C5E1CFA072 /* DPDUIView+Extension.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = "DPDUIView+Extension.swift"; sourceTree = ""; }; + 660BB3DED3B6A0EA1658B82D /* ToJSON.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = ToJSON.swift; sourceTree = ""; }; + 660BB3F05127AE28636B07EC /* ImmutableMappable.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = ImmutableMappable.swift; sourceTree = ""; }; + 660BB40C90C48543A4A5D098 /* GeneralUtils.podspec */ = {isa = PBXFileReference; lastKnownFileType = file.podspec; path = GeneralUtils.podspec; sourceTree = ""; }; + 660BB41E63AE5F14D2FAB0C2 /* DPDConstants.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = DPDConstants.swift; sourceTree = ""; }; + 660BB459F7FFFE9742A3B38E /* CommonExtension.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = CommonExtension.swift; sourceTree = ""; }; + 660BB47302AD40CB9B0040A9 /* EnumTransform.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = EnumTransform.swift; sourceTree = ""; }; + 660BB476D80C5BC75D17D120 /* ISO8601DateTransform.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = ISO8601DateTransform.swift; sourceTree = ""; }; + 660BB4D5825BC7F02DB04003 /* Array+Extension.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = "Array+Extension.swift"; sourceTree = ""; }; + 660BB4F148620A46352C8BFE /* ECB.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = ECB.swift; sourceTree = ""; }; + 660BB5012299257B8EA4C3DF /* TransformType.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = TransformType.swift; sourceTree = ""; }; + 660BB50FFF818E312491F252 /* Utils.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = Utils.swift; sourceTree = ""; }; + 660BB521E5B40346D865AF79 /* ZeroPadding.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = ZeroPadding.swift; sourceTree = ""; }; + 660BB52399A43573D51E26E6 /* SecureBytes.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = SecureBytes.swift; sourceTree = ""; }; + 660BB530DC81A2B7D4D6A075 /* PBKDF2.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = PBKDF2.swift; sourceTree = ""; }; + 660BB5350E970DF5E9C640CA /* Rabbit.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = Rabbit.swift; sourceTree = ""; }; + 660BB53576D9837788B89B16 /* CFB.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = CFB.swift; sourceTree = ""; }; + 660BB53A77A128D39D246C80 /* Operators.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = Operators.swift; sourceTree = ""; }; + 660BB56D86EA67C397D97E4E /* Padding.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = Padding.swift; sourceTree = ""; }; + 660BB5723BD2238D62A5DB0A /* CustomDateFormatTransform.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = CustomDateFormatTransform.swift; sourceTree = ""; }; + 660BB595A76E4789432D15C2 /* HMAC+Foundation.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = "HMAC+Foundation.swift"; sourceTree = ""; }; + 660BB5B239E1B2BC3BDA47A0 /* UInt64+Extension.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = "UInt64+Extension.swift"; sourceTree = ""; }; + 660BB5FBB1FC126C8B5DFDE0 /* NoPadding.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = NoPadding.swift; sourceTree = ""; }; + 660BB604C1941534593A1C44 /* BlockModeOptions.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = BlockModeOptions.swift; sourceTree = ""; }; + 660BB6297DE7449544B9F1E2 /* DrawerVisualState.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = DrawerVisualState.swift; sourceTree = ""; }; + 660BB639F6E0051D120BD08A /* StringExtension.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = StringExtension.swift; sourceTree = ""; }; + 660BB63FA48D20F64E7601EB /* OFB.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = OFB.swift; sourceTree = ""; }; + 660BB6585B2B229B4CD64794 /* DrawerController.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = DrawerController.swift; sourceTree = ""; }; + 660BB69DA413B6B970E70694 /* UILableCustomLeftImage.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = UILableCustomLeftImage.swift; sourceTree = ""; }; + 660BB6C6DEBAEE62102CED69 /* ToastWindow.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = ToastWindow.swift; sourceTree = ""; }; + 660BB6DBA145E5AAB587B78A /* Poly1305.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = Poly1305.swift; sourceTree = ""; }; + 660BB6F58D44898F9AFD8D42 /* EnumOperators.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = EnumOperators.swift; sourceTree = ""; }; + 660BB6F91F29724BEB82A0A6 /* AnimatedMenuButton.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = AnimatedMenuButton.swift; sourceTree = ""; }; + 660BB71E69B75077967CE687 /* Cipher.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = Cipher.swift; sourceTree = ""; }; + 660BB72FB5E47C4EA0CE02E3 /* ToastView.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = ToastView.swift; sourceTree = ""; }; + 660BB75B3BFD437D420BEC71 /* AnimatedControllerFromBottom.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = AnimatedControllerFromBottom.swift; sourceTree = ""; }; + 660BB76CDA9432C229F6D293 /* AnimatedTransitioning.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = AnimatedTransitioning.swift; sourceTree = ""; }; + 660BB7837AC018AB4F02088D /* UInt16+Extension.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = "UInt16+Extension.swift"; sourceTree = ""; }; + 660BB7C469F3295449B48747 /* Generics.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = Generics.swift; sourceTree = ""; }; + 660BB7C6CB72E9D07866674F /* PBKDF1.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = PBKDF1.swift; sourceTree = ""; }; + 660BB7D1246730E3C0A10755 /* PCBC.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = PCBC.swift; sourceTree = ""; }; + 660BB8097091C9DE74926BE5 /* HexColorTransform.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = HexColorTransform.swift; sourceTree = ""; }; + 660BB810558E7D7420EF7BE0 /* UIButtonCustom.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = UIButtonCustom.swift; sourceTree = ""; }; + 660BB83C13A6BF8C70DA02FD /* DropDown.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = DropDown.swift; sourceTree = ""; }; + 660BB84ECDAC06DF8A370C00 /* IntegerConvertible.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = IntegerConvertible.swift; sourceTree = ""; }; + 660BB8B80EDDDC9F6FB6618B /* DropDownCell.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = DropDownCell.swift; sourceTree = ""; }; + 660BB8D43009ACE8FA90B51D /* DigestType.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = DigestType.swift; sourceTree = ""; }; + 660BB92A63F2195321CF86D0 /* Utils+Foundation.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = "Utils+Foundation.swift"; sourceTree = ""; }; + 660BB9327F1A29A238848D02 /* TransformOf.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = TransformOf.swift; sourceTree = ""; }; + 660BB961FF0DD677BD299896 /* Authenticator.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = Authenticator.swift; sourceTree = ""; }; + 660BB972E0E2D74CE8074DDF /* SecurityUtils.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = SecurityUtils.swift; sourceTree = ""; }; + 660BB9862858C648E7A2913D /* UIImageViewCustom.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = UIImageViewCustom.swift; sourceTree = ""; }; + 660BB9A0DFB90DDB7F1BD9A2 /* ToastCenter.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = ToastCenter.swift; sourceTree = ""; }; + 660BB9F128FBFECA116F838E /* Updatable.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = Updatable.swift; sourceTree = ""; }; + 660BBA5731B2425A91A7B7C4 /* String+FoundationExtension.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = "String+FoundationExtension.swift"; sourceTree = ""; }; + 660BBA587C4EB16F5C7B6F72 /* UITableViewLoading.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = UITableViewLoading.swift; sourceTree = ""; }; + 660BBA8B1C7C6962F1F225CD /* PKCS5.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = PKCS5.swift; sourceTree = ""; }; + 660BBAD1B1ECD02481A86166 /* AES+Foundation.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = "AES+Foundation.swift"; sourceTree = ""; }; + 660BBADD9397444A4D0AE48D /* UITableViewLoadMore.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = UITableViewLoadMore.swift; sourceTree = ""; }; + 660BBB074D45462CB8D6D086 /* RandomAccessCryptor.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = RandomAccessCryptor.swift; sourceTree = ""; }; + 660BBB47A50033D64F099A59 /* FileUtils.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = FileUtils.swift; sourceTree = ""; }; + 660BBB5C8436A73A79FC944B /* IContainerController.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = IContainerController.swift; sourceTree = ""; }; + 660BBB61A48A134AD3049B36 /* CTR.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = CTR.swift; sourceTree = ""; }; + 660BBB9583DB947DB3A048A0 /* Collection+Extension.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = "Collection+Extension.swift"; sourceTree = ""; }; + 660BBBA0B59200A63CC5C49F /* CSArrayType+Foundation.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = "CSArrayType+Foundation.swift"; sourceTree = ""; }; + 660BBBAC2F5E734910E2F1FC /* VTopNotification.xib */ = {isa = PBXFileReference; lastKnownFileType = file.xib; path = VTopNotification.xib; sourceTree = ""; }; + 660BBBB6BD143E05E992EDA8 /* VPlayerControl.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = VPlayerControl.swift; sourceTree = ""; }; + 660BBBB9740469B8D8B93A31 /* Map.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = Map.swift; sourceTree = ""; }; + 660BBBE5553388AA439B36DA /* ChaCha20.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = ChaCha20.swift; sourceTree = ""; }; + 660BBBF9DBE36AD64EF7A088 /* ISRadioButton.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = ISRadioButton.swift; sourceTree = ""; }; + 660BBC24E9C194110A5ADED4 /* String+Extension.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = "String+Extension.swift"; sourceTree = ""; }; + 660BBC38F01F8727031A1E1F /* BlockMode.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = BlockMode.swift; sourceTree = ""; }; + 660BBC3CD49C6DB102DBDA73 /* CSArrayType+Extensions.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = "CSArrayType+Extensions.swift"; sourceTree = ""; }; + 660BBC4B54E57DC9FF98302D /* DateFormatterTransform.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = DateFormatterTransform.swift; sourceTree = ""; }; + 660BBC557EB1233B301FC676 /* Toaster.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = Toaster.h; sourceTree = ""; }; + 660BBC70A8038A3A8EF66430 /* Checksum.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = Checksum.swift; sourceTree = ""; }; + 660BBC7ADEFEBAFF39A487C9 /* Mapper.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = Mapper.swift; sourceTree = ""; }; + 660BBC8645A4F542EB45CB99 /* PreferenceUtils.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = PreferenceUtils.swift; sourceTree = ""; }; + 660BBC8A059E90CD7DB470CC /* ViewTopBar.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = ViewTopBar.swift; sourceTree = ""; }; + 660BBCDEFE5560B4C4239FAA /* UInt8+Extension.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = "UInt8+Extension.swift"; sourceTree = ""; }; + 660BBCFC470D2DB341A5B5AD /* HMAC.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = HMAC.swift; sourceTree = ""; }; + 660BBD0E2B7CF1AD7818CCB3 /* UICollectionViewLoadData.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = UICollectionViewLoadData.swift; sourceTree = ""; }; + 660BBD1E3926FDFEEA4C3E9B /* VCContainer.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = VCContainer.swift; sourceTree = ""; }; + 660BBD3C1756EAE55528C2A3 /* UInt32+Extension.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = "UInt32+Extension.swift"; sourceTree = ""; }; + 660BBD53861230A02DEBFD95 /* SHA1.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = SHA1.swift; sourceTree = ""; }; + 660BBD58BF51A8CF5A05BFAF /* UIViewCustom.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = UIViewCustom.swift; sourceTree = ""; }; + 660BBD62C125875A7D977481 /* BaseUIPresentationController.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = BaseUIPresentationController.swift; sourceTree = ""; }; + 660BBD820E5BE874917E8EB4 /* DPDKeyboardListener.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = DPDKeyboardListener.swift; sourceTree = ""; }; + 660BBDA6244648043A2EACB9 /* SCLExtensions.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = SCLExtensions.swift; sourceTree = ""; }; + 660BBDD1799055BEC5CE5940 /* DataTypeUtils.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = DataTypeUtils.swift; sourceTree = ""; }; + 660BBDD6CA2B01B39EEE98F0 /* Data+Extension.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = "Data+Extension.swift"; sourceTree = ""; }; + 660BBDDA727C4F10116C6DF3 /* UITableViewLoadDataBg.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = UITableViewLoadDataBg.swift; sourceTree = ""; }; + 660BBDE96B42528FE255B5C5 /* Queue.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = Queue.swift; sourceTree = ""; }; + 660BBDEFCF681709EAD2FB6A /* Cryptors.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = Cryptors.swift; sourceTree = ""; }; + 660BBE36EA589E9A87A6CA7A /* SHA2.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = SHA2.swift; sourceTree = ""; }; + 660BBE4C5CC8638788123CFC /* NetWorkUtils.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = NetWorkUtils.swift; sourceTree = ""; }; + 660BBE566526783A34B92E56 /* Toast.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = Toast.swift; sourceTree = ""; }; + 660BBE857B2FF54AFC7F5CC6 /* UILabelCustom.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = UILabelCustom.swift; sourceTree = ""; }; + 660BBE903D7FF61A49962895 /* Bit.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = Bit.swift; sourceTree = ""; }; + 660BBEFDB0C6C51E324BE954 /* BaseCell.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = BaseCell.swift; sourceTree = ""; }; + 660BBF10747F6743A335F6D9 /* BlockCipher.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = BlockCipher.swift; sourceTree = ""; }; + 660BBF18BB7037C2ACE44AC8 /* Blowfish+Foundation.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = "Blowfish+Foundation.swift"; sourceTree = ""; }; + 660BBF2E4D60371CFCA8DC8D /* DataTransform.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = DataTransform.swift; sourceTree = ""; }; + 660BBF3465EB342B13F54876 /* DownloadTask.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = DownloadTask.swift; sourceTree = ""; }; + 660BBF64A961C03D9A68FC8F /* DrawerVisualStateManager.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = DrawerVisualStateManager.swift; sourceTree = ""; }; + 660BBF8A846AE94CA97F1325 /* TransformOperators.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = TransformOperators.swift; sourceTree = ""; }; + 660BBFB61C5945D61F956A86 /* Digest.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = Digest.swift; sourceTree = ""; }; + 660BBFBFBE49D2DF93ED1409 /* NSDecimalNumberTransform.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = NSDecimalNumberTransform.swift; sourceTree = ""; }; + 660BBFE2105C6A1EDFD52F1B /* Int+Extension.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = "Int+Extension.swift"; sourceTree = ""; }; + F976D5061E68747800708D6A /* GeneralUtils.framework */ = {isa = PBXFileReference; explicitFileType = wrapper.framework; includeInIndex = 0; path = GeneralUtils.framework; sourceTree = BUILT_PRODUCTS_DIR; }; + F976D5091E68747800708D6A /* GeneralUtils.h */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.c.h; path = GeneralUtils.h; sourceTree = ""; }; + F976D50A1E68747800708D6A /* Info.plist */ = {isa = PBXFileReference; lastKnownFileType = text.plist.xml; path = Info.plist; sourceTree = ""; }; + F976D5161E69025200708D6A /* Session.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = Session.swift; sourceTree = ""; }; + F976D5181E6902DC00708D6A /* AnimatedImageView.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = AnimatedImageView.swift; sourceTree = ""; }; + F976D5191E6902DC00708D6A /* Box.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = Box.swift; sourceTree = ""; }; + F976D51A1E6902DC00708D6A /* CacheSerializer.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = CacheSerializer.swift; sourceTree = ""; }; + F976D51B1E6902DC00708D6A /* Filter.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = Filter.swift; sourceTree = ""; }; + F976D51C1E6902DC00708D6A /* Image.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = Image.swift; sourceTree = ""; }; + F976D51D1E6902DC00708D6A /* ImageCache.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = ImageCache.swift; sourceTree = ""; }; + F976D51E1E6902DC00708D6A /* ImageDownloader.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = ImageDownloader.swift; sourceTree = ""; }; + F976D51F1E6902DC00708D6A /* ImagePrefetcher.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = ImagePrefetcher.swift; sourceTree = ""; }; + F976D5201E6902DC00708D6A /* ImageProcessor.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = ImageProcessor.swift; sourceTree = ""; }; + F976D5211E6902DC00708D6A /* ImageTransition.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = ImageTransition.swift; sourceTree = ""; }; + F976D5221E6902DC00708D6A /* ImageView+Kingfisher.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = "ImageView+Kingfisher.swift"; sourceTree = ""; }; + F976D5231E6902DC00708D6A /* Indicator.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = Indicator.swift; sourceTree = ""; }; + F976D5241E6902DC00708D6A /* Kingfisher.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = Kingfisher.h; sourceTree = ""; }; + F976D5251E6902DC00708D6A /* Kingfisher.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = Kingfisher.swift; sourceTree = ""; }; + F976D5261E6902DC00708D6A /* KingfisherManager.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = KingfisherManager.swift; sourceTree = ""; }; + F976D5271E6902DC00708D6A /* KingfisherOptionsInfo.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = KingfisherOptionsInfo.swift; sourceTree = ""; }; + F976D5281E6902DC00708D6A /* RequestModifier.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = RequestModifier.swift; sourceTree = ""; }; + F976D5291E6902DC00708D6A /* Resource.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = Resource.swift; sourceTree = ""; }; + F976D52A1E6902DC00708D6A /* String+MD5.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = "String+MD5.swift"; sourceTree = ""; }; + F976D52B1E6902DC00708D6A /* ThreadHelper.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = ThreadHelper.swift; sourceTree = ""; }; + F976D52C1E6902DC00708D6A /* UIButton+Kingfisher.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = "UIButton+Kingfisher.swift"; sourceTree = ""; }; + F983E1251E69ADF4008FEC23 /* Assets.xcassets */ = {isa = PBXFileReference; lastKnownFileType = folder.assetcatalog; path = Assets.xcassets; sourceTree = ""; }; +/* End PBXFileReference section */ + +/* Begin PBXFrameworksBuildPhase section */ + F976D5021E68747800708D6A /* Frameworks */ = { + isa = PBXFrameworksBuildPhase; + buildActionMask = 2147483647; + files = ( + ); + runOnlyForDeploymentPostprocessing = 0; + }; +/* End PBXFrameworksBuildPhase section */ + +/* Begin PBXGroup section */ + 660BB08F437B180191B7E8B7 /* BlockMode */ = { + isa = PBXGroup; + children = ( + 660BB2997837FA6B1C43C043 /* CBC.swift */, + 660BB53576D9837788B89B16 /* CFB.swift */, + 660BBB61A48A134AD3049B36 /* CTR.swift */, + 660BB4F148620A46352C8BFE /* ECB.swift */, + 660BB63FA48D20F64E7601EB /* OFB.swift */, + 660BB7D1246730E3C0A10755 /* PCBC.swift */, + 660BBC38F01F8727031A1E1F /* BlockMode.swift */, + 660BB27373A195C8F1FEA5ED /* BlockModeWorker.swift */, + 660BB604C1941534593A1C44 /* BlockModeOptions.swift */, + 660BB37E485037901CB53692 /* RandomAccessBlockModeWorker.swift */, + ); + path = BlockMode; + sourceTree = ""; + }; + 660BB15FC9B49DF01FB4DD59 /* page */ = { + isa = PBXGroup; + children = ( + 660BB3C988109B8EF4492314 /* BasePageViewController.swift */, + ); + path = page; + sourceTree = ""; + }; + 660BB17204A9CED25BF09584 /* DrawerController */ = { + isa = PBXGroup; + children = ( + 660BB0449C844F79AECE464A /* DrawerController.h */, + 660BB6585B2B229B4CD64794 /* DrawerController.swift */, + 660BB6297DE7449544B9F1E2 /* DrawerVisualState.swift */, + 660BB6F91F29724BEB82A0A6 /* AnimatedMenuButton.swift */, + 660BB282901996CBE32F18AE /* DrawerBarButtonItem.swift */, + 660BBF64A961C03D9A68FC8F /* DrawerVisualStateManager.swift */, + ); + path = DrawerController; + sourceTree = ""; + }; + 660BB227787C5154B9F8A7CA /* SCLAlertView */ = { + isa = PBXGroup; + children = ( + 660BB0E5F9ECF184D4433074 /* SCLAlertView.swift */, + 660BBDA6244648043A2EACB9 /* SCLExtensions.swift */, + ); + path = SCLAlertView; + sourceTree = ""; + }; + 660BB27368730D615070D1E2 /* libs */ = { + isa = PBXGroup; + children = ( + 660BBBE466B2294A030154B6 /* ObjectMapper */, + 660BBDF3E8E390B1EA68EA3A /* CryptoSwift */, + 660BB259BD12F23C07D28B6A /* SwiftyJSON.swift */, + 660BB66E813D9FCA4514E7A6 /* Kingfisher */, + 660BB227787C5154B9F8A7CA /* SCLAlertView */, + 660BB7D123299D890699ED7F /* Toaster */, + 660BB1D131D0294D71F457F6 /* SwiftOverlays.swift */, + ); + path = libs; + sourceTree = ""; + }; + 660BB2C4386C7190322EA06B /* Foundation */ = { + isa = PBXGroup; + children = ( + 660BBAD1B1ECD02481A86166 /* AES+Foundation.swift */, + 660BBDD6CA2B01B39EEE98F0 /* Data+Extension.swift */, + 660BB595A76E4789432D15C2 /* HMAC+Foundation.swift */, + 660BB92A63F2195321CF86D0 /* Utils+Foundation.swift */, + 660BB29F9B379AC3DE165B5D /* Rabbit+Foundation.swift */, + 660BBF18BB7037C2ACE44AC8 /* Blowfish+Foundation.swift */, + 660BB0282AEE873F45A0BEEE /* ChaCha20+Foundation.swift */, + 660BBBA0B59200A63CC5C49F /* CSArrayType+Foundation.swift */, + 660BBA5731B2425A91A7B7C4 /* String+FoundationExtension.swift */, + ); + path = Foundation; + sourceTree = ""; + }; + 660BB35AE8A552BDA1358CF8 /* models */ = { + isa = PBXGroup; + children = ( + F976D5161E69025200708D6A /* Session.swift */, + ); + path = models; + sourceTree = ""; + }; + 660BB4A65AF559E60AD04599 /* ui */ = { + isa = PBXGroup; + children = ( + 660BB15FC9B49DF01FB4DD59 /* page */, + 660BBA3B9D8B683F7641F10F /* views */, + 660BB17204A9CED25BF09584 /* DrawerController */, + 660BBD1E3926FDFEEA4C3E9B /* VCContainer.swift */, + 660BBC4F31CD8939D2704751 /* PresentationDialog */, + 660BBB5C8436A73A79FC944B /* IContainerController.swift */, + 660BB002E1E06FBF9C7EE8A6 /* GeneralMenuController.swift */, + ); + path = ui; + sourceTree = ""; + }; + 660BB59EBD27343E01AE44C9 /* PKCS5 */ = { + isa = PBXGroup; + children = ( + 660BBA8B1C7C6962F1F225CD /* PKCS5.swift */, + 660BB7C6CB72E9D07866674F /* PBKDF1.swift */, + 660BB530DC81A2B7D4D6A075 /* PBKDF2.swift */, + ); + path = PKCS5; + sourceTree = ""; + }; + 660BB66E813D9FCA4514E7A6 /* Kingfisher */ = { + isa = PBXGroup; + children = ( + F976D5181E6902DC00708D6A /* AnimatedImageView.swift */, + F976D5191E6902DC00708D6A /* Box.swift */, + F976D51A1E6902DC00708D6A /* CacheSerializer.swift */, + F976D51B1E6902DC00708D6A /* Filter.swift */, + F976D51C1E6902DC00708D6A /* Image.swift */, + F976D51D1E6902DC00708D6A /* ImageCache.swift */, + F976D51E1E6902DC00708D6A /* ImageDownloader.swift */, + F976D51F1E6902DC00708D6A /* ImagePrefetcher.swift */, + F976D5201E6902DC00708D6A /* ImageProcessor.swift */, + F976D5211E6902DC00708D6A /* ImageTransition.swift */, + F976D5221E6902DC00708D6A /* ImageView+Kingfisher.swift */, + F976D5231E6902DC00708D6A /* Indicator.swift */, + F976D5241E6902DC00708D6A /* Kingfisher.h */, + F976D5251E6902DC00708D6A /* Kingfisher.swift */, + F976D5261E6902DC00708D6A /* KingfisherManager.swift */, + F976D5271E6902DC00708D6A /* KingfisherOptionsInfo.swift */, + F976D5281E6902DC00708D6A /* RequestModifier.swift */, + F976D5291E6902DC00708D6A /* Resource.swift */, + F976D52A1E6902DC00708D6A /* String+MD5.swift */, + F976D52B1E6902DC00708D6A /* ThreadHelper.swift */, + F976D52C1E6902DC00708D6A /* UIButton+Kingfisher.swift */, + ); + path = Kingfisher; + sourceTree = ""; + }; + 660BB7D123299D890699ED7F /* Toaster */ = { + isa = PBXGroup; + children = ( + 660BB72FB5E47C4EA0CE02E3 /* ToastView.swift */, + 660BB6C6DEBAEE62102CED69 /* ToastWindow.swift */, + 660BB9A0DFB90DDB7F1BD9A2 /* ToastCenter.swift */, + 660BBC557EB1233B301FC676 /* Toaster.h */, + 660BBE566526783A34B92E56 /* Toast.swift */, + ); + path = Toaster; + sourceTree = ""; + }; + 660BB7D3C520848F3D2CB2FD /* CollectionView */ = { + isa = PBXGroup; + children = ( + 660BB2454201E512E17C80C1 /* UICollectionViewLoading.swift */, + 660BBD0E2B7CF1AD7818CCB3 /* UICollectionViewLoadData.swift */, + ); + path = CollectionView; + sourceTree = ""; + }; + 660BB9246F72CA782E0D51B4 /* TableView */ = { + isa = PBXGroup; + children = ( + 660BBEFDB0C6C51E324BE954 /* BaseCell.swift */, + 660BB105FA331EE64030B3DF /* CellLoadMore.swift */, + 660BB0EE87A69672537B1730 /* BaseTbLoadData.swift */, + 660BBA587C4EB16F5C7B6F72 /* UITableViewLoading.swift */, + 660BBADD9397444A4D0AE48D /* UITableViewLoadMore.swift */, + 660BBDDA727C4F10116C6DF3 /* UITableViewLoadDataBg.swift */, + 660BB06AB76AC8C25F03C45E /* UITableViewLoadDataFromUIThread.swift */, + ); + path = TableView; + sourceTree = ""; + }; + 660BBA3B9D8B683F7641F10F /* views */ = { + isa = PBXGroup; + children = ( + 660BBB2BC1F2654E8842A3ED /* vTopBar */, + 660BBCE62EE713590AC9C251 /* DropDown */, + 660BB9246F72CA782E0D51B4 /* TableView */, + 660BB7D3C520848F3D2CB2FD /* CollectionView */, + 660BBE68D5D2C911182BDFBE /* VTopNotification */, + 660BBD58BF51A8CF5A05BFAF /* UIViewCustom.swift */, + 660BBBF9DBE36AD64EF7A088 /* ISRadioButton.swift */, + 660BBE857B2FF54AFC7F5CC6 /* UILabelCustom.swift */, + 660BB810558E7D7420EF7BE0 /* UIButtonCustom.swift */, + 660BBBB6BD143E05E992EDA8 /* VPlayerControl.swift */, + 660BB022BC1FB91F190D27B9 /* FloatRatingView.swift */, + 660BB343E55D2B9B85CA01FF /* UITextViewCustom.swift */, + 660BB9862858C648E7A2913D /* UIImageViewCustom.swift */, + 660BB69DA413B6B970E70694 /* UILableCustomLeftImage.swift */, + 660BB2DDB3FBB3B88F726D55 /* UIViewCustomGradientBg.swift */, + 660BB2D9306FF40787602A43 /* UIViewCustomPressHightLight.swift */, + ); + path = views; + sourceTree = ""; + }; + 660BBB2BC1F2654E8842A3ED /* vTopBar */ = { + isa = PBXGroup; + children = ( + 660BB3C4D28B44FD15017017 /* ViewTopBar.xib */, + 660BBC8A059E90CD7DB470CC /* ViewTopBar.swift */, + ); + path = vTopBar; + sourceTree = ""; + }; + 660BBBC081AE41EEA62CFDB5 /* commonUtils */ = { + isa = PBXGroup; + children = ( + 660BBDE96B42528FE255B5C5 /* Queue.swift */, + 660BBB47A50033D64F099A59 /* FileUtils.swift */, + 660BB329CCA6116DC566C7EC /* CacheUtils.swift */, + 660BB091EE4A5B55273D74C2 /* CommonUtils.swift */, + 660BB183616C474DA865EF52 /* DialogUtils.swift */, + 660BB1D9E1D3F3A4CA67C287 /* RecordUtils.swift */, + 660BBF3465EB342B13F54876 /* DownloadTask.swift */, + 660BBE4C5CC8638788123CFC /* NetWorkUtils.swift */, + 660BBDD1799055BEC5CE5940 /* DataTypeUtils.swift */, + 660BB459F7FFFE9742A3B38E /* CommonExtension.swift */, + 660BBC8645A4F542EB45CB99 /* PreferenceUtils.swift */, + 660BB639F6E0051D120BD08A /* StringExtension.swift */, + 660BB972E0E2D74CE8074DDF /* SecurityUtils.swift */, + ); + path = commonUtils; + sourceTree = ""; + }; + 660BBBE466B2294A030154B6 /* ObjectMapper */ = { + isa = PBXGroup; + children = ( + 660BB309E5CABE571009195A /* DictionaryTransform.swift */, + 660BB8097091C9DE74926BE5 /* HexColorTransform.swift */, + 660BB9327F1A29A238848D02 /* TransformOf.swift */, + 660BB6F58D44898F9AFD8D42 /* EnumOperators.swift */, + 660BB5012299257B8EA4C3DF /* TransformType.swift */, + 660BB47302AD40CB9B0040A9 /* EnumTransform.swift */, + 660BBF2E4D60371CFCA8DC8D /* DataTransform.swift */, + 660BB2950BC5B3B32EE27C48 /* MapError.swift */, + 660BB06D9754DB8833DE8B43 /* URLTransform.swift */, + 660BBFBFBE49D2DF93ED1409 /* NSDecimalNumberTransform.swift */, + 660BB476D80C5BC75D17D120 /* ISO8601DateTransform.swift */, + 660BB3DED3B6A0EA1658B82D /* ToJSON.swift */, + 660BB2FF8D5B2F0D39DAF74D /* DateTransform.swift */, + 660BBC4B54E57DC9FF98302D /* DateFormatterTransform.swift */, + 660BB53A77A128D39D246C80 /* Operators.swift */, + 660BBF8A846AE94CA97F1325 /* TransformOperators.swift */, + 660BB5723BD2238D62A5DB0A /* CustomDateFormatTransform.swift */, + 660BB0C57701B0E930D621DE /* FromJSON.swift */, + 660BBBB9740469B8D8B93A31 /* Map.swift */, + 660BB143B094DFEE1DEB6308 /* Mappable.swift */, + 660BB3F05127AE28636B07EC /* ImmutableMappable.swift */, + 660BBC7ADEFEBAFF39A487C9 /* Mapper.swift */, + ); + path = ObjectMapper; + sourceTree = ""; + }; + 660BBC4F31CD8939D2704751 /* PresentationDialog */ = { + isa = PBXGroup; + children = ( + 660BB76CDA9432C229F6D293 /* AnimatedTransitioning.swift */, + 660BB75B3BFD437D420BEC71 /* AnimatedControllerFromBottom.swift */, + 660BBD62C125875A7D977481 /* BaseUIPresentationController.swift */, + 660BB3CCB355725DF41E9F50 /* BaseViewControllerShowTransculent.swift */, + ); + path = PresentationDialog; + sourceTree = ""; + }; + 660BBCE62EE713590AC9C251 /* DropDown */ = { + isa = PBXGroup; + children = ( + 660BB1E8D21904BC23E8A988 /* ComboBox.swift */, + 660BB83C13A6BF8C70DA02FD /* DropDown.swift */, + 660BB41E63AE5F14D2FAB0C2 /* DPDConstants.swift */, + 660BB8B80EDDDC9F6FB6618B /* DropDownCell.swift */, + 660BBD820E5BE874917E8EB4 /* DPDKeyboardListener.swift */, + 660BB3DBE117B9C5E1CFA072 /* DPDUIView+Extension.swift */, + ); + path = DropDown; + sourceTree = ""; + }; + 660BBDF3E8E390B1EA68EA3A /* CryptoSwift */ = { + isa = PBXGroup; + children = ( + 660BBDEFCF681709EAD2FB6A /* Cryptors.swift */, + 660BBCDEFE5560B4C4239FAA /* UInt8+Extension.swift */, + 660BBC3CD49C6DB102DBDA73 /* CSArrayType+Extensions.swift */, + 660BB5FBB1FC126C8B5DFDE0 /* NoPadding.swift */, + 660BBC70A8038A3A8EF66430 /* Checksum.swift */, + 660BBCFC470D2DB341A5B5AD /* HMAC.swift */, + 660BB50FFF818E312491F252 /* Utils.swift */, + 660BB1DD713B75A8245F77A3 /* BytesSequence.swift */, + 660BB22E32E7867182F932AD /* MD5.swift */, + 660BB7837AC018AB4F02088D /* UInt16+Extension.swift */, + 660BB7C469F3295449B48747 /* Generics.swift */, + 660BB59EBD27343E01AE44C9 /* PKCS5 */, + 660BBFE2105C6A1EDFD52F1B /* Int+Extension.swift */, + 660BB6DBA145E5AAB587B78A /* Poly1305.swift */, + 660BB4D5825BC7F02DB04003 /* Array+Extension.swift */, + 660BB8D43009ACE8FA90B51D /* DigestType.swift */, + 660BB176F48EC804605D945A /* RandomBytesSequence.swift */, + 660BB5350E970DF5E9C640CA /* Rabbit.swift */, + 660BB2C4386C7190322EA06B /* Foundation */, + 660BBD53861230A02DEBFD95 /* SHA1.swift */, + 660BB36713CCEF1025DAA864 /* AES.swift */, + 660BBBE5553388AA439B36DA /* ChaCha20.swift */, + 660BBE36EA589E9A87A6CA7A /* SHA2.swift */, + 660BBB9583DB947DB3A048A0 /* Collection+Extension.swift */, + 660BB71E69B75077967CE687 /* Cipher.swift */, + 660BB56D86EA67C397D97E4E /* Padding.swift */, + 660BBB074D45462CB8D6D086 /* RandomAccessCryptor.swift */, + 660BBC24E9C194110A5ADED4 /* String+Extension.swift */, + 660BB5B239E1B2BC3BDA47A0 /* UInt64+Extension.swift */, + 660BB521E5B40346D865AF79 /* ZeroPadding.swift */, + 660BB52399A43573D51E26E6 /* SecureBytes.swift */, + 660BBD3C1756EAE55528C2A3 /* UInt32+Extension.swift */, + 660BB9F128FBFECA116F838E /* Updatable.swift */, + 660BB84ECDAC06DF8A370C00 /* IntegerConvertible.swift */, + 660BBF10747F6743A335F6D9 /* BlockCipher.swift */, + 660BBFB61C5945D61F956A86 /* Digest.swift */, + 660BB08F437B180191B7E8B7 /* BlockMode */, + 660BB961FF0DD677BD299896 /* Authenticator.swift */, + 660BB0AA9740EF11D34188AB /* Blowfish.swift */, + 660BB0EDACEF4F3A11D45AA9 /* SHA3.swift */, + 660BB357ABC9D61A4FE9FC40 /* PKCS7.swift */, + 660BBE903D7FF61A49962895 /* Bit.swift */, + ); + path = CryptoSwift; + sourceTree = ""; + }; + 660BBE68D5D2C911182BDFBE /* VTopNotification */ = { + isa = PBXGroup; + children = ( + 660BBBAC2F5E734910E2F1FC /* VTopNotification.xib */, + 660BB14B1226E5D778D9EFB2 /* VTopNotification.swift */, + ); + path = VTopNotification; + sourceTree = ""; + }; + F976D4FC1E68747800708D6A = { + isa = PBXGroup; + children = ( + F976D5081E68747800708D6A /* GeneralUtils */, + F976D5071E68747800708D6A /* Products */, + 660BB40C90C48543A4A5D098 /* GeneralUtils.podspec */, + ); + sourceTree = ""; + }; + F976D5071E68747800708D6A /* Products */ = { + isa = PBXGroup; + children = ( + F976D5061E68747800708D6A /* GeneralUtils.framework */, + ); + name = Products; + sourceTree = ""; + }; + F976D5081E68747800708D6A /* GeneralUtils */ = { + isa = PBXGroup; + children = ( + F983E1251E69ADF4008FEC23 /* Assets.xcassets */, + F976D5091E68747800708D6A /* GeneralUtils.h */, + F976D50A1E68747800708D6A /* Info.plist */, + 660BBBC081AE41EEA62CFDB5 /* commonUtils */, + 660BB27368730D615070D1E2 /* libs */, + 660BB4A65AF559E60AD04599 /* ui */, + 660BB35AE8A552BDA1358CF8 /* models */, + ); + path = GeneralUtils; + sourceTree = ""; + }; +/* End PBXGroup section */ + +/* Begin PBXHeadersBuildPhase section */ + F976D5031E68747800708D6A /* Headers */ = { + isa = PBXHeadersBuildPhase; + buildActionMask = 2147483647; + files = ( + F976D5391E6902DC00708D6A /* Kingfisher.h in Headers */, + F976D50B1E68747800708D6A /* GeneralUtils.h in Headers */, + 660BBC607B7C9EEC7AA35F56 /* Toaster.h in Headers */, + 660BBEB5FF4B1440CBE3ED42 /* DrawerController.h in Headers */, + ); + runOnlyForDeploymentPostprocessing = 0; + }; +/* End PBXHeadersBuildPhase section */ + +/* Begin PBXNativeTarget section */ + F976D5051E68747800708D6A /* GeneralUtils */ = { + isa = PBXNativeTarget; + buildConfigurationList = F976D50E1E68747800708D6A /* Build configuration list for PBXNativeTarget "GeneralUtils" */; + buildPhases = ( + F976D5011E68747800708D6A /* Sources */, + F976D5021E68747800708D6A /* Frameworks */, + F976D5031E68747800708D6A /* Headers */, + F976D5041E68747800708D6A /* Resources */, + ); + buildRules = ( + ); + dependencies = ( + ); + name = GeneralUtils; + productName = GeneralUtils; + productReference = F976D5061E68747800708D6A /* GeneralUtils.framework */; + productType = "com.apple.product-type.framework"; + }; +/* End PBXNativeTarget section */ + +/* Begin PBXProject section */ + F976D4FD1E68747800708D6A /* Project object */ = { + isa = PBXProject; + attributes = { + LastUpgradeCheck = 0820; + ORGANIZATIONNAME = english; + TargetAttributes = { + F976D5051E68747800708D6A = { + CreatedOnToolsVersion = 8.2; + LastSwiftMigration = 0820; + ProvisioningStyle = Automatic; + }; + }; + }; + buildConfigurationList = F976D5001E68747800708D6A /* Build configuration list for PBXProject "GeneralUtils" */; + compatibilityVersion = "Xcode 3.2"; + developmentRegion = English; + hasScannedForEncodings = 0; + knownRegions = ( + en, + ); + mainGroup = F976D4FC1E68747800708D6A; + productRefGroup = F976D5071E68747800708D6A /* Products */; + projectDirPath = ""; + projectRoot = ""; + targets = ( + F976D5051E68747800708D6A /* GeneralUtils */, + ); + }; +/* End PBXProject section */ + +/* Begin PBXResourcesBuildPhase section */ + F976D5041E68747800708D6A /* Resources */ = { + isa = PBXResourcesBuildPhase; + buildActionMask = 2147483647; + files = ( + 660BBC9CC373AAB73C6C74E2 /* GeneralUtils.podspec in Resources */, + 660BB9A6AE5DC32DE19DBABF /* ViewTopBar.xib in Resources */, + F983E1261E69ADF4008FEC23 /* Assets.xcassets in Resources */, + 660BB3B75EE3FD06FCEA216B /* VTopNotification.xib in Resources */, + ); + runOnlyForDeploymentPostprocessing = 0; + }; +/* End PBXResourcesBuildPhase section */ + +/* Begin PBXSourcesBuildPhase section */ + F976D5011E68747800708D6A /* Sources */ = { + isa = PBXSourcesBuildPhase; + buildActionMask = 2147483647; + files = ( + F976D53A1E6902DC00708D6A /* Kingfisher.swift in Sources */, + F976D53D1E6902DC00708D6A /* RequestModifier.swift in Sources */, + F976D53E1E6902DC00708D6A /* Resource.swift in Sources */, + 660BB29C372A958C0B86C416 /* Queue.swift in Sources */, + 660BB3029621648615E3E9E1 /* FileUtils.swift in Sources */, + 660BB5A0E9B5F854773C2B7C /* CacheUtils.swift in Sources */, + 660BB3171CAED790D4BE5B12 /* CommonUtils.swift in Sources */, + 660BB6A863BAE2C92F215CF9 /* DialogUtils.swift in Sources */, + 660BB3149D2BBC2BEF0E2CA7 /* RecordUtils.swift in Sources */, + 660BBFB98C0904C89DCFD491 /* DownloadTask.swift in Sources */, + 660BB368E7B84778781FCE3C /* NetWorkUtils.swift in Sources */, + 660BB90C319A5DAEAD289D9D /* DataTypeUtils.swift in Sources */, + 660BB52A9CABD5BF9FAB9D37 /* CommonExtension.swift in Sources */, + 660BBA1E335DD4E71931DDF8 /* PreferenceUtils.swift in Sources */, + 660BBFDEFD7AA2DFDBF25937 /* StringExtension.swift in Sources */, + 660BBBDACD3534EB52AEC32F /* DictionaryTransform.swift in Sources */, + 660BB6EB1178785DF70C6083 /* HexColorTransform.swift in Sources */, + 660BB70E3CD72CAF4737F3F6 /* TransformOf.swift in Sources */, + 660BBB4946D8F14B33D7B434 /* EnumOperators.swift in Sources */, + 660BB1CED2484BBB77382C52 /* TransformType.swift in Sources */, + 660BB6E884453AC44D47C904 /* EnumTransform.swift in Sources */, + F976D52E1E6902DC00708D6A /* Box.swift in Sources */, + F976D5411E6902DC00708D6A /* UIButton+Kingfisher.swift in Sources */, + 660BBA78A2FB3117F3F0F105 /* DataTransform.swift in Sources */, + 660BBA307B2FAAC75FAB932C /* MapError.swift in Sources */, + 660BB509C00D339853CD3516 /* URLTransform.swift in Sources */, + 660BBC1AD7840540E6234A84 /* NSDecimalNumberTransform.swift in Sources */, + 660BBE9717148FD1FD0A6B53 /* ISO8601DateTransform.swift in Sources */, + 660BB564D493CC0EA4F7E80D /* ToJSON.swift in Sources */, + 660BB598C593836339B1EBC0 /* DateTransform.swift in Sources */, + 660BB275D72E072967319D3C /* DateFormatterTransform.swift in Sources */, + F976D5401E6902DC00708D6A /* ThreadHelper.swift in Sources */, + 660BB31B77CEBBF559611F63 /* Operators.swift in Sources */, + 660BB38A40811060B4268DDF /* TransformOperators.swift in Sources */, + 660BBEE0871750BFEFD26E3E /* CustomDateFormatTransform.swift in Sources */, + 660BB28A34746B71F32CBFA2 /* FromJSON.swift in Sources */, + 660BBDE6B9635AA67A47C6C3 /* Map.swift in Sources */, + F976D5301E6902DC00708D6A /* Filter.swift in Sources */, + 660BBBA4C085D12BC882B01B /* Mappable.swift in Sources */, + 660BB876DDFD2B33CC105757 /* ImmutableMappable.swift in Sources */, + 660BBE6D5D83B258C173D089 /* Mapper.swift in Sources */, + 660BB6B4930C9C9A68A23238 /* SwiftyJSON.swift in Sources */, + 660BB4DB26E542023BE791A3 /* Cryptors.swift in Sources */, + 660BB8FE9365F2F946AD9FCA /* UInt8+Extension.swift in Sources */, + 660BBC4099897B2D268FD716 /* CSArrayType+Extensions.swift in Sources */, + 660BB39E46E69ABBE1766E3A /* NoPadding.swift in Sources */, + 660BB214E6EFB96A34FBBA3E /* Checksum.swift in Sources */, + 660BBA0B4A44F77A7231535B /* HMAC.swift in Sources */, + 660BB3DEB8563F6C19997C46 /* Utils.swift in Sources */, + 660BBD6EA511BF216FFE9807 /* BytesSequence.swift in Sources */, + F976D53F1E6902DC00708D6A /* String+MD5.swift in Sources */, + 660BBEB72FD420C5370241FF /* MD5.swift in Sources */, + 660BB763F29C94A0DFB810B9 /* UInt16+Extension.swift in Sources */, + 660BB017307C97835E430B85 /* Generics.swift in Sources */, + 660BB3F33AF55AE1AB398817 /* PKCS5.swift in Sources */, + 660BB211B3285CA16F2CC432 /* PBKDF1.swift in Sources */, + 660BB534E53CE88CE12E5BE5 /* PBKDF2.swift in Sources */, + 660BB702C71DEECC871DBCE8 /* Int+Extension.swift in Sources */, + 660BBF1814F172D685CDDFB0 /* Poly1305.swift in Sources */, + 660BB28C653560033F478E62 /* Array+Extension.swift in Sources */, + 660BB5500B0E8B28CFBD0AA3 /* DigestType.swift in Sources */, + 660BB02813284FF82C9A5C68 /* RandomBytesSequence.swift in Sources */, + 660BB722BC16861C5A13A71C /* Rabbit.swift in Sources */, + 660BB34B0E661054F3EE3F24 /* AES+Foundation.swift in Sources */, + 660BB0AB7BCC0CD54BC3F694 /* Data+Extension.swift in Sources */, + 660BBAA747957EEF9193D5D1 /* HMAC+Foundation.swift in Sources */, + 660BBD38F499BDC8FD830503 /* Utils+Foundation.swift in Sources */, + F976D5311E6902DC00708D6A /* Image.swift in Sources */, + 660BBBDF4CE07E9369B7A0BE /* Rabbit+Foundation.swift in Sources */, + F976D5321E6902DC00708D6A /* ImageCache.swift in Sources */, + 660BBA5A1887353812391145 /* Blowfish+Foundation.swift in Sources */, + 660BB53FAFFF909C2E1C9BCB /* ChaCha20+Foundation.swift in Sources */, + 660BB2B063B9EEB6BAE10A4D /* CSArrayType+Foundation.swift in Sources */, + F976D53B1E6902DC00708D6A /* KingfisherManager.swift in Sources */, + 660BB195A1D42FC892A02A44 /* String+FoundationExtension.swift in Sources */, + 660BBED8076643223A1A1F9F /* SHA1.swift in Sources */, + 660BB63DEC21DA281E71D7FB /* AES.swift in Sources */, + 660BBFF1A3DE36950FF834FA /* ChaCha20.swift in Sources */, + 660BB5F6F9E8243D2BDC44F4 /* SHA2.swift in Sources */, + 660BB3D0D6B9F632CA86D222 /* Collection+Extension.swift in Sources */, + 660BBBAF48437D32BC2E9ED6 /* Cipher.swift in Sources */, + 660BB0CDC8E38699F67BDCDF /* Padding.swift in Sources */, + 660BB922FAB4EFFC6DA16A90 /* RandomAccessCryptor.swift in Sources */, + 660BB674657F1FBF15DDABE5 /* String+Extension.swift in Sources */, + 660BB99342616A64D8779A24 /* UInt64+Extension.swift in Sources */, + 660BB73DAF74E5D158619545 /* ZeroPadding.swift in Sources */, + 660BBCBA4021E9807BC26C44 /* SecureBytes.swift in Sources */, + 660BB29A28A9512DE1B658A1 /* UInt32+Extension.swift in Sources */, + 660BB567122A08A7880178BE /* Updatable.swift in Sources */, + 660BBFDE1C1F2729DA32D9A3 /* IntegerConvertible.swift in Sources */, + 660BBE32F64C4A63C38A2A33 /* BlockCipher.swift in Sources */, + 660BBE6E74262696D06D3396 /* Digest.swift in Sources */, + F976D52F1E6902DC00708D6A /* CacheSerializer.swift in Sources */, + 660BB3747F292ACB52E42079 /* CBC.swift in Sources */, + 660BB9F41D77949A45917C40 /* CFB.swift in Sources */, + 660BB883A116CE74CC9EE7D8 /* CTR.swift in Sources */, + 660BB62EEC22830D63048FE8 /* ECB.swift in Sources */, + 660BB36DCF3F46251B8EE3FB /* OFB.swift in Sources */, + 660BB94B68EB2F4D5EBFF98D /* PCBC.swift in Sources */, + 660BBEAFEE4B7074195BB228 /* BlockMode.swift in Sources */, + 660BBA04490927989BAE074E /* BlockModeWorker.swift in Sources */, + F976D5381E6902DC00708D6A /* Indicator.swift in Sources */, + 660BB23BB6D055996A8BF62B /* BlockModeOptions.swift in Sources */, + 660BB39B8103E48A8CCD11E4 /* RandomAccessBlockModeWorker.swift in Sources */, + F976D53C1E6902DC00708D6A /* KingfisherOptionsInfo.swift in Sources */, + 660BB271F8FC8E5BA195C74E /* Authenticator.swift in Sources */, + 660BB4EB34BB99E2AEFA0329 /* Blowfish.swift in Sources */, + 660BB7B90D211A04BE805BCA /* SHA3.swift in Sources */, + 660BBC24B162B9D0627A204B /* PKCS7.swift in Sources */, + 660BB9566076EE2DDC7CE2E8 /* Bit.swift in Sources */, + 660BB09490F2E44D8A54B835 /* SCLAlertView.swift in Sources */, + 660BB87ADEE46A00BFB1E2AD /* SCLExtensions.swift in Sources */, + 660BBCFB13F7C0980EF8844A /* ToastView.swift in Sources */, + 660BB096980E50195EC9E6C4 /* ToastWindow.swift in Sources */, + 660BB10AC416E1F583DB5781 /* ToastCenter.swift in Sources */, + F976D5351E6902DC00708D6A /* ImageProcessor.swift in Sources */, + 660BBDCD6C885D47F48F2711 /* Toast.swift in Sources */, + F976D5171E69025200708D6A /* Session.swift in Sources */, + 660BB47326AA4D3CEB5D959F /* SwiftOverlays.swift in Sources */, + 660BBA8F2D1E0B38B941AA5D /* SecurityUtils.swift in Sources */, + 660BBD3D9677DACCF050D2A6 /* BasePageViewController.swift in Sources */, + 660BB4C4C7B206E20897C273 /* ViewTopBar.swift in Sources */, + 660BBC1564A61534A95EE11F /* ComboBox.swift in Sources */, + 660BB6623229B3104AC3F530 /* DropDown.swift in Sources */, + 660BBB7A0F35D6324DE5FCA5 /* DPDConstants.swift in Sources */, + 660BB9320EDFA44DB9E76A5A /* DropDownCell.swift in Sources */, + 660BB977B861049752788962 /* DPDKeyboardListener.swift in Sources */, + 660BBDC2F499F5A06289EDA4 /* DPDUIView+Extension.swift in Sources */, + F976D5371E6902DC00708D6A /* ImageView+Kingfisher.swift in Sources */, + 660BBD46DC6D3DF2DF46EEC4 /* BaseCell.swift in Sources */, + F976D52D1E6902DC00708D6A /* AnimatedImageView.swift in Sources */, + 660BB7348DC81863AC0B7D69 /* CellLoadMore.swift in Sources */, + F976D5361E6902DC00708D6A /* ImageTransition.swift in Sources */, + 660BBC4AF5B23D206515241F /* BaseTbLoadData.swift in Sources */, + 660BBED47DCF543CFF09130A /* UITableViewLoading.swift in Sources */, + 660BBE969598871ADCCC5A46 /* UITableViewLoadMore.swift in Sources */, + 660BB2B2F6151FFF78E72CC8 /* UITableViewLoadDataBg.swift in Sources */, + 660BB33A23DDEC11377AFBC6 /* UITableViewLoadDataFromUIThread.swift in Sources */, + 660BBF78048DEF820E87FC3E /* UICollectionViewLoading.swift in Sources */, + 660BB3BDAECA7622691BAA71 /* UICollectionViewLoadData.swift in Sources */, + 660BBBC1CC0A02BE671BC7C2 /* VTopNotification.swift in Sources */, + 660BB7FEF1D1C33D574AD39F /* UIViewCustom.swift in Sources */, + 660BB7A6680B8DC96970636D /* ISRadioButton.swift in Sources */, + 660BB1470B2BD1017A147821 /* UILabelCustom.swift in Sources */, + 660BB05547B110F273DFEBFE /* UIButtonCustom.swift in Sources */, + 660BB22A39A192A41D4F3344 /* VPlayerControl.swift in Sources */, + 660BB401D73E4F771BE53A63 /* FloatRatingView.swift in Sources */, + 660BBB256B6DBCE6A136D1D8 /* UITextViewCustom.swift in Sources */, + 660BB5EDEC866BD4D755F3F6 /* UIImageViewCustom.swift in Sources */, + 660BB4E07507BBD9FFD59844 /* UILableCustomLeftImage.swift in Sources */, + 660BB296CC86AD7275DD7EBF /* UIViewCustomGradientBg.swift in Sources */, + F976D5331E6902DC00708D6A /* ImageDownloader.swift in Sources */, + 660BB6418F3B36DB8CAB963E /* UIViewCustomPressHightLight.swift in Sources */, + 660BB9F302854FD3B6394FB0 /* DrawerController.swift in Sources */, + 660BBE9AEB71901AB0FB1FD6 /* DrawerVisualState.swift in Sources */, + 660BBE0EA3C641CAB4E13722 /* AnimatedMenuButton.swift in Sources */, + 660BBD0FE3DB483CBF87B2DD /* DrawerBarButtonItem.swift in Sources */, + F976D5341E6902DC00708D6A /* ImagePrefetcher.swift in Sources */, + 660BBE3884FAF5A6041108D2 /* DrawerVisualStateManager.swift in Sources */, + 660BB1E7887AA04473643D5E /* VCContainer.swift in Sources */, + 660BBC6872E19063EAB297C1 /* AnimatedTransitioning.swift in Sources */, + 660BB6D1CEC505522F484BE3 /* AnimatedControllerFromBottom.swift in Sources */, + 660BB1A4E46E2C1130AD3978 /* BaseUIPresentationController.swift in Sources */, + 660BBEE19174C58FC617F9F0 /* BaseViewControllerShowTransculent.swift in Sources */, + 660BBA43A564BC8CDD6F4B1D /* IContainerController.swift in Sources */, + 660BB7C0931100C45D2A4709 /* GeneralMenuController.swift in Sources */, + ); + runOnlyForDeploymentPostprocessing = 0; + }; +/* End PBXSourcesBuildPhase section */ + +/* Begin XCBuildConfiguration section */ + F976D50C1E68747800708D6A /* Debug */ = { + isa = XCBuildConfiguration; + buildSettings = { + ALWAYS_SEARCH_USER_PATHS = NO; + CLANG_ANALYZER_NONNULL = YES; + CLANG_CXX_LANGUAGE_STANDARD = "gnu++0x"; + CLANG_CXX_LIBRARY = "libc++"; + CLANG_ENABLE_MODULES = YES; + CLANG_ENABLE_OBJC_ARC = YES; + CLANG_WARN_BOOL_CONVERSION = YES; + CLANG_WARN_CONSTANT_CONVERSION = YES; + CLANG_WARN_DIRECT_OBJC_ISA_USAGE = YES_ERROR; + CLANG_WARN_DOCUMENTATION_COMMENTS = YES; + CLANG_WARN_EMPTY_BODY = YES; + CLANG_WARN_ENUM_CONVERSION = YES; + CLANG_WARN_INFINITE_RECURSION = YES; + CLANG_WARN_INT_CONVERSION = YES; + CLANG_WARN_OBJC_ROOT_CLASS = YES_ERROR; + CLANG_WARN_SUSPICIOUS_MOVE = YES; + CLANG_WARN_UNREACHABLE_CODE = YES; + CLANG_WARN__DUPLICATE_METHOD_MATCH = YES; + "CODE_SIGN_IDENTITY[sdk=iphoneos*]" = "iPhone Developer"; + COPY_PHASE_STRIP = NO; + CURRENT_PROJECT_VERSION = 1; + DEBUG_INFORMATION_FORMAT = dwarf; + ENABLE_STRICT_OBJC_MSGSEND = YES; + ENABLE_TESTABILITY = YES; + GCC_C_LANGUAGE_STANDARD = gnu99; + GCC_DYNAMIC_NO_PIC = NO; + GCC_NO_COMMON_BLOCKS = YES; + GCC_OPTIMIZATION_LEVEL = 0; + GCC_PREPROCESSOR_DEFINITIONS = ( + "DEBUG=1", + "$(inherited)", + ); + GCC_WARN_64_TO_32_BIT_CONVERSION = YES; + GCC_WARN_ABOUT_RETURN_TYPE = YES_ERROR; + GCC_WARN_UNDECLARED_SELECTOR = YES; + GCC_WARN_UNINITIALIZED_AUTOS = YES_AGGRESSIVE; + GCC_WARN_UNUSED_FUNCTION = YES; + GCC_WARN_UNUSED_VARIABLE = YES; + IPHONEOS_DEPLOYMENT_TARGET = 10.2; + MTL_ENABLE_DEBUG_INFO = YES; + ONLY_ACTIVE_ARCH = YES; + SDKROOT = iphoneos; + SWIFT_ACTIVE_COMPILATION_CONDITIONS = DEBUG; + SWIFT_OPTIMIZATION_LEVEL = "-Onone"; + TARGETED_DEVICE_FAMILY = "1,2"; + VERSIONING_SYSTEM = "apple-generic"; + VERSION_INFO_PREFIX = ""; + }; + name = Debug; + }; + F976D50D1E68747800708D6A /* Release */ = { + isa = XCBuildConfiguration; + buildSettings = { + ALWAYS_SEARCH_USER_PATHS = NO; + CLANG_ANALYZER_NONNULL = YES; + CLANG_CXX_LANGUAGE_STANDARD = "gnu++0x"; + CLANG_CXX_LIBRARY = "libc++"; + CLANG_ENABLE_MODULES = YES; + CLANG_ENABLE_OBJC_ARC = YES; + CLANG_WARN_BOOL_CONVERSION = YES; + CLANG_WARN_CONSTANT_CONVERSION = YES; + CLANG_WARN_DIRECT_OBJC_ISA_USAGE = YES_ERROR; + CLANG_WARN_DOCUMENTATION_COMMENTS = YES; + CLANG_WARN_EMPTY_BODY = YES; + CLANG_WARN_ENUM_CONVERSION = YES; + CLANG_WARN_INFINITE_RECURSION = YES; + CLANG_WARN_INT_CONVERSION = YES; + CLANG_WARN_OBJC_ROOT_CLASS = YES_ERROR; + CLANG_WARN_SUSPICIOUS_MOVE = YES; + CLANG_WARN_UNREACHABLE_CODE = YES; + CLANG_WARN__DUPLICATE_METHOD_MATCH = YES; + "CODE_SIGN_IDENTITY[sdk=iphoneos*]" = "iPhone Developer"; + COPY_PHASE_STRIP = NO; + CURRENT_PROJECT_VERSION = 1; + DEBUG_INFORMATION_FORMAT = "dwarf-with-dsym"; + ENABLE_NS_ASSERTIONS = NO; + ENABLE_STRICT_OBJC_MSGSEND = YES; + GCC_C_LANGUAGE_STANDARD = gnu99; + GCC_NO_COMMON_BLOCKS = YES; + GCC_WARN_64_TO_32_BIT_CONVERSION = YES; + GCC_WARN_ABOUT_RETURN_TYPE = YES_ERROR; + GCC_WARN_UNDECLARED_SELECTOR = YES; + GCC_WARN_UNINITIALIZED_AUTOS = YES_AGGRESSIVE; + GCC_WARN_UNUSED_FUNCTION = YES; + GCC_WARN_UNUSED_VARIABLE = YES; + IPHONEOS_DEPLOYMENT_TARGET = 10.2; + MTL_ENABLE_DEBUG_INFO = NO; + SDKROOT = iphoneos; + SWIFT_OPTIMIZATION_LEVEL = "-Owholemodule"; + TARGETED_DEVICE_FAMILY = "1,2"; + VALIDATE_PRODUCT = YES; + VERSIONING_SYSTEM = "apple-generic"; + VERSION_INFO_PREFIX = ""; + }; + name = Release; + }; + F976D50F1E68747800708D6A /* Debug */ = { + isa = XCBuildConfiguration; + buildSettings = { + CLANG_ENABLE_MODULES = YES; + CODE_SIGN_IDENTITY = ""; + "CODE_SIGN_IDENTITY[sdk=iphoneos*]" = "iPhone Developer"; + DEFINES_MODULE = YES; + DYLIB_COMPATIBILITY_VERSION = 1; + DYLIB_CURRENT_VERSION = 1; + DYLIB_INSTALL_NAME_BASE = "@rpath"; + INFOPLIST_FILE = GeneralUtils/Info.plist; + INSTALL_PATH = "$(LOCAL_LIBRARY_DIR)/Frameworks"; + IPHONEOS_DEPLOYMENT_TARGET = 9.0; + LD_RUNPATH_SEARCH_PATHS = "$(inherited) @executable_path/Frameworks @loader_path/Frameworks"; + PRODUCT_BUNDLE_IDENTIFIER = com.GeneralUtils; + PRODUCT_NAME = "$(TARGET_NAME)"; + SKIP_INSTALL = YES; + SWIFT_OBJC_BRIDGING_HEADER = ""; + SWIFT_OPTIMIZATION_LEVEL = "-Onone"; + SWIFT_VERSION = 3.0; + }; + name = Debug; + }; + F976D5101E68747800708D6A /* Release */ = { + isa = XCBuildConfiguration; + buildSettings = { + CLANG_ENABLE_MODULES = YES; + CODE_SIGN_IDENTITY = ""; + "CODE_SIGN_IDENTITY[sdk=iphoneos*]" = "iPhone Developer"; + DEFINES_MODULE = YES; + DYLIB_COMPATIBILITY_VERSION = 1; + DYLIB_CURRENT_VERSION = 1; + DYLIB_INSTALL_NAME_BASE = "@rpath"; + INFOPLIST_FILE = GeneralUtils/Info.plist; + INSTALL_PATH = "$(LOCAL_LIBRARY_DIR)/Frameworks"; + IPHONEOS_DEPLOYMENT_TARGET = 9.0; + LD_RUNPATH_SEARCH_PATHS = "$(inherited) @executable_path/Frameworks @loader_path/Frameworks"; + PRODUCT_BUNDLE_IDENTIFIER = com.GeneralUtils; + PRODUCT_NAME = "$(TARGET_NAME)"; + SKIP_INSTALL = YES; + SWIFT_OBJC_BRIDGING_HEADER = ""; + SWIFT_VERSION = 3.0; + }; + name = Release; + }; +/* End XCBuildConfiguration section */ + +/* Begin XCConfigurationList section */ + F976D5001E68747800708D6A /* Build configuration list for PBXProject "GeneralUtils" */ = { + isa = XCConfigurationList; + buildConfigurations = ( + F976D50C1E68747800708D6A /* Debug */, + F976D50D1E68747800708D6A /* Release */, + ); + defaultConfigurationIsVisible = 0; + defaultConfigurationName = Release; + }; + F976D50E1E68747800708D6A /* Build configuration list for PBXNativeTarget "GeneralUtils" */ = { + isa = XCConfigurationList; + buildConfigurations = ( + F976D50F1E68747800708D6A /* Debug */, + F976D5101E68747800708D6A /* Release */, + ); + defaultConfigurationIsVisible = 0; + defaultConfigurationName = Release; + }; +/* End XCConfigurationList section */ + }; + rootObject = F976D4FD1E68747800708D6A /* Project object */; +} diff --git a/GeneralUtils/GeneralUtils.xcodeproj/project.xcworkspace/contents.xcworkspacedata b/GeneralUtils/GeneralUtils.xcodeproj/project.xcworkspace/contents.xcworkspacedata new file mode 100644 index 0000000..66efec1 --- /dev/null +++ b/GeneralUtils/GeneralUtils.xcodeproj/project.xcworkspace/contents.xcworkspacedata @@ -0,0 +1,7 @@ + + + + + diff --git a/GeneralUtils/GeneralUtils.xcodeproj/project.xcworkspace/xcuserdata/ptran.xcuserdatad/UserInterfaceState.xcuserstate b/GeneralUtils/GeneralUtils.xcodeproj/project.xcworkspace/xcuserdata/ptran.xcuserdatad/UserInterfaceState.xcuserstate new file mode 100644 index 0000000000000000000000000000000000000000..2605ff568185943a814e0e90d8a3427bd9c14386 GIT binary patch literal 56222 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 literal 0 HcmV?d00001 diff --git a/GeneralUtils/GeneralUtils.xcodeproj/project.xcworkspace/xcuserdata/ptran.xcuserdatad/xcschemes/xcschememanagement.plist b/GeneralUtils/GeneralUtils.xcodeproj/project.xcworkspace/xcuserdata/ptran.xcuserdatad/xcschemes/xcschememanagement.plist new file mode 100644 index 0000000..ee3458d --- /dev/null +++ b/GeneralUtils/GeneralUtils.xcodeproj/project.xcworkspace/xcuserdata/ptran.xcuserdatad/xcschemes/xcschememanagement.plist @@ -0,0 +1,5 @@ + + + + + diff --git a/GeneralUtils/GeneralUtils.xcodeproj/xcuserdata/ptran.xcuserdatad/xcschemes/GeneralUtils.xcscheme b/GeneralUtils/GeneralUtils.xcodeproj/xcuserdata/ptran.xcuserdatad/xcschemes/GeneralUtils.xcscheme new file mode 100644 index 0000000..02903c9 --- /dev/null +++ b/GeneralUtils/GeneralUtils.xcodeproj/xcuserdata/ptran.xcuserdatad/xcschemes/GeneralUtils.xcscheme @@ -0,0 +1,80 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/GeneralUtils/GeneralUtils.xcodeproj/xcuserdata/ptran.xcuserdatad/xcschemes/xcschememanagement.plist b/GeneralUtils/GeneralUtils.xcodeproj/xcuserdata/ptran.xcuserdatad/xcschemes/xcschememanagement.plist new file mode 100644 index 0000000..76cf394 --- /dev/null +++ b/GeneralUtils/GeneralUtils.xcodeproj/xcuserdata/ptran.xcuserdatad/xcschemes/xcschememanagement.plist @@ -0,0 +1,22 @@ + + + + + SchemeUserState + + GeneralUtils.xcscheme + + orderHint + 1 + + + SuppressBuildableAutocreation + + F976D5051E68747800708D6A + + primary + + + + + diff --git a/GeneralUtils/GeneralUtils/Assets.xcassets/ic_arrow_back_black.imageset/Contents.json b/GeneralUtils/GeneralUtils/Assets.xcassets/ic_arrow_back_black.imageset/Contents.json new file mode 100644 index 0000000..dc00c74 --- /dev/null +++ b/GeneralUtils/GeneralUtils/Assets.xcassets/ic_arrow_back_black.imageset/Contents.json @@ -0,0 +1,23 @@ +{ + "images" : [ + { + "idiom" : "universal", + "filename" : "ic_arrow_back_36pt.png", + "scale" : "1x" + }, + { + "idiom" : "universal", + "filename" : "ic_arrow_back_36pt_2x.png", + "scale" : "2x" + }, + { + "idiom" : "universal", + "filename" : "ic_arrow_back_36pt_3x.png", + "scale" : "3x" + } + ], + "info" : { + "version" : 1, + "author" : "xcode" + } +} \ No newline at end of file diff --git a/GeneralUtils/GeneralUtils/Assets.xcassets/ic_arrow_back_black.imageset/ic_arrow_back_36pt.png b/GeneralUtils/GeneralUtils/Assets.xcassets/ic_arrow_back_black.imageset/ic_arrow_back_36pt.png new file mode 100644 index 0000000000000000000000000000000000000000..aa204612c69501d0414827890b7d0f8fa83c234d GIT binary patch literal 1111 zcmV-d1gQIoP)U8P*7-ZbZ>KLZ*U+lnSp_Ufq@}0xwybFAi#%#fq@|}KQEO56)-X|e7nZL z$iTqBa9P*U#mSX{G{Bl%P*lRez;J+pfx##xwK$o9f#C}S14DXwNkIt%17i#W1A|CX zc0maP17iUL1A|C*NRTrF17iyV0~1e4YDEbH0|SF|enDkXW_m`6f}y3QrGjHhep0GJ zaAk2xYHqQDXI^rCQ9*uDVo7QW0|Nup4h9AW240u^5(W3f%sd4n162kpgNVo|1qcff zJ_s=cNG>fZg9jx8g8+j9g8_pBLjXe}Lp{R+hNBE`7{wV~7)u#fFy3PlV+vxLz;uCG zm^qSpA@ds+OO_6nTdaDlt*rOhEZL^9ePa)2-_4=K(Z%tFGm-NGmm}8}ZcXk5JW@PU zd4+f<@d@)yL(o<5icqT158+-B6_LH7;i6x}CW#w~Uy-Pgl#@Irl`kzV zeL|*8R$ca%T%Wv){2zs_iiJvgN^h0dsuZZ2sQy$tsNSU!s;Q*;LF<6_B%M@UD?LHI zSNcZ`78uqV#TeU~$eS{ozBIdFzSClfs*^S+dw;4dus<{M;#|MXC)T}S9v!D zcV!QCPhBq)ZyO(X-(bH4|NMaZz==UigLj2o41F2S6d@OB6%`R(5i>J(Puzn9wnW{e zu;hl6HK{k#IWjCVGqdJqU(99Cv(K+6*i`tgSi2;vbXD1#3jNBGs$DgVwO(~o>mN4i zHPtkqZIx>)Y(Ls5-Br|mx>vQYvH$Kwn@O`L|D75??eGkZnfg$5<;Xeg_o%+-I&+-3%01W^SH2RkDT>t<8AY({UO#lFTB>(_`g8%^e z{{R4h=>PzAFaQARU;qF*m;eA5Z<1fdMgRZ+xk*GpRCwC#)qM)WFboCo*Aohx-eOk} zJMaJsIf=Tn$po4INa);0UfT&G%K?5gC3$fjmMOPFKLu4D5T6ZI9tQxmMH$eW0WK)y znG6NYP9DiGQs#=S#mqo)%p|1D4JE@&K=I5dl){Wa$}}i=W&kO3#|b7A4rvckhAeU4 zhI*}?(I&U{@!6%cSuv7E%@1S*WvvKJ*-J}OOpH(z7iUXDwgqfYAe dWd9@d8UXXueF4I=8e{+f002ovPDHLkV1hDg(cJ(5 literal 0 HcmV?d00001 diff --git a/GeneralUtils/GeneralUtils/Assets.xcassets/ic_arrow_back_black.imageset/ic_arrow_back_36pt_2x.png b/GeneralUtils/GeneralUtils/Assets.xcassets/ic_arrow_back_black.imageset/ic_arrow_back_36pt_2x.png new file mode 100644 index 0000000000000000000000000000000000000000..adf4659a95d0026a486195799c302f48b7f675b9 GIT binary patch literal 1248 zcmV<61Rwi}P)U8P*7-ZbZ>KLZ*U+lnSp_Ufq@}0xwybFAi#%#fq@|}KQEO56)-X|e7nZL z$iTqBa9P*U#mSX{G{Bl%P*lRez;J+pfx##xwK$o9f#C}S14DXwNkIt%17i#W1A|CX zc0maP17iUL1A|C*NRTrF17iyV0~1e4YDEbH0|SF|enDkXW_m`6f}y3QrGjHhep0GJ zaAk2xYHqQDXI^rCQ9*uDVo7QW0|Nup4h9AW240u^5(W3f%sd4n162kpgNVo|1qcff zJ_s=cNG>fZg9jx8g8+j9g8_pBLjXe}Lp{R+hNBE`7{wV~7)u#fFy3PlV+vxLz;uCG zm^qSpA@ds+OO_6nTdaDlt*rOhEZL^9ePa)2-_4=K(Z%tFGm-NGmm}8}ZcXk5JW@PU zd4+f<@d@)yL(o<5icqT158+-B6_LH7;i6x}CW#w~Uy-Pgl#@Irl`kzV zeL|*8R$ca%T%Wv){2zs_iiJvgN^h0dsuZZ2sQy$tsNSU!s;Q*;LF<6_B%M@UD?LHI zSNcZ`78uqV#TeU~$eS{ozBIdFzSClfs*^S+dw;4dus<{M;#|MXC)T}S9v!D zcV!QCPhBq)ZyO(X-(bH4|NMaZz==UigLj2o41F2S6d@OB6%`R(5i>J(Puzn9wnW{e zu;hl6HK{k#IWjCVGqdJqU(99Cv(K+6*i`tgSi2;vbXD1#3jNBGs$DgVwO(~o>mN4i zHPtkqZIx>)Y(Ls5-Br|mx>vQYvH$Kwn@O`L|D75??eGkZnfg$5<;Xeg_o%+-I&+-3%01W^SH2RkDT>t<8AY({UO#lFTB>(_`g8%^e z{{R4h=>PzAFaQARU;qF*m;eA5Z<1fdMgRZ-LPzAKnw=ppEKzJ;6C2K zAmbyRz|)Dk@v%2?uNz~+;9~}8|A}c6mXI%<2W_)E(u&ML1~QO=3}m2zL6flWxaZS~ z4F%*-0a&0)1LR(i6-qwHHS)5?lnZj+GVL(Nl?Q5b3Y>Tu3gBphf;f60pR-5)j-v$% z=IDSTI2xcRjyx!mBMoYE3LL+`FA3_vkpy+($bo#$0eJ{V3e=e+1M0z%0QKSw4(iJp z7}Vkn7@I5_B+2OjlI8pZD7hs|a8oCE>=V2gQ~Y)GC_OaGkDsM0qd*HH>6WkoB;6wa zL;K8ZgLcSqW`d$gj8^(9i8E}dQG6n?#xXT=T$rF>5_6>Ymc$);Zc+Fo_E>m}5pGP7 zPb#tEW~fP;VaeS?O;Uvg_mnkBcg$7pA?+}bfed6I0~shX9s>aT9P literal 0 HcmV?d00001 diff --git a/GeneralUtils/GeneralUtils/Assets.xcassets/ic_arrow_back_black.imageset/ic_arrow_back_36pt_3x.png b/GeneralUtils/GeneralUtils/Assets.xcassets/ic_arrow_back_black.imageset/ic_arrow_back_36pt_3x.png new file mode 100644 index 0000000000000000000000000000000000000000..407150ba28adc8cde7558e5a856425a3cd15c7c1 GIT binary patch literal 1367 zcmeAS@N?(olHy`uVBq!ia0vp^IUvlz0wh)Q=eq$Z&H|6fVg?3oVGw3ym^DX&fq_{f z)7d#7AS1sdzc?emK*7`5S)rgPKP@vSm4Tt+R&qkZyaz8HJvpUv;6Ok?NYE3xClZo^ zl1mTN&1>v!oY@EhiiSIP957Tk&<VC-0%FLPH%$&@_%-rk|R0d`{IyHO$S$b&jclX;p5WO$(PUUD}lFRTs3%sUWq`Gb?XnQ+ixcU7%xKV3KDR7f|sP zJ~kkToBl_L_4|=CHmu6bp=?^s9VawcIk*MwI1E`l^mMhF*;SdF8Jd}z8Jn4%8Jv}z zZ4WcGE#}FWI4T({;Vl_%a4%UXnJa15fs)3^8J3eO6+cUhc~9e;7QLow&Du5JZ|K}y zwy`#uKmGpMg-0$P{n%ZPvtN5kJT5>mzFQT zpRk|h|DT3m2Ra?So6B2ccxolji71L^ii!%x3K|=i`QK?~+2(S0$%ZFwQ%qNyU$!*T zF*4r#EG_;_>iNy**K6De`LQlyx6100(3`Wl{+^n&D%P}TYg}pYYk9L*rdLho=T6Pm z&auCxc{lV*?XK{x>o@*?=Q7)Kv-*O-+)#_@F zdcF>Reokfn-_p8Eu5Z2F*Q><+Ew4T2J3G4k{gwN{`|2Mh-b>!7{(FAvK7q>052gR2 zf0m2enbaEn{qyQ|)BA_^taWpLUH*0c8&EL#Y7+!>a@a2CEqi4C48d;*SC|8RJe*7srr_TW@Zk_B|XRz<2UA~Js!9IO`VysW<#pjhsNwZ&s*1S zHmf-M`>0GrkAb+D{F%<9Y{kii2W29C48q0u&&)i^RGeOTKx%_Tf^Wp%#NLR#iDx5f z6L}+T6MZA^CajH|oA5R=HbHO=-v)^=3!N@ep6=w=rhopmhk^axXzvmk+^r<`4?LILt6O{wyxK0)t}WG%AC`pa0X9TKbLh*2~7YT2uNW7 literal 0 HcmV?d00001 diff --git a/GeneralUtils/GeneralUtils/Assets.xcassets/ic_arrow_drop_down.imageset/Contents.json b/GeneralUtils/GeneralUtils/Assets.xcassets/ic_arrow_drop_down.imageset/Contents.json new file mode 100644 index 0000000..bb3ac07 --- /dev/null +++ b/GeneralUtils/GeneralUtils/Assets.xcassets/ic_arrow_drop_down.imageset/Contents.json @@ -0,0 +1,21 @@ +{ + "images" : [ + { + "idiom" : "universal", + "filename" : "ic_arrow_drop_down.png", + "scale" : "1x" + }, + { + "idiom" : "universal", + "scale" : "2x" + }, + { + "idiom" : "universal", + "scale" : "3x" + } + ], + "info" : { + "version" : 1, + "author" : "xcode" + } +} \ No newline at end of file diff --git a/GeneralUtils/GeneralUtils/Assets.xcassets/ic_arrow_drop_down.imageset/ic_arrow_drop_down.png b/GeneralUtils/GeneralUtils/Assets.xcassets/ic_arrow_drop_down.imageset/ic_arrow_drop_down.png new file mode 100644 index 0000000000000000000000000000000000000000..f993f992d9b7c3bc4c4ad944ee581f1706b55e8e GIT binary patch literal 1186 zcmeAS@N?(olHy`uVBq!ia0vp^IUvlz0wh)Q=eq$Z&H|6fVg?3oVGw3ym^DX&fq_{f z)7d#7AS1sdzc?emK*7`5S)rgPKP@vSm4Tt+R&qkZyaz8HJvpUv;6Ok?NYE3xClZo^ zl1mTN&1>v!oY@EhiiSIP957Tk&<VC-0%FLPH%$&@_%-rk|R0d`{IyHO$S$b&jclX;p5WO$(PUUD}lFRTs3%sUWq`Gb?XnQ+ixcU7%xKV3KDR7f|sP zJ~kkToBl_L_4|=CHmu6bp=?^s9VawcIk*MwI1E`l^mMhF*;SdF8Jd}z8Jn4%8Jv}z zZ4WcGE#}FWI4T({;Vl_%a4%UXnJa15fs)3^8J3eO6+cUhc~9e;7QLow&Du5JZ|K}y zwy`#uKmGpMg-0$P{n%ZPvtN5kJT5>mzFQT zpRk|h|DT3m2Ra?So6B2ccxolji71L^ii!%x3K|=i`QK?~+2(S0$%ZFwQ%qNyU$!*T zF*4r#EG_;_>iNy**K6De`LQlyx6100(3`Wl{+^n&D%P}TYg}pYYk9L*rdLho=T6Pm z&auCxc{lV*?XK{x>o@*?=Q7)Kv-*O-+)#_@F zdcF>Reokfn-_p8Eu5Z2F*Q><+Ew4T2J3G4k{gwN{`|2Mh-b>!7{(FAvK7q>052gR2 zf0m2enbaEn{qyQ|)BA_^taWpLUH*0c8&EL#Y7+!>a@a2CEqi4C48d;*SC|86%6Qi(^Q|tv5GL2QoVfxEwT0<;nd2 zHp2f1qmz@4yk|6TkJ97F34zDI3|C*Ea8LtDMwlHWj zpT4BDMnuP*dt=cC9^GSJhx#rzt_nT5A1oXI+aB{bu^McdOo;;#)Jf8s+#`ACHnQ^WB}a zmT&h3yA9Xc_g*SnlituftNNOKo2Ab|V4lVY>XuGtWT>`&cG&Nfqcbq<7(8A5T-G@y GGywoR1OTW2 literal 0 HcmV?d00001 diff --git a/GeneralUtils/GeneralUtils/Assets.xcassets/placeholder.imageset/Contents.json b/GeneralUtils/GeneralUtils/Assets.xcassets/placeholder.imageset/Contents.json new file mode 100644 index 0000000..996d3e7 --- /dev/null +++ b/GeneralUtils/GeneralUtils/Assets.xcassets/placeholder.imageset/Contents.json @@ -0,0 +1,23 @@ +{ + "images" : [ + { + "idiom" : "universal", + "filename" : "placeholder.png", + "scale" : "1x" + }, + { + "idiom" : "universal", + "filename" : "placeholder@2x.png", + "scale" : "2x" + }, + { + "idiom" : "universal", + "filename" : "placeholder@3x.png", + "scale" : "3x" + } + ], + "info" : { + "version" : 1, + "author" : "xcode" + } +} \ No newline at end of file diff --git a/GeneralUtils/GeneralUtils/Assets.xcassets/placeholder.imageset/placeholder.png b/GeneralUtils/GeneralUtils/Assets.xcassets/placeholder.imageset/placeholder.png new file mode 100644 index 0000000000000000000000000000000000000000..4cc380909297f58a384b8140ebae3b53fdfa5793 GIT binary patch literal 2442 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 literal 0 HcmV?d00001 diff --git a/GeneralUtils/GeneralUtils/Assets.xcassets/placeholder.imageset/placeholder@2x.png b/GeneralUtils/GeneralUtils/Assets.xcassets/placeholder.imageset/placeholder@2x.png new file mode 100644 index 0000000000000000000000000000000000000000..1059b2c18d0cd5a20ee3f328ec595fb463c51562 GIT binary patch literal 5674 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 TWYr#;zksQ+g;BWy{@#B8kx4A8 literal 0 HcmV?d00001 diff --git a/GeneralUtils/GeneralUtils/Assets.xcassets/placeholder.imageset/placeholder@3x.png b/GeneralUtils/GeneralUtils/Assets.xcassets/placeholder.imageset/placeholder@3x.png new file mode 100644 index 0000000000000000000000000000000000000000..af1b5ed1449d9dbdd8cd563fd5b4591ab0412cd5 GIT binary patch literal 10314 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 OIiMh`EK?=*IrxA2Y + +//! Project version number for GeneralUtils. +FOUNDATION_EXPORT double GeneralUtilsVersionNumber; + +//! Project version string for GeneralUtils. +FOUNDATION_EXPORT const unsigned char GeneralUtilsVersionString[]; + +// In this header, you should import all the public headers of your framework using statements like #import + + + diff --git a/GeneralUtils/GeneralUtils/Info.plist b/GeneralUtils/GeneralUtils/Info.plist new file mode 100644 index 0000000..fbe1e6b --- /dev/null +++ b/GeneralUtils/GeneralUtils/Info.plist @@ -0,0 +1,24 @@ + + + + + CFBundleDevelopmentRegion + en + CFBundleExecutable + $(EXECUTABLE_NAME) + CFBundleIdentifier + $(PRODUCT_BUNDLE_IDENTIFIER) + CFBundleInfoDictionaryVersion + 6.0 + CFBundleName + $(PRODUCT_NAME) + CFBundlePackageType + FMWK + CFBundleShortVersionString + 1.0 + CFBundleVersion + $(CURRENT_PROJECT_VERSION) + NSPrincipalClass + + + diff --git a/GeneralUtils/GeneralUtils/commonUtils/CacheUtils.swift b/GeneralUtils/GeneralUtils/commonUtils/CacheUtils.swift new file mode 100644 index 0000000..03b5379 --- /dev/null +++ b/GeneralUtils/GeneralUtils/commonUtils/CacheUtils.swift @@ -0,0 +1,82 @@ +import Foundation + +class CacheUtils { + + static func getObj(_ key: String) -> T? { + if let jsonString:String = FileUtils.readFile(fileSubPath: key, saveTo: .Document){ + return Mapper().map(JSONString: jsonString) + } + return nil + } + + static func getListObj(_ key: String) -> [T]? { + if let jsonString:String = FileUtils.readFile(fileSubPath: key, saveTo: .Document){ + return Mapper().mapArray(JSONString: jsonString) + } + return nil + } + + static func saveObj(_ key: String, t: T){ + if let jsonString: String = Mapper().toJSONString(t){ + FileUtils.writeFile(data: jsonString, fileSubPath: key, saveTo: .Document) + } + } + + /**removeIfExits: true => sẽ remove cái cũ và thêm ở cuối*/ + static func saveObjToList(_ key: String, t: T, maxSize: Int? = nil, removeIfExits: Bool = true) where T: Equatable{ + var list: [T]? = getListObj(key) + + if list == nil { + list = [T]() + }else if removeIfExits{ + var removes = [T]() + for item in list! { + if item == t { + removes.append(item) + } + } + for item in removes { + list?.removeElement(element: item) + } + } + list?.insert(t, at: 0) + saveListObj(key, list: list!, maxSize: maxSize) + } + + @discardableResult static func removeObjFromList(_ key: String, t: T) -> Bool where T: Equatable { + var list: [T]? = getListObj(key) + if list != nil { + let result = list!.removeElement(element: t) + saveListObj(key, list: list!) + return result + } + return false + } + + static func icContaintObjInList(_ key: String, t: T) -> Bool where T: Equatable { + if let list: [T] = getListObj(key) { + return list.contains(t) + } + return false + } + + static func saveListObj(_ key: String, list: [T], maxSize: Int? = nil){ + if let maxSize = maxSize, list.count > maxSize { + var recents = [T]() + for item in list { + recents.append(item) + if recents.count >= maxSize { + break + } + } + if let jsonString: String = Mapper().toJSONString(recents){ + FileUtils.writeFile(data: jsonString, fileSubPath: key, saveTo: .Document) + } + return + } + + if let jsonString: String = Mapper().toJSONString(list){ + FileUtils.writeFile(data: jsonString, fileSubPath: key, saveTo: .Document) + } + } +} diff --git a/GeneralUtils/GeneralUtils/commonUtils/CommonExtension.swift b/GeneralUtils/GeneralUtils/commonUtils/CommonExtension.swift new file mode 100644 index 0000000..b150434 --- /dev/null +++ b/GeneralUtils/GeneralUtils/commonUtils/CommonExtension.swift @@ -0,0 +1,387 @@ +import UIKit +import Foundation + +public extension String { + public var html2AttributedString: NSAttributedString? { + guard let data = data(using: .utf8) else { return nil } + do { + return try NSAttributedString(data: data, options: [NSDocumentTypeDocumentAttribute: NSHTMLTextDocumentType, NSCharacterEncodingDocumentAttribute: String.Encoding.utf8.rawValue], documentAttributes: nil) + } catch let error as NSError { + println(error.localizedDescription) + return nil + } + } + + public var html2String: String? { + return html2AttributedString?.string + } + +} + +//extension Collection { +// /// Return a copy of `self` with its elements shuffled +// func shuffle() -> [Iterator.Element] { +// var list = Array(self) +// list.shuffleInPlace() +// return list +// } +//} +// +//extension MutableCollection where Index == Int { +// /// Shuffle the elements of `self` in-place. +// mutating func shuffleInPlace() { +// // empty and single-element collections don't shuffle +// if count < 2 { return } +// +// for i in 0.. [Element] { + var elements = [Element]() + for item in self { + elements.append(item) + } + return elements + } +} + +public extension MutableCollection where Index == Int { + /// Shuffle the elements of `self` in-place. + public mutating func shuffle() { + // empty and single-element collections don't shuffle + if count < 2 { return } + + for i in startIndex ..< endIndex - 1 { + let j = Int(arc4random_uniform(UInt32(endIndex - i))) + i + if i != j { + swap(&self[i], &self[j]) + } + } + } +} + +public extension Array where Element: Equatable { + @discardableResult public mutating func removeElement(element: Element) -> Bool { + if let index = index(of: element) { + remove(at: index) + return true + } + return false + } +} + +public extension UICollectionView { + public func reloadItemsAtPosition(_ row: Int, session: Int = 0) { + self.reloadItems(at: [IndexPath(row: row, section: session)]) + } + + public func reloadItemsAtArrayPosition(_ rows: [Int], session: Int = 0) { + var indexPaths = [IndexPath]() + for row in rows { + indexPaths.append(IndexPath(row: row, section: session)) + } + self.reloadItems(at: indexPaths) + } +} + +public extension UIImageView { + public func setRounded(_ radiusParam: CGFloat? = nil) { + // self.layer.borderWidth = 1 + // self.layer.borderColor = UIColor.blackColor().CGColor + if radiusParam != nil { + self.layer.cornerRadius = radiusParam! + } else { + let radius = self.frame.width / 2 + self.layer.cornerRadius = radius + } + self.layer.masksToBounds = true + } + + public func changeImageColor(_ tintColor: UIColor) { + self.image = self.image?.imageWithColor(tintColor) + } + + public func changeImageColor(usingTinColor: Bool) { + if usingTinColor { + self.image = self.image?.withRenderingMode(UIImageRenderingMode.alwaysTemplate) + } else { + self.image = self.image?.withRenderingMode(UIImageRenderingMode.alwaysOriginal) + } + } +} + +public extension UIImage { + public func imageWithColor(_ color1: UIColor) -> UIImage { + UIGraphicsBeginImageContextWithOptions(self.size, false, self.scale) + color1.setFill() + + let context = UIGraphicsGetCurrentContext()! as CGContext + context.translateBy(x: 0, y: self.size.height) + context.scaleBy(x: 1.0, y: -1.0); + context.setBlendMode(CGBlendMode.normal) + + let rect = CGRect(x: 0, y: 0, width: self.size.width, height: self.size.height) as CGRect + context.clip(to: rect, mask: self.cgImage!) + context.fill(rect) + + let newImage = UIGraphicsGetImageFromCurrentImageContext()! as UIImage + UIGraphicsEndImageContext() + + return newImage + } + + public func imageWithInsets(insetDimen: CGFloat) -> UIImage? { + return imageWithInset(UIEdgeInsets(top: insetDimen, left: insetDimen, bottom: insetDimen, right: insetDimen)) + } + + public func imageWithInset(_ insets: UIEdgeInsets) -> UIImage? { + UIGraphicsBeginImageContextWithOptions(CGSize(width: self.size.width + insets.left + insets.right, height: self.size.height + insets.top + insets.bottom), false, self.scale) + let origin = CGPoint(x: insets.left, y: insets.top) + self.draw(at: origin) + let imageWithInsets = UIGraphicsGetImageFromCurrentImageContext() + UIGraphicsEndImageContext() + return imageWithInsets + } + +} + + +public extension UIView { + public var parentViewController: UIViewController? { + var parentResponder: UIResponder? = self + while parentResponder != nil { + parentResponder = parentResponder!.next + if let viewController = parentResponder as? UIViewController { + return viewController + } + } + return nil + } + + public func removeAllChild() { + for subview in self.subviews { + subview.removeFromSuperview() + } + } +} + +public extension UIButton { + public func setImageWithOutAnimation(_ image: UIImage?) { + UIView.setAnimationsEnabled(false) + + setImage(image, for: .normal) + + layoutIfNeeded() + UIView.setAnimationsEnabled(true) + } + + public func setTitleWithOutAnimation(_ title: String?) { + UIView.setAnimationsEnabled(false) + + setTitle(title, for: .normal) + + layoutIfNeeded() + UIView.setAnimationsEnabled(true) + } +} + +public extension UIViewController { + /** + - func Chi them buton Next, Pre, Done. không xử lý di chuyển layout khi keyboard open + textFields: Phai la UITextField, hoac UITextView + + let field1 = UITextField() + let field2 = UITextField() + addInputAccessoryForTextFields([field1, field2], dismissable: true, previousNextable: true) + + Chu y phai co 2 image: prev_arrow_white, next_arrow_white + */ + public func addInputAccessoryForTextFields(_ textFields: [UIView], dismissable: Bool = true, previousNextable: Bool = true) { + for (index, textField) in textFields.enumerated() { + let toolbar: UIToolbar = UIToolbar() + toolbar.sizeToFit() + + var items = [UIBarButtonItem]() + if previousNextable { + let previousButton = UIBarButtonItem(image: #imageLiteral(resourceName:"prev_arrow_white"), style: .plain, target: nil, action: nil) + previousButton.width = 30 + if textField == textFields.first { + previousButton.isEnabled = false + } else { + previousButton.target = textFields[index - 1] + previousButton.action = #selector(UITextField.becomeFirstResponder) + } + + let nextButton = UIBarButtonItem(image: #imageLiteral(resourceName:"next_arrow_white"), style: .plain, target: nil, action: nil) + nextButton.width = 30 + if textField == textFields.last { + nextButton.isEnabled = false + } else { + nextButton.target = textFields[index + 1] + nextButton.action = #selector(UITextField.becomeFirstResponder) + } + + items.append(contentsOf: [previousButton, nextButton]) + } + + if dismissable { + let spacer = UIBarButtonItem(barButtonSystemItem: .flexibleSpace, target: nil, action: nil) + let doneButton = UIBarButtonItem(barButtonSystemItem: .done, target: view, action: #selector(UIView.endEditing)) + items.append(contentsOf: [spacer, doneButton]) + } + + toolbar.setItems(items, animated: false) + if textField is UITextView { + (textField as! UITextView).inputAccessoryView = toolbar + } else if textField is UISearchBar { + (textField as! UISearchBar).inputAccessoryView = toolbar + } else { + (textField as! UITextField).inputAccessoryView = toolbar + } + } + } +} + +public extension URL { + public init?(filePathOrUrl: String) { + if filePathOrUrl.start(with: "http") { + self.init(string: filePathOrUrl) + } else { + self.init(fileURLWithPath: filePathOrUrl) + } + } +} + +public extension UIColor { + public convenience init(hexString: String) { + let hex = hexString.trimmingCharacters(in: CharacterSet.alphanumerics.inverted) + var int = UInt32() + Scanner(string: hex).scanHexInt32(&int) + let a, r, g, b: UInt32 + switch hex.characters.count { + case 3: // RGB (12-bit) + (a, r, g, b) = (255, (int >> 8) * 17, (int >> 4 & 0xF) * 17, (int & 0xF) * 17) + case 6: // RGB (24-bit) + (a, r, g, b) = (255, int >> 16, int >> 8 & 0xFF, int & 0xFF) + case 8: // ARGB (32-bit) + (a, r, g, b) = (int >> 24, int >> 16 & 0xFF, int >> 8 & 0xFF, int & 0xFF) + default: + (a, r, g, b) = (1, 1, 1, 0) + } + self.init(red: CGFloat(r) / 255, green: CGFloat(g) / 255, blue: CGFloat(b) / 255, alpha: CGFloat(a) / 255) + } +} + +public extension NotificationCenter { + public func setObserver(_ observer: AnyObject, selector: Selector, name: String?, object: AnyObject?) { + self.removeObserver(observer, name: name.map { NSNotification.Name(rawValue: $0) }, object: object) + self.addObserver(observer, selector: selector, name: name.map { NSNotification.Name(rawValue: $0) }, object: object) + } +} + +public extension UIApplication { + public class func topViewController(_ base: UIViewController? = UIApplication.shared.keyWindow?.rootViewController) -> UIViewController? { + if let nav = base as? UINavigationController { + return topViewController(nav.visibleViewController) + } + if let tab = base as? UITabBarController { + if let selected = tab.selectedViewController { + return topViewController(selected) + } + } + if let presented = base?.presentedViewController { + return topViewController(presented) + } + return base + } +} + + +public func arc4random(_ type: T.Type) -> T { + var r: T = 0 + arc4random_buf(&r, MemoryLayout.size) + return r +} + +public extension UInt64 { + public static func random(lower: UInt64 = min, upper: UInt64 = max) -> UInt64 { + var m: UInt64 + let u = upper - lower + var r = arc4random(UInt64.self) + + if u > UInt64(Int64.max) { + m = 1 + ~u + } else { + m = ((max - (u * 2)) + 1) % u + } + + while r < m { + r = arc4random(UInt64.self) + } + + return (r % u) + lower + } +} + +public extension Int64 { + public static func random(lower: Int64 = min, upper: Int64 = max) -> Int64 { + let (s, overflow) = Int64.subtractWithOverflow(upper, lower) + let u = overflow ? UInt64.max - UInt64(~s) : UInt64(s) + let r = UInt64.random(upper: u) + + if r > UInt64(Int64.max) { + return Int64(r - (UInt64(~lower) + 1)) + } else { + return Int64(r) + lower + } + } +} + +public extension UInt32 { + public static func random(lower: UInt32 = min, upper: UInt32 = max) -> UInt32 { + return arc4random_uniform(upper - lower) + lower + } +} + +public extension Int32 { + public static func random(lower: Int32 = min, upper: Int32 = max) -> Int32 { + let r = arc4random_uniform(UInt32(Int64(upper) - Int64(lower))) + return Int32(Int64(r) + Int64(lower)) + } +} + +public extension UInt { + public static func random(lower: UInt = min, upper: UInt = max) -> UInt { + return UInt(UInt64.random(lower: UInt64(lower), upper: UInt64(upper))) + } +} + +public extension Int { + public static func random(lower: Int = min, upper: Int = max) -> Int { + return Int(Int64.random(lower: Int64(lower), upper: Int64(upper))) + } +} diff --git a/GeneralUtils/GeneralUtils/commonUtils/CommonUtils.swift b/GeneralUtils/GeneralUtils/commonUtils/CommonUtils.swift new file mode 100644 index 0000000..4acebc8 --- /dev/null +++ b/GeneralUtils/GeneralUtils/commonUtils/CommonUtils.swift @@ -0,0 +1,118 @@ +import Foundation +import UIKit + +public class CommonUtils{ + + /** + let url = FileUtils.getURL(fileSubPath: self.songRecorded.getSubPath(), location: .Document) + CommonUtils.shareIntent(self.viewController!, shareText: self.songRecorded.fileNameRecorded, shareUrl: url, excludedActivityTypes: [.addToReadingList, .postToFacebook]) + */ + public static func shareIntent(_ viewController: UIViewController, shareText: String, shareUrl: URL, shareImage: UIImage? = nil, excludedActivityTypes: [UIActivityType]? = nil) { + var activityItems = [shareText, shareUrl] as [Any] + if let shareImage = shareImage{ + activityItems.append(shareImage) + } + + let vc = UIActivityViewController(activityItems: activityItems, applicationActivities: []) + if let excludedActivityTypes = excludedActivityTypes { + vc.excludedActivityTypes = excludedActivityTypes + } + + viewController.present(vc, animated: true, completion: nil) + } + + + public static func showToastLong(text: String){ + Toast(text: text, duration: Delay.long).show() + } + + public static func showToastShort(text: String){ + ToastCenter.default.cancelAll() + Toast(text: text, duration: Delay.short).show() + } + + public static func showTopNotification(title: String?, subTitle: String?){ + let notificationView = VTopNotification() + notificationView.setData(title: title, subTitle: subTitle) + let width = UIScreen.main.bounds.width + notificationView.frame.size.width = width + notificationView.frame.origin.x = width/2 + + var height = StringUtils.heightWithConstrainedWidth(title, width: width - 90, font: UIFont.boldSystemFont(ofSize: 16)) + StringUtils.heightWithConstrainedWidth(title, width: width - 90, font: UIFont.systemFont(ofSize: 16)) + if height < 50 { height = 50 } + notificationView.frame.size.height = height + 20 + notificationView.frame.origin.y = 0 + UIViewController.showNotificationOnTopOfStatusBar(notificationView, duration: 5) + } + + // ======== Thread ======== + public static func delayExcute(_ delay: TimeInterval, queueParam: DispatchQueue? = nil, block: @escaping ()->()) { + var queue: DispatchQueue! + if queueParam == nil { + queue = DispatchQueue.main + } else { queue = queueParam } + let time = DispatchTime.now() + Double(Int64(delay * Double(NSEC_PER_SEC))) / Double(NSEC_PER_SEC) + queue.asyncAfter(deadline: time, execute: block) + } + + public static func executebackgroundThread(_ background: @escaping (() -> Void), completion: (() -> Void)?) { + DispatchQueue.global().async { + background() + if let completion = completion{ + DispatchQueue.main.async(execute: { + completion() + }) + } + } + } + + public static func executebackgroundThread(_ background: @escaping (() -> Void)){ + executebackgroundThread(background, completion: nil) + } + + public static func excuteOnMainThread(_ funcExcute: @escaping (() -> Void)) { + DispatchQueue.main.async(execute: { + funcExcute() + }) + } + + // set languge: vi, en + static var currentBundle: Bundle? + public static func setLanguge(languageCode: String){ + if let path = Bundle.main.path(forResource: languageCode, ofType: "lproj"){ + CommonUtils.currentBundle = Bundle.init(path: path) + } + } +} + +// Global function +public func setImageUrl(imv: UIImageView, imageUrl: String?) { + if let imageUrl = imageUrl { + let urlStr = imageUrl.addingPercentEncoding(withAllowedCharacters: CharacterSet.urlQueryAllowed)! + var url: URL? + if urlStr.start(with: "http") { + url = URL(string: urlStr) + }else{ + url = URL(fileURLWithPath: urlStr) + } + + if let url = url{ + imv.kf.setImage(with: url, placeholder: #imageLiteral(resourceName: "placeholder")) + return + } + } + imv.image = #imageLiteral(resourceName: "placeholder") +} + +public func LocalizedString(_ key: String) -> String{ + if let currentBundle = CommonUtils.currentBundle { + return NSLocalizedString(key, tableName: nil, bundle: currentBundle, value: "", comment: key) + } + + return NSLocalizedString(key, comment: key) +} + +public func println(_ items: Any){ + print("aaaa: \(items)") +} + diff --git a/GeneralUtils/GeneralUtils/commonUtils/DataTypeUtils.swift b/GeneralUtils/GeneralUtils/commonUtils/DataTypeUtils.swift new file mode 100644 index 0000000..cd94f41 --- /dev/null +++ b/GeneralUtils/GeneralUtils/commonUtils/DataTypeUtils.swift @@ -0,0 +1,70 @@ +import Foundation +import UIKit + +public class DataTypeUtils { + + public static func getCurrentTimeMillis() -> Double { + return NSDate().timeIntervalSince1970 * 1000 + } + + public static func getCurrentTimeSecond() -> Double { + return NSDate().timeIntervalSince1970 + } + + /** + * Result sample: 05:09 + */ + public static func convertTimeDisplayInPlay(miliSecond: Int64) -> String { + let seconds = (miliSecond / 1000) % 60; + let secondsStr: String, minuteStr: String; + if (seconds >= 10) { + secondsStr = String(seconds); + } else { + secondsStr = "0\(seconds)"; + } + let minutes = ((miliSecond - seconds) / 1000) / 60; + minuteStr = String(minutes) + return "\(minuteStr):\(secondsStr)" + } + + /** + * example: 1k, 1m + */ + public static func getCountStringDisplay(count: Int) -> String { + if count < 1000 { + return String(count) + } + if (count > 1000000) { + return "\(count % 1000000)m"; + } + return "\(count % 1000)k"; + + } + + public static func resizeImage(image: UIImage, targetSize: CGSize) -> UIImage { + let size = image.size + + let widthRatio = targetSize.width / image.size.width + let heightRatio = targetSize.height / image.size.height + + // Figure out what our orientation is, and use that to form the rectangle + var newSize: CGSize + if (widthRatio > heightRatio) { + newSize = CGSize.init(width: size.width * heightRatio, height: size.height * heightRatio) + } else { + newSize = CGSize.init(width: size.width * widthRatio, height: size.height * widthRatio) + } + + // This is the rect that we've calculated out and this is what is actually used below + let rect = CGRect.init(x: 0, y: 0, width: newSize.width, height: newSize.height) + + // Actually do the resizing to the rect using the ImageContext stuff + UIGraphicsBeginImageContextWithOptions(newSize, false, 1.0) + image.draw(in: rect) + let newImage = UIGraphicsGetImageFromCurrentImageContext() + UIGraphicsEndImageContext() + + return newImage! + } +} + diff --git a/GeneralUtils/GeneralUtils/commonUtils/DialogUtils.swift b/GeneralUtils/GeneralUtils/commonUtils/DialogUtils.swift new file mode 100644 index 0000000..14b4faa --- /dev/null +++ b/GeneralUtils/GeneralUtils/commonUtils/DialogUtils.swift @@ -0,0 +1,183 @@ +import Foundation +import UIKit + +public class DialogUtils { + /** + // Button + kButtonFont: UIFont + buttonCornerRadius : CGFloat + showCloseButton: Bool + kButtonHeight: CGFloat + + // Circle Image + showCircularIcon: Bool + kCircleTopPosition: CGFloat + kCircleBackgroundTopPosition: CGFloat + kCircleHeight: CGFloat + kCircleIconHeight: CGFloat + + // Text + kTitleFont: UIFont + kTitleTop:CGFloat + kTitleHeight:CGFloat + kTextFont: UIFont + kTextHeight: CGFloat + kTextFieldHeight: CGFloat + kTextViewdHeight: CGFloat + + // View + kDefaultShadowOpacity: CGFloat + kWindowWidth: CGFloat + kWindowHeight: CGFloat + shouldAutoDismiss: Bool // Set this false to 'Disable' Auto hideView when SCLButton is tapped + fieldCornerRadius : CGFloat + contentViewCornerRadius : CGFloat + disableTapGesture: Bool // set this to true if adding tableview to subView + + + let alert = DialogUtils.builderDialog(SCLAlertView.SCLAppearance( + showCloseButton: false + )) + */ + public static func builderDialog(_ appearance: SCLAlertView.SCLAppearance? = nil) -> SCLAlertView { + if let appearance = appearance { + return SCLAlertView(appearance: appearance) + } else { + return SCLAlertView() + } + } + + public static func builderDialog(showCloseButton: Bool, showTitle: Bool) -> SCLAlertView { + if !showTitle { + return DialogUtils.builderDialog(SCLAlertView.SCLAppearance(kTitleHeight: 10, showCloseButton: showCloseButton)) + } else { + return DialogUtils.builderDialog(SCLAlertView.SCLAppearance(kTitleHeight: 10, showCloseButton: showCloseButton)) + } + } + + @discardableResult public static func showInfo(titleParam: String? = nil, messageParam: String?, closeText: String = "OK", type: TypeDialog = .info) -> SCLAlertViewResponder { + var title: String!, subTitle: String! + var alertView: SCLAlertView! + if messageParam == nil { + subTitle = "" + } else { + subTitle = messageParam! + } + + if titleParam == nil { + title = "" + let appearance = SCLAlertView.SCLAppearance( + kTitleHeight: 10 + ) + alertView = SCLAlertView(appearance: appearance) + } else { + title = titleParam! + alertView = SCLAlertView.init() + } + if type == .info { + return alertView.showInfo(title, subTitle: subTitle, closeButtonTitle: closeText) + } else { + return alertView.showError(title, subTitle: subTitle, closeButtonTitle: closeText) + } + } + + + public static func showInfo(titleParam: String? = nil, customView: UIView, heightView: Int) { + customView.frame = CGRect.init(x: 0, y: 0, width: 270, height: heightView) + var alertView: SCLAlertView! + var appearance: SCLAlertView.SCLAppearance! + if titleParam == nil { + appearance = SCLAlertView.SCLAppearance( + kTitleHeight: 10, + kWindowWidth: 310, + showCircularIcon: false + ) + } else { + appearance = SCLAlertView.SCLAppearance( + kWindowWidth: 310, + showCircularIcon: false + ) + } + alertView = SCLAlertView(appearance: appearance) + alertView.customSubview = customView + + alertView.showInfo(titleParam ?? "", subTitle: "").setDismissBlock { + customView.removeFromSuperview() + } + } + + @discardableResult public static func showQuestion(titleParam: String? = nil, messageParam: String?, type: TypeDialog = .info, yesTitle: String = "Đồng ý", noTitle: String = "Không", yesAction: @escaping () -> Void) -> SCLAlertViewResponder { + var title: String!, subTitle: String! + var alertView: SCLAlertView! + if messageParam == nil { + subTitle = "" + } else { + subTitle = messageParam! + } + + if titleParam == nil { + title = "" + let appearance = SCLAlertView.SCLAppearance( + kTitleHeight: 10 + ) + alertView = SCLAlertView(appearance: appearance) + } else { + title = titleParam! + alertView = SCLAlertView.init() + } + alertView.addButton(yesTitle, action: yesAction) + if type == .info { + return alertView.showInfo(title, subTitle: subTitle, closeButtonTitle: noTitle) + } else { + return alertView.showError(title, subTitle: subTitle, closeButtonTitle: noTitle) + } + } + + + @discardableResult public static func showInputDialog(titleParam: String? = nil, messageParam: String? = nil, okText: String = "OK", cancelText: String = "Cancel", okAction: @escaping () -> Void, dismisBlock: (() -> Void)? = nil) -> (UITextField, SCLAlertViewResponder) { + var title: String!, subTitle: String! + var alertView: SCLAlertView! + if messageParam == nil { + subTitle = "" + } else { + subTitle = messageParam! + } + + if titleParam == nil { + title = "" + let appearance = SCLAlertView.SCLAppearance( + kTitleHeight: 10, + shouldAutoDismiss: false + ) + alertView = SCLAlertView(appearance: appearance) + } else { + title = titleParam! + let appearance = SCLAlertView.SCLAppearance( + shouldAutoDismiss: false + ) + alertView = SCLAlertView(appearance: appearance) + } + let edt = alertView.addTextField() + alertView.addButton(okText, action: okAction) + + let alertResponse = alertView.showInfo(title, subTitle: subTitle, closeButtonTitle: cancelText) + if let dismisBlock = dismisBlock { + alertResponse.setDismissBlock(dismisBlock) + } + return (edt, alertResponse) + } + + public static func showPopupMenu(_ anchorView: UIView, menus: [String], selectionAction: @escaping SelectionClosure) { + let dropDown = DropDown() + dropDown.dataSource = menus + dropDown.selectionAction = selectionAction + dropDown.anchorView = anchorView + dropDown.bottomOffset = CGPoint(x: 0, y: anchorView.bounds.height) + dropDown.show() + } +} + +public enum TypeDialog { + case info + case error +} diff --git a/GeneralUtils/GeneralUtils/commonUtils/DownloadTask.swift b/GeneralUtils/GeneralUtils/commonUtils/DownloadTask.swift new file mode 100644 index 0000000..8fecbc2 --- /dev/null +++ b/GeneralUtils/GeneralUtils/commonUtils/DownloadTask.swift @@ -0,0 +1,91 @@ +import Foundation + +public class DownloadTask: NSObject, URLSessionDownloadDelegate { + public var delegate: DownloadTaskDelegate? + + private var activeDownloads = [String: URL]() + // [urlDownLoad, destinationURLSave] + private lazy var downloadsSession: Foundation.URLSession = { + let configuration = URLSessionConfiguration.default + let session = Foundation.URLSession(configuration: configuration, delegate: self, delegateQueue: nil) + return session + }() + + public init(delegate: DownloadTaskDelegate?) { + super.init() + self.delegate = delegate + } + + public func startDownload(urlDownload: String, destinationURL: URL) { + println("startDownload: \(urlDownload)") + if activeDownloads[urlDownload] != nil { return } + activeDownloads[urlDownload] = destinationURL + if let url = URL(string: urlDownload) { + let task = downloadsSession.downloadTask(with: url) + task.resume() + } + } + + func isDownloading() -> Bool { + return activeDownloads.count > 0 + } + + public func urlSession(_ session: URLSession, task: URLSessionTask, didCompleteWithError error: Error?) { + if let error = error, let originalURL = task.originalRequest?.url?.absoluteString { + println("didCompleteWithError: \(originalURL) - \(error.localizedDescription)") + downloadComplete(error: error, destinationURL: nil, originalURL: originalURL) + } + } + + public func urlSession(_ session: URLSession, downloadTask: URLSessionDownloadTask, didFinishDownloadingTo location: URL) { + guard let originalURL = downloadTask.originalRequest?.url?.absoluteString else { + println("Download fail: originalRequest.url nil") + downloadComplete(error: NSError.init(), destinationURL: nil, originalURL: nil) + return + } + + guard let destinationURL = activeDownloads[originalURL] else { + println("Download fail: destinationURL nil - \(originalURL)") + downloadComplete(error: NSError.init(), destinationURL: nil, originalURL: originalURL) + return + } + + let fileManager = FileManager.default + do { + try fileManager.removeItem(at: destinationURL) + } catch { + } + do { + let dirUrl = destinationURL.deletingLastPathComponent() + if !fileManager.fileExists(atPath: dirUrl.path) { + try fileManager.createDirectory(at: dirUrl, withIntermediateDirectories: true, attributes: nil) + } + try fileManager.moveItem(at: location, to: destinationURL) + println("downloadComplete: \(originalURL) -> \(destinationURL)") + downloadComplete(error: nil, destinationURL: destinationURL, originalURL: originalURL) + return + } catch let error as NSError { + println("Could not copy file to disk: \(error.localizedDescription)") + downloadComplete(error: error, destinationURL: destinationURL, originalURL: originalURL) + } + } + + public func urlSession(_ session: URLSession, downloadTask: URLSessionDownloadTask, didWriteData bytesWritten: Int64, totalBytesWritten: Int64, totalBytesExpectedToWrite: Int64) { + if let delegate = delegate { + delegate.downloadUpdateProgress?(percent: Int(Float(totalBytesWritten) / Float(totalBytesExpectedToWrite) * Float(100))) + } + } + + private func downloadComplete(error: Any?, destinationURL: URL?, originalURL: String?) { + if let originalURL = originalURL { + activeDownloads[originalURL] = nil + } + delegate?.downloadComplete(error: error, destinationURL: destinationURL, originalURL: originalURL) + } +} + +@objc public protocol DownloadTaskDelegate { + func downloadComplete(error: Any?, destinationURL: URL?, originalURL: String?) + + @objc optional func downloadUpdateProgress(percent: Int) +} diff --git a/GeneralUtils/GeneralUtils/commonUtils/FileUtils.swift b/GeneralUtils/GeneralUtils/commonUtils/FileUtils.swift new file mode 100644 index 0000000..914ee35 --- /dev/null +++ b/GeneralUtils/GeneralUtils/commonUtils/FileUtils.swift @@ -0,0 +1,233 @@ +import Foundation + +public class FileUtils { + + public static func getJsonFromResourceFile(name: String?, inDirectory subpath: String?, isNeedDecrypt: Bool = false) -> JSON? { + if let data = readDataFromResourceFile(name: name, inDirectory: subpath, isNeedDecrypt: isNeedDecrypt) { + return JSON.init(data: data) + } + return nil + } + + public static func getObjFromResourceFile(name: String?, inDirectory subpath: String?, isNeedDecrypt: Bool = false) -> T? { + if let data = readDataFromResourceFile(name: name, inDirectory: subpath, isNeedDecrypt: isNeedDecrypt) { + guard let jsonString = String.init(data: data, encoding: .utf8) else { + return nil + } + return Mapper().map(JSONString: jsonString) + } + return nil + } + + public static func getListObjFromResourceFile(name: String?, inDirectory subpath: String?, isNeedDecrypt: Bool = false) -> [T]? { + if let data = readDataFromResourceFile(name: name, inDirectory: subpath, isNeedDecrypt: isNeedDecrypt) { + guard let jsonString = String.init(data: data, encoding: .utf8) else { + return nil + } + return Mapper().mapArray(JSONString: jsonString) + } + return nil + } + + public static func readDataFromResourceFile(name: String?, inDirectory subpath: String?, isNeedDecrypt: Bool = false) -> Data? { + if let path = Bundle.main.path(forResource: name, ofType: nil, inDirectory: subpath), let originalData = try? Data(contentsOf: URL(fileURLWithPath: path)) { + if isNeedDecrypt { + return SecurityUtils.decryptData(data: originalData) + } else { + return originalData + } + } + return nil + } + + + public static func writeFile(data: String, fileSubPath: String, saveTo: SaveFileLocation) { + var dir: String! + if saveTo == .Document { + dir = getDocumentsDirectory() + } else { + dir = getLibraryDirectory() + } + let filePath = dir.appendingPathComponent(fileSubPath) + do { + try data.write(to: URL.init(fileURLWithPath: filePath), atomically: true, encoding: String.Encoding.utf8) + } catch let error { + println("writeFile ERROR: \(error.localizedDescription)") + } + } + + public static func writeFile(data: Data, fileSubPath: String, saveTo: SaveFileLocation) { + var dir: String! + if saveTo == .Document { + dir = getDocumentsDirectory() + } else { + dir = getLibraryDirectory() + } + let filePath = dir.appendingPathComponent(fileSubPath) + do { + try data.write(to: URL.init(fileURLWithPath: filePath)) + } catch let error { + println("writeFile ERROR: \(error.localizedDescription)") + } + } + + /** + fileSubPath: không chứa / ở đầu + */ + public static func readFile(fileSubPath: String, saveTo: SaveFileLocation) -> String? { + var dir: String! + if saveTo == .Document { + dir = getDocumentsDirectory() + } else { + dir = getLibraryDirectory() + } + let filePath = dir.appendingPathComponent(fileSubPath) + + do { + return try String.init(contentsOfFile: filePath) + } catch let error { + println("readFile ERROR: \(error.localizedDescription)") + return nil + } + } + + public static func readFile(fileSubPath: String, saveTo: SaveFileLocation, isDecrypt: Bool? = nil) -> Data? { + var dir: String! + if saveTo == .Document { + dir = getDocumentsDirectory() + } else { + dir = getLibraryDirectory() + } + let filePath = dir.appendingPathComponent(fileSubPath) + do { + let originalData = try Data(contentsOf: URL(fileURLWithPath: filePath)) + if isDecrypt == true { + return SecurityUtils.decryptData(data: originalData) + } else { + return originalData + } + } catch let error { + println("readFile ERROR: \(error.localizedDescription)") + return nil + } + } + + @discardableResult public static func deleteFile(fileSubPath: String, saveTo: SaveFileLocation) -> Bool { + var dir: String! + if saveTo == .Document { + dir = getDocumentsDirectory() + } else { + dir = getLibraryDirectory() + } + let filePath = dir.appendingPathComponent(fileSubPath) + + do { + try FileManager.default.removeItem(atPath: filePath) + return true + } catch let error { + println("readFile ERROR: \(error.localizedDescription)") + return false + } + } + + /** Return true -> Da co thu muc */ + public static func createDirIfNeed(dirSubPath: String, saveTo: SaveFileLocation) -> Bool { + var dir: String! + if saveTo == .Document { + dir = getDocumentsDirectory() + } else { + dir = getLibraryDirectory() + } + let dirPath = dir.appendingPathComponent(dirSubPath) + if !FileManager.default.fileExists(atPath: dirPath) { + do { + try FileManager.default.createDirectory(atPath: dirPath, withIntermediateDirectories: true, attributes: nil) + return true + } catch { + return false + } + } + return true + } + + public static func lastModify(fileSubPath: String, saveTo: SaveFileLocation) -> NSDate? { + var dir: String! + if saveTo == .Document { + dir = getDocumentsDirectory() + } else { + dir = getLibraryDirectory() + } + let filePath = dir.appendingPathComponent(fileSubPath) + guard let attributes = try? FileManager.default.attributesOfItem(atPath: filePath) else { return nil } + return attributes[FileAttributeKey.modificationDate] as? NSDate + } + + public static func moveFile(atPath: String, toPath: String) throws { + try FileManager.default.moveItem(atPath: atPath, toPath: toPath) + } + + public static func moveFile(at: URL, to: URL) throws { + try FileManager.default.moveItem(at: at, to: to) + } + + /** + fileSubPath: không chứa / ở đầu + */ + public static func getURL(fileSubPath: String, location: SaveFileLocation) -> URL { + var dir: String! + if location == .Document { + dir = getDocumentsDirectory() + } else { + dir = getLibraryDirectory() + } + let filePath = dir.appendingPathComponent(fileSubPath) + return URL.init(fileURLWithPath: filePath) + } + + /* + Lưu dữ liệu được tạo ra bởi người dùng + */ + public static func getDocumentsDirectory() -> String { + let paths = NSSearchPathForDirectoriesInDomains(.documentDirectory, .userDomainMask, true) + let documentsDirectory = paths[0] + return documentsDirectory + } + + public static func existDocumentsDirectory(fileName: String) -> Bool { + let fileManager = FileManager.default + let documentsPath = NSSearchPathForDirectoriesInDomains(.documentDirectory, .userDomainMask, true)[0] as NSString + return fileManager.fileExists(atPath: documentsPath.appendingPathComponent(fileName)) + } + + /* + Lưu dữ liệu của ứng dụng, dữ liệu được tải về sẽ lưu ở đây + */ + public static func getLibraryDirectory() -> String { + let paths = NSSearchPathForDirectoriesInDomains(.libraryDirectory, .userDomainMask, true) + let documentsDirectory = paths[0] + return documentsDirectory + } + + /** + fileSubPath: không chứa / ở đầu + */ + public static func getURLFromLibraryDirectory(fileSubPath: String?) -> URL { + let paths = NSSearchPathForDirectoriesInDomains(.libraryDirectory, .userDomainMask, true) + if let fileSubPath = fileSubPath { + return URL.init(fileURLWithPath: paths[0].appendingPathComponent(fileSubPath)) + } else { + return URL.init(fileURLWithPath: paths[0]) + } + } + + public static func existLibraryDirectory(fileName: String) -> Bool { + let fileManager = FileManager.default + let documentsPath = NSSearchPathForDirectoriesInDomains(.libraryDirectory, .userDomainMask, true)[0] as NSString + return fileManager.fileExists(atPath: documentsPath.appendingPathComponent(fileName)) + } +} + +public enum SaveFileLocation { + case Document + case Library +} diff --git a/GeneralUtils/GeneralUtils/commonUtils/NetWorkUtils.swift b/GeneralUtils/GeneralUtils/commonUtils/NetWorkUtils.swift new file mode 100644 index 0000000..f65a783 --- /dev/null +++ b/GeneralUtils/GeneralUtils/commonUtils/NetWorkUtils.swift @@ -0,0 +1,190 @@ +import Foundation +import SystemConfiguration +import SystemConfiguration.CaptiveNetwork + +public class NetWorkUtils { + + public static func isOnline() -> Bool { + var zeroAddress = sockaddr_in(sin_len: 0, sin_family: 0, sin_port: 0, sin_addr: in_addr(s_addr: 0), sin_zero: (0, 0, 0, 0, 0, 0, 0, 0)) + zeroAddress.sin_len = UInt8(MemoryLayout.size(ofValue: zeroAddress)) + zeroAddress.sin_family = sa_family_t(AF_INET) + + let defaultRouteReachability = withUnsafePointer(to: &zeroAddress) { + $0.withMemoryRebound(to: sockaddr.self, capacity: 1) { zeroSockAddress in + SCNetworkReachabilityCreateWithAddress(nil, zeroSockAddress) + } + } + + var flags: SCNetworkReachabilityFlags = SCNetworkReachabilityFlags(rawValue: 0) + if SCNetworkReachabilityGetFlags(defaultRouteReachability!, &flags) == false { + return false + } + let isReachable = flags == .reachable + return isReachable + } + + public static func isHasInternet() -> Bool { + var zeroAddress = sockaddr_in(sin_len: 0, sin_family: 0, sin_port: 0, sin_addr: in_addr(s_addr: 0), sin_zero: (0, 0, 0, 0, 0, 0, 0, 0)) + zeroAddress.sin_len = UInt8(MemoryLayout.size(ofValue: zeroAddress)) + zeroAddress.sin_family = sa_family_t(AF_INET) + + let defaultRouteReachability = withUnsafePointer(to: &zeroAddress) { + $0.withMemoryRebound(to: sockaddr.self, capacity: 1) { zeroSockAddress in + SCNetworkReachabilityCreateWithAddress(nil, zeroSockAddress) + } + } + + var flags: SCNetworkReachabilityFlags = SCNetworkReachabilityFlags(rawValue: 0) + if SCNetworkReachabilityGetFlags(defaultRouteReachability!, &flags) == false { + return false + } + + let isReachable = flags == .reachable + let needsConnection = flags == .connectionRequired + + return isReachable && !needsConnection + } + + /** + complete, completeArray: Chỉ truyền vào 1 cái tương ứng với kiểu data trả về + */ + public static func excuteHttpGet(urlStr: String, fileSubPathCache: String? = nil, saveTo: SaveFileLocation? = nil, + complete: ((_ result: T?, _ errorText: String?) -> ())? = nil, + completeArray: ((_ result: [T]?, _ errorText: String?) -> ())? = nil) { + + @discardableResult func completeResult(strResult: String?, strError: String?) -> Bool { + if let strResult = strResult { + if let complete = complete { + if let t = Mapper().map(JSONString: strResult) { + CommonUtils.excuteOnMainThread { complete(t, nil) } + return true + } + } + if let ts = Mapper().mapArray(JSONString: strResult) { + CommonUtils.excuteOnMainThread { completeArray?(ts, nil) } + return true + } + return false + } + + CommonUtils.excuteOnMainThread { + complete?(nil, strError) + completeArray?(nil, strError) + } + return false + } + + if let fileSubPathCache = fileSubPathCache, let saveTo = saveTo, let timeModify = FileUtils.lastModify(fileSubPath: fileSubPathCache, saveTo: saveTo) { + if timeModify.timeIntervalSinceNow > -36000, let catchString: String = FileUtils.readFile(fileSubPath: fileSubPathCache, saveTo: saveTo) { + if completeResult(strResult: catchString, strError: nil) { + println("Load from cached file: \(timeModify.timeIntervalSinceNow)") + return + } + } + } + + println("excuteHttpGet: \(urlStr)") + let url = URL(string: urlStr) + let task = URLSession.shared.dataTask(with: url!) { data, response, error in + guard error == nil else { + completeResult(strResult: nil, strError: error.debugDescription) + return + } + guard let data = data else { + completeResult(strResult: nil, strError: "Data is empty") + return + } + if let resultStr = String.init(data: data, encoding: String.Encoding.utf8) { + if completeResult(strResult: resultStr, strError: nil) { + if let fileSubPathCache = fileSubPathCache, let saveTo = saveTo { + FileUtils.writeFile(data: resultStr, fileSubPath: fileSubPathCache, saveTo: saveTo) + } + return + } + } + + CommonUtils.excuteOnMainThread { + complete?(nil, nil) + completeArray?(nil, nil) + } + } + + task.resume() + } + + public static func excuteHttpGet(urlStr: String, fileSubPathCache: String? = nil, saveTo: SaveFileLocation? = nil, + complete: @escaping ((_ result: String?, _ errorText: String?) -> Bool)) { + + if let fileSubPathCache = fileSubPathCache, let saveTo = saveTo, let timeModify = FileUtils.lastModify(fileSubPath: fileSubPathCache, saveTo: saveTo) { + if timeModify.timeIntervalSinceNow > -36000, let catchString: String = FileUtils.readFile(fileSubPath: fileSubPathCache, saveTo: saveTo) { + if complete(catchString, nil) { + println("Load from cached file: \(timeModify.timeIntervalSinceNow)") + return + } + } + } + + println("excuteHttpGet: \(urlStr)") + let url = URL(string: urlStr) + let task = URLSession.shared.dataTask(with: url!) { data, response, error in + guard error == nil else { + let _ = complete(nil, error.debugDescription) + return + } + guard let data = data else { + let _ = complete(nil, "Data is empty") + return + } + if let resultStr = String.init(data: data, encoding: String.Encoding.utf8) { + if complete(resultStr, nil) { + if let fileSubPathCache = fileSubPathCache, let saveTo = saveTo { + FileUtils.writeFile(data: resultStr, fileSubPath: fileSubPathCache, saveTo: saveTo) + } + return + } + } + } + + task.resume() + } + + public static func excuteHttpGetReturnData(urlStr: String, fileSubPathCache: String? = nil, saveTo: SaveFileLocation? = nil, isDecrypt: Bool? = nil, isCheckTimeoutCache: Bool = true, complete: @escaping ((_ data: Data?, _ errorText: String?) -> Bool)) { + CommonUtils.executebackgroundThread { + let urlStrFinal = urlStr.replacing(" ", with: "%20") + if let fileSubPathCache = fileSubPathCache, let saveTo = saveTo { + if let data: Data = FileUtils.readFile(fileSubPath: fileSubPathCache, saveTo: saveTo, isDecrypt: isDecrypt) { + let timeModify = FileUtils.lastModify(fileSubPath: fileSubPathCache, saveTo: saveTo) + + if !isCheckTimeoutCache || (timeModify != nil && timeModify!.timeIntervalSinceNow > -36000) { + if complete(data, nil) { + println("Load from cached file") + return + } + } + } + } + + println("excuteHttpGet: \(urlStrFinal)") + let url = URL(string: urlStrFinal) + let task = URLSession.shared.dataTask(with: url!) { data, response, error in + if let data = data { + var isSuccess: Bool? + if isDecrypt == true { + let decryptData: Data? = SecurityUtils.decryptData(data: data) + isSuccess = complete(decryptData, error?.localizedDescription) + } else { + isSuccess = complete(data, error?.localizedDescription) + } + + if let fileSubPathCache = fileSubPathCache, let saveTo = saveTo, isSuccess == true { + FileUtils.writeFile(data: data, fileSubPath: fileSubPathCache, saveTo: saveTo) + } + } else { + let _ = complete(nil, error?.localizedDescription) + } + } + + task.resume() + } + } +} diff --git a/GeneralUtils/GeneralUtils/commonUtils/PreferenceUtils.swift b/GeneralUtils/GeneralUtils/commonUtils/PreferenceUtils.swift new file mode 100644 index 0000000..29e4acc --- /dev/null +++ b/GeneralUtils/GeneralUtils/commonUtils/PreferenceUtils.swift @@ -0,0 +1,46 @@ +import Foundation + + +public struct PreferenceKeys { + public static let TIME_OPEN_FULL_ADS = "TIME_OPEN_FULL_ADS" +} + +public class PreferenceUtils{ + public static func saveInt(key: String, value: Int?) { + let defaults = UserDefaults.standard + return defaults.set(value, forKey: key) + } + public static func getInt(key: String, canCheckAndReturnNil:Bool = true) -> Int? { + let defaults = UserDefaults.standard + if canCheckAndReturnNil && defaults.object(forKey: key) == nil {return nil} + return defaults.integer(forKey: key) + } + + + public static func saveBool(key: String, value: Bool?, isInstant: Bool = false) { + let defaults = UserDefaults.standard + defaults.set(value, forKey: key) + if isInstant { + defaults.synchronize() + } + } + + public static func getBool(key: String) -> Bool { + let defaults = UserDefaults.standard + return defaults.bool(forKey: key) + } + + public static func saveString(key: String, value: String?, isInstant: Bool = false) { + let defaults = UserDefaults.standard + defaults.setValue(value, forKey: key) + if isInstant { + defaults.synchronize() + } + } + + public static func getString(key: String) -> String? { + let defaults = UserDefaults.standard + return defaults.string(forKey: key) + } +} + diff --git a/GeneralUtils/GeneralUtils/commonUtils/Queue.swift b/GeneralUtils/GeneralUtils/commonUtils/Queue.swift new file mode 100644 index 0000000..dcc99cf --- /dev/null +++ b/GeneralUtils/GeneralUtils/commonUtils/Queue.swift @@ -0,0 +1,47 @@ + +// should be an inner class of Queue, but inner classes and generics crash the compiler, SourceKit (repeatedly) and occasionally XCode. +public class _QueueItem { + let value: T! + var next: _QueueItem? + + public init(_ newvalue: T?) { + self.value = newvalue + } +} + +/// +/// A standard queue (FIFO - First In First Out). Supports simultaneous adding and removing, but only one item can be added at a time, and only one item can be removed at a time. +/// + open class Queue { + + public typealias Element = T + + public var _front: _QueueItem + public var _back: _QueueItem + + public init () { + // Insert dummy item. Will disappear when the first item is added. + _back = _QueueItem(nil) + _front = _back + } + + /// Add a new item to the back of the queue. + public func enqueue (_ value: Element) { + _back.next = _QueueItem(value) + _back = _back.next! + } + + /// Return and remove the item at the front of the queue. + public func dequeue () -> Element? { + if let newhead = _front.next { + _front = newhead + return newhead.value + } else { + return nil + } + } + + open func isEmpty() -> Bool { + return _front === _back + } +} diff --git a/GeneralUtils/GeneralUtils/commonUtils/RecordUtils.swift b/GeneralUtils/GeneralUtils/commonUtils/RecordUtils.swift new file mode 100644 index 0000000..7d03c02 --- /dev/null +++ b/GeneralUtils/GeneralUtils/commonUtils/RecordUtils.swift @@ -0,0 +1,81 @@ +import UIKit +import Foundation +import AVFoundation + +public class RecordUtils: NSObject, AVAudioRecorderDelegate { + static var recordingSession: AVAudioSession? + var audioRecorder: AVAudioRecorder? + var funcStartRecordCallback: (() -> ())? + var funcStopRecordCallback: (() -> ())? + + public func requestRecordPermision(_ funcSuccessCallback: @escaping () -> (), funcFailCallback: @escaping () -> ()) { + RecordUtils.recordingSession = AVAudioSession.sharedInstance() + + do { + try RecordUtils.recordingSession?.setCategory(AVAudioSessionCategoryPlayAndRecord, with: .defaultToSpeaker) + try RecordUtils.recordingSession?.setActive(true) + RecordUtils.recordingSession?.requestRecordPermission({ (allowed) in + DispatchQueue.main.async { + if allowed { + funcSuccessCallback() + } else { + funcFailCallback() + } + } + }) + } catch { + funcFailCallback() + } + } + + /** + let audioSaveURL = URL(fileURLWithPath: FileUtils.getDocumentsDirectory().appendingPathComponent("tmp.m4a")) + */ + public func startRecording(audioSaveURL: URL, funcStartRecordCallback: @escaping () -> (), funcStopRecordCallback: @escaping () -> ()) { + self.funcStartRecordCallback = funcStartRecordCallback + self.funcStopRecordCallback = funcStopRecordCallback + requestRecordPermision({ + self.startRecordingAfterRequestPermision(audioSaveURL) + }, + funcFailCallback: { + CommonUtils.showToastLong(text: "Không thể ghi âm") + }) + } + + public func isRecording() -> Bool { + return audioRecorder != nil + } + + fileprivate func startRecordingAfterRequestPermision(_ audioSaveURL: URL) { + if audioRecorder != nil { + return + } + let settings = [ + AVFormatIDKey: Int(kAudioFormatMPEG4AAC), + AVSampleRateKey: 12000.0, + AVNumberOfChannelsKey: 1 as NSNumber, + AVEncoderAudioQualityKey: AVAudioQuality.high.rawValue + ] as [String : Any] + + do { + audioRecorder = try AVAudioRecorder(url: audioSaveURL, settings: settings) + audioRecorder?.delegate = self + audioRecorder?.record() + funcStartRecordCallback?() + } catch { + finishRecording() + } + } + + public func finishRecording() { + audioRecorder?.stop() + audioRecorder = nil + funcStopRecordCallback?() + } + + public func audioRecorderDidFinishRecording(_ recorder: AVAudioRecorder, successfully flag: Bool) { + if !flag { + finishRecording() + } + } +} diff --git a/GeneralUtils/GeneralUtils/commonUtils/SecurityUtils.swift b/GeneralUtils/GeneralUtils/commonUtils/SecurityUtils.swift new file mode 100644 index 0000000..fb81bc0 --- /dev/null +++ b/GeneralUtils/GeneralUtils/commonUtils/SecurityUtils.swift @@ -0,0 +1,41 @@ +// +// SecurityUtils.swift +// LuyenThiTOEIC +// +// Created by Philip Tran on 1/14/17. +// Copyright © 2017 Learn English A To Z. All rights reserved. +// + +import Foundation + +public class SecurityUtils { + + private static func getAESInstance() throws -> AES { + let keyCharArray: [Character] = ["Q", "h", "f", "r", "l", "f", "l", "l", "L", "l", "L", "l", "t", "K", "e", "y"] + let key = String(keyCharArray).utf8.map { UInt8($0) } + let aes = try AES(key: key, iv: nil, blockMode: BlockMode.ECB, padding: PKCS7()) + return aes + } + + public static func decryptData(data: Data) -> String? { + do { + let aes = try getAESInstance() + let decriptData = try aes.decrypt(data) + let resultStr = String.init(data: Data.init(bytes: decriptData), encoding: String.Encoding.utf8) + return resultStr + } catch let error { + print(error.localizedDescription) + return nil + } + } + + public static func decryptData(data: Data) -> Data? { + do { + let aes = try getAESInstance() + return try Data.init(bytes: aes.decrypt(data)) + } catch let error { + print(error.localizedDescription) + return nil + } + } +} diff --git a/GeneralUtils/GeneralUtils/commonUtils/StringExtension.swift b/GeneralUtils/GeneralUtils/commonUtils/StringExtension.swift new file mode 100644 index 0000000..9098511 --- /dev/null +++ b/GeneralUtils/GeneralUtils/commonUtils/StringExtension.swift @@ -0,0 +1,673 @@ +// +// StringExtensions.swift +// SwifterSwift +// +// Created by Omar Albeik on 8/5/16. +// Copyright © 2016 Omar Albeik. All rights reserved. +// + +import Foundation +import UIKit + + +public class StringUtils { + public static func isEmpty(_ str: String?) -> Bool { + if let source = str, source.length > 0 { + return false + } + return true + } + + public static func getStandStr(_ str: String) -> String { + let khongDau = str.folding(options: .diacriticInsensitive, locale: .current) + return khongDau.lowercased().trimmed.replacing(",", with: "").replacing(".", with: "").replacing("?", with: "").replacing("-", with: "").replacing("_", with: "").replacing("/", with: "") + } + + /** + Return chuỗi string là các dấu gạch chân bên dưới: _ _ _ _ _ + */ + public static func getEmptyString(_ length: Int) -> String { + if length == 0 { + return "" + } + var str: String = "" + for _ in 0 ..< length { + str.append("_ ") + } + return str + } + + public static func heightWithConstrainedWidth(_ str: String?, width: CGFloat, font: UIFont) -> CGFloat { + if let str = str { + let constraintRect = CGSize(width: width, height: .greatestFiniteMagnitude) + let boundingBox = str.boundingRect(with: constraintRect, options: .usesLineFragmentOrigin, attributes: [NSFontAttributeName: font], context: nil) + + return boundingBox.height + } + return 0 + } + +} + +// MARK: - Properties + +public extension Character { + public var asciiValue: UInt32? { + return String(self).unicodeScalars.filter{$0.isASCII}.first?.value + } +} + +public extension String { + public var length: Int { return characters.count } + + init(utf32chars:[UInt32]) { + let data = Data.init(bytes: utf32chars, count: utf32chars.count * MemoryLayout.size) + self = NSString(data: data, encoding: String.Encoding.utf32LittleEndian.rawValue) as! String + } + + public var asciiArray: [UInt32] { + return unicodeScalars.filter { $0.isASCII }.map { $0.value } + } + + public func index(from: Int) -> Index { + return self.index(startIndex, offsetBy: from) + } + + public func substring(from: Int) -> String { + let fromIndex = index(from: from) + return substring(from: fromIndex) + } + + public func substring(to: Int) -> String { + let toIndex = index(from: to) + return substring(to: toIndex) + } + + public func substring(with r: Range) -> String { + let startIndex = index(from: r.lowerBound) + let endIndex = index(from: r.upperBound) + return substring(with: startIndex ..< endIndex) + } + + /// SwifterSwift: String decoded from base64 (if applicable). + public var base64Decoded: String? { + // https://github.com/Reza-Rg/Base64-Swift-Extension/blob/master/Base64.swift + guard let decodedData = Data(base64Encoded: self) else { + return nil + } + return String(data: decodedData, encoding: .utf8) + } + + /// SwifterSwift: String encoded in base64 (if applicable). + public var base64Encoded: String? { + // https://github.com/Reza-Rg/Base64-Swift-Extension/blob/master/Base64.swift + let plainData = self.data(using: .utf8) + return plainData?.base64EncodedString() + } + + /// SwifterSwift: CamelCase of string. + public var camelCased: String { + let source = lowercased() + if source.characters.contains(" ") { + let first = source.substring(to: source.index(after: source.startIndex)) + let camel = source.capitalized.replacing(" ", with: "").replacing("\n", with: "") + let rest = String(camel.characters.dropFirst()) + return "\(first)\(rest)" + } else { + let first = source.lowercased().substring(to: source.index(after: source.startIndex)) + let rest = String(source.characters.dropFirst()) + return "\(first)\(rest)" + + } + } + + /// SwifterSwift: Check if string contains one or more emojis. + public var containEmoji: Bool { + // http://stackoverflow.com/questions/30757193/find-out-if-character-in-string-is-emoji + for scalar in unicodeScalars { + switch scalar.value { + case 0x3030, 0x00AE, 0x00A9, // Special Characters + 0x1D000 ... 0x1F77F, // Emoticons + 0x2100 ... 0x27BF, // Misc symbols and Dingbats + 0xFE00 ... 0xFE0F, // Variation Selectors + 0x1F900 ... 0x1F9FF: // Supplemental Symbols and Pictographs + return true + default: + continue + } + } + return false + } + + /// SwifterSwift: First character of string (if applicable). + public var firstCharacter: String? { + return Array(characters).map({ String($0) }).first + } + + /// SwifterSwift: Check if string contains one or more letters. + public var hasLetters: Bool { + return rangeOfCharacter(from: .letters, options: .numeric, range: nil) != nil + } + + /// SwifterSwift: Check if string contains one or more numbers. + public var hasNumbers: Bool { + return rangeOfCharacter(from: .decimalDigits, options: .literal, range: nil) != nil + } + + /// SwifterSwift: Check if string contains only letters. + public var isAlphabetic: Bool { + return hasLetters && !hasNumbers + } + + /// SwifterSwift: Check if string contains at least one letter and one number. + public var isAlphaNumeric: Bool { + return components(separatedBy: CharacterSet.alphanumerics).joined(separator: "").characters.count == 0 && hasLetters && hasNumbers + } + + /// SwifterSwift: Check if string is valid email format. + public var isEmail: Bool { + // http://stackoverflow.com/questions/25471114/how-to-validate-an-e-mail-address-in-swift + let emailRegEx = "[A-Z0-9a-z._%+-]+@[A-Za-z0-9.-]+\\.[A-Za-z]{2,}" + let emailTest = NSPredicate(format: "SELF MATCHES %@", emailRegEx) + return emailTest.evaluate(with: self) + } + + /// SwifterSwift: Check if string is https URL. + public var isHttpsUrl: Bool { + guard start(with: "https://".lowercased()) else { + return false + } + return URL(string: self) != nil + } + + /// SwifterSwift: Check if string is http URL. + public var isHttpUrl: Bool { + guard start(with: "http://".lowercased()) else { + return false + } + return URL(string: self) != nil + } + + /// SwifterSwift: Check if string contains only numbers. + public var isNumeric: Bool { + return !hasLetters && hasNumbers + } + + /// SwifterSwift: Last character of string (if applicable). + public var lastCharacter: String? { + guard let last = characters.last else { + return nil + } + return String(last) + } + + /// SwifterSwift: Latinized string. + public var latinized: String { + return folding(options: .diacriticInsensitive, locale: Locale.current) + } + + /// SwifterSwift: Array of strings separated by new lines. + public var lines: [String] { + var result: [String] = [] + enumerateLines { (line, stop) -> () in + result.append(line) + } + return result + } + + /// SwifterSwift: The most common character in string. + public var mostCommonCharacter: String { + var mostCommon = "" + let charSet = Set(withoutSpacesAndNewLines.characters.map { String($0) }) + var count = 0 + for string in charSet { + if self.count(of: string) > count { + count = self.count(of: string) + mostCommon = string + } + } + return mostCommon + } + + /// SwifterSwift: Reversed string. + public var reversed: String { + return String(characters.reversed()) + } + + /// SwifterSwift: Bool value from string (if applicable). + public var bool: Bool? { + let selfLowercased = self.trimmed.lowercased() + if selfLowercased == "true" || selfLowercased == "1" { + return true + } else if selfLowercased == "false" || selfLowercased == "0" { + return false + } else { + return nil + } + } + + /// SwifterSwift: Date object from "yyyy-MM-dd" formatted string + public var date: Date? { + let selfLowercased = self.trimmed.lowercased() + let formatter = DateFormatter() + formatter.timeZone = TimeZone.current + formatter.dateFormat = "yyyy-MM-dd" + return formatter.date(from: selfLowercased) + } + + /// SwifterSwift: Date object from "yyyy-MM-dd HH:mm:ss" formatted string. + public var dateTime: Date? { + let selfLowercased = self.trimmed.lowercased() + let formatter = DateFormatter() + formatter.timeZone = TimeZone.current + formatter.dateFormat = "yyyy-MM-dd HH:mm:ss" + return formatter.date(from: selfLowercased) + } + + /// SwifterSwift: Double value from string (if applicable). + public var double: Double? { + let formatter = NumberFormatter() + return formatter.number(from: self) as? Double + } + + /// SwifterSwift: Float value from string (if applicable). + public var float: Float? { + let formatter = NumberFormatter() + return formatter.number(from: self) as? Float + } + + /// SwifterSwift: Float32 value from string (if applicable). + public var float32: Float32? { + let formatter = NumberFormatter() + return formatter.number(from: self) as? Float32 + } + + /// SwifterSwift: Float64 value from string (if applicable). + public var float64: Float64? { + let formatter = NumberFormatter() + return formatter.number(from: self) as? Float64 + } + + /// SwifterSwift: Integer value from string (if applicable). + public var int: Int? { + return Int(self) + } + + /// SwifterSwift: Int16 value from string (if applicable). + public var int16: Int16? { + return Int16(self) + } + + /// SwifterSwift: Int32 value from string (if applicable). + public var int32: Int32? { + return Int32(self) + } + + /// SwifterSwift: Int64 value from string (if applicable). + public var int64: Int64? { + return Int64(self) + } + + /// SwifterSwift: Int8 value from string (if applicable). + public var int8: Int8? { + return Int8(self) + } + + /// SwifterSwift: URL from string (if applicable). + public var url: URL? { + return URL(string: self) + } + + /// SwifterSwift: String with no spaces or new lines in beginning and end. + public var trimmed: String { + return trimmingCharacters(in: CharacterSet.whitespacesAndNewlines) + } + + /// SwifterSwift: Array with unicodes for all characters in a string. + public var unicodeArray: [Int] { + return unicodeScalars.map({ $0.hashValue }) + } + + /// SwifterSwift: Readable string from a URL string. + public var urlDecoded: String { + return removingPercentEncoding ?? self + } + + /// SwifterSwift: URL escaped string. + public var urlEncoded: String { + return addingPercentEncoding(withAllowedCharacters: .urlHostAllowed) ?? self + } + + /// SwifterSwift: String without spaces and new lines. + public var withoutSpacesAndNewLines: String { + return replacing(" ", with: "").replacing("\n", with: "") + } + +} + + +// MARK: - Methods + +public extension String { + + /// SwifterSwift: Copy string to global pasteboard. + public func copyToPasteboard() { + UIPasteboard.general.string = self + } + + /// SwifterSwift: Converts string format to CamelCase. + public mutating func camelize() { + self = camelCased + } + + /// SwifterSwift: Check if string contains one or more instance of substring. + /// + /// - Parameters: + /// - string: substring to search for. + /// - caseSensitive: set true for case sensitive search (default is true). + /// - Returns: true if string contains one or more instance of substring. + public func contain(_ string: String, caseSensitive: Bool = true) -> Bool { + if !caseSensitive { + return range(of: string, options: .caseInsensitive) != nil + } + return range(of: string) != nil + } + + /// SwifterSwift: Count of substring in string. + /// + /// - Parameters: + /// - string: substring to search for. + /// - caseSensitive: set true for case sensitive search (default is true). + /// - Returns: count of substring in string. + public func count(of string: String, caseSensitive: Bool = true) -> Int { + if !caseSensitive { + return lowercased().components(separatedBy: string).count - 1 + } + return components(separatedBy: string).count - 1 + } + + /// SwifterSwift: Check if string ends with substring. + /// + /// - Parameters: + /// - suffix: substring to search if string ends with. + /// - caseSensitive: set true for case sensitive search (default is true). + /// - Returns: true if string ends with substring. + public func end(with suffix: String, caseSensitive: Bool = true) -> Bool { + if !caseSensitive { + return lowercased().hasSuffix(suffix.lowercased()) + } + return hasSuffix(suffix) + } + + /// SwifterSwift: First index of substring in string. + /// + /// - Parameter string: substring to search for. + /// - Returns: first index of substring in string (if applicable). + public func firstIndex(of string: String) -> Int? { + return Array(self.characters).map({ String($0) }).index(of: string) + } + + /// SwifterSwift: Latinize string. + public mutating func latinize() { + self = latinized + } + + /// SwifterSwift: Random string of given length. + /// + /// - Parameter ofLength: number of characters in string. + /// - Returns: random string of given length. + public static func random(ofLength: Int) -> String { + var string = "" + guard ofLength > 0 else { + return string + } + let base = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789" + for _ in 0 ..< ofLength { + let randomIndex = arc4random_uniform(UInt32(base.characters.count)) + string += "\(base[base.index(base.startIndex, offsetBy: IndexDistance(randomIndex))])" + } + return string + } + + /// SwifterSwift: String by replacing part of string with another string. + /// + /// - Parameters: + /// - substring: old substring to find and replace + /// - newString: new string to insert in old string place + /// - Returns: string after replacing substring with newString + public func replacing(_ substring: String, with newString: String) -> String { + return replacingOccurrences(of: substring, with: newString) + } + + public func replaceFirst(of pattern: String, + with replacement: String) -> String { + if let range = self.range(of: pattern) { + return self.replacingCharacters(in: range, with: replacement) + } else { + return self + } + } + + /// SwifterSwift: Reverse string. + public mutating func reverse() { + self = String(characters.reversed()) + } + + /// SwifterSwift: Array of strings separated by given string. + /// + /// - Parameter separator: separator to split string by. + /// - Returns: array of strings separated by given string. + public func splited(by separator: Character) -> [String] { + return characters.split { $0 == separator }.map(String.init) + } + + public func splited(by str: String) -> [String] { + return self.components(separatedBy: str) + } + + /// SwifterSwift: Check if string starts with substring. + /// + /// - Parameters: + /// - suffix: substring to search if string starts with. + /// - caseSensitive: set true for case sensitive search (default is true). + /// - Returns: true if string starts with substring. + public func start(with prefix: String, caseSensitive: Bool = true) -> Bool { + if !caseSensitive { + return lowercased().hasPrefix(prefix.lowercased()) + } + return hasPrefix(prefix) + } + + /// SwifterSwift: Date object from string of date format. + /// + /// - Parameter format: date format + /// - Returns: Date object from string (if applicable). + public func date(withFormat format: String) -> Date? { + let dateFormatter = DateFormatter() + dateFormatter.dateFormat = format + return dateFormatter.date(from: self) + } + + /// SwifterSwift: Removes spaces and new lines in beginning and end of string. + public mutating func trim() { + self = trimmingCharacters(in: CharacterSet.whitespacesAndNewlines) + } + + public func trimAndReturn() -> String { + return trimmingCharacters(in: CharacterSet.whitespacesAndNewlines) + } + + /// SwifterSwift: Truncate string (cut it to a given number of characters). + /// + /// - Parameters: + /// - toLength: maximum number of charachters before cutting. + /// - trailing: string to add at the end of truncated string. + public mutating func truncate(toLength: Int, trailing: String? = "...") { + guard toLength > 0 else { + return + } + if self.characters.count > toLength { + self = self.substring(to: self.index(startIndex, offsetBy: toLength)) + (trailing ?? "") + } + } + + /// SwifterSwift: Truncated string (limited to a given number of characters). + /// Truncated string (cut to a given number of characters). + /// + /// - Parameters: + /// - toLength: maximum number of charachters before cutting. + /// - trailing: string to add at the end of truncated string. + /// - Returns: truncated string (this is an exa...). + public func truncated(toLength: Int, trailing: String? = "...") -> String { + guard self.characters.count > toLength, toLength > 0 else { + return self + } + return self.substring(to: self.index(startIndex, offsetBy: toLength)) + (trailing ?? "") + } + + /// SwifterSwift: Convert URL string to readable string. + public mutating func urlDecode() { + self = removingPercentEncoding ?? self + } + + /// SwifterSwift: Escape string. + public mutating func urlEncode() { + self = addingPercentEncoding(withAllowedCharacters: .urlHostAllowed) ?? self + } + +} + + +// MARK: - Operators + +public extension String { + + /// SwifterSwift: Repeat string multiple times. + /// + /// - Parameters: + /// - lhs: string to repeat. + /// - rhs: number of times to repeat character. + /// - Returns: string with character repeated n times. + static public func *(lhs: String, rhs: Int) -> String { + var newString = "" + for _ in 0 ..< rhs { + newString += lhs + } + return newString + } + + /// SwifterSwift: Repeat string multiple times. + /// + /// - Parameters: + /// - lhs: number of times to repeat character. + /// - rhs: string to repeat. + /// - Returns: string with character repeated n times. + static public func *(lhs: Int, rhs: String) -> String { + var newString = "" + for _ in 0 ..< lhs { + newString += rhs + } + return newString + } + +} + + +// MARK: - Initializers + +public extension String { + + /// SwifterSwift: Create a new string from a base64 string (if applicable). + /// + /// - Parameter base64: base64 string. + public init?(base64: String) { + if let str = base64.base64Decoded { + self.init(str) + return + } + return nil + } + +} + + +// MARK: - NSAttributedString extensions + +public extension String { + + /// SwifterSwift: Bold string. + public var bold: NSAttributedString { + return NSMutableAttributedString(string: self, attributes: [NSFontAttributeName: UIFont.boldSystemFont(ofSize: UIFont.systemFontSize)]) + } + + /// SwifterSwift: Underlined string + public var underline: NSAttributedString { + return NSAttributedString(string: self, attributes: [NSUnderlineStyleAttributeName: NSUnderlineStyle.styleSingle.rawValue]) + } + + /// SwifterSwift: Strikethrough string. + public var strikethrough: NSAttributedString { + return NSAttributedString(string: self, attributes: [NSStrikethroughStyleAttributeName: NSNumber(value: NSUnderlineStyle.styleSingle.rawValue as Int)]) + } + + /// SwifterSwift: Italic string. + public var italic: NSAttributedString { + return NSMutableAttributedString(string: self, attributes: [NSFontAttributeName: UIFont.italicSystemFont(ofSize: UIFont.systemFontSize)]) + } + + /// SwifterSwift: Add color to string. + /// + /// - Parameter color: text color. + /// - Returns: a NSAttributedString versions of string colored with given color. + public func colored(with color: UIColor) -> NSAttributedString { + return NSMutableAttributedString(string: self, attributes: [NSForegroundColorAttributeName: color]) + } + +} + + +//MARK: - NSString extensions + +public extension String { + + /// SwifterSwift: NSString from a string + public var nsString: NSString { + return NSString(string: self) + } + + /// SwifterSwift: NSString lastPathComponent + public var lastPathComponent: String { + return (self as NSString).lastPathComponent + } + + /// SwifterSwift: NSString pathExtension + public var pathExtension: String { + return (self as NSString).pathExtension + } + + /// SwifterSwift: NSString deletingLastPathComponent + public var deletingLastPathComponent: String { + return (self as NSString).deletingLastPathComponent + } + + /// SwifterSwift: NSString deletingPathExtension + public var deletingPathExtension: String { + return (self as NSString).deletingPathExtension + } + + /// SwifterSwift: NSString pathComponents + public var pathComponents: [String] { + return (self as NSString).pathComponents + } + + /// SwifterSwift: NSString appendingPathComponent(str: String) + public func appendingPathComponent(_ str: String) -> String { + return (self as NSString).appendingPathComponent(str) + } + + /// SwifterSwift: NSString appendingPathExtension(str: String) (if applicable). + public func appendingPathExtension(_ str: String) -> String? { + return (self as NSString).appendingPathExtension(str) + } + +} diff --git a/GeneralUtils/GeneralUtils/libs/CryptoSwift/AES.swift b/GeneralUtils/GeneralUtils/libs/CryptoSwift/AES.swift new file mode 100644 index 0000000..3574cad --- /dev/null +++ b/GeneralUtils/GeneralUtils/libs/CryptoSwift/AES.swift @@ -0,0 +1,586 @@ +// +// AES.swift +// CryptoSwift +// +// Created by Marcin Krzyzanowski on 21/11/14. +// Copyright (c) 2014 Marcin Krzyzanowski. All rights reserved. +// +// Implementation of Gladman algorithm http://www.gladman.me.uk/AES +// + +private typealias Key = SecureBytes + +/// The Advanced Encryption Standard (AES) +public final class AES: BlockCipher { + + public enum Error: Swift.Error { + /// Data padding is required + case dataPaddingRequired + /// Invalid key or IV + case invalidKeyOrInitializationVector + /// Invalid IV + case invalidInitializationVector + } + + public enum Variant: Int { + case aes128 = 1, aes192, aes256 + + var Nk: Int { // Nk words + return [4, 6, 8][self.rawValue - 1] + } + + var Nb: Int { // Nb words + return 4 + } + + var Nr: Int { // Nr + return Nk + 6 + } + } + + fileprivate let blockMode: BlockMode + public static let blockSize: Int = 16 // 128 /8 + + public var variant: Variant { + switch (self.key.count * 8) { + case 128: + return .aes128 + case 192: + return .aes192 + case 256: + return .aes256 + default: + preconditionFailure("Unknown AES variant for given key.") + } + } + private let key: Key + fileprivate let iv: Array + fileprivate let padding: Padding + fileprivate lazy var expandedKey: Array> = self.expandKey(self.key, variant: self.variant) + fileprivate lazy var expandedKeyInv: Array> = self.expandKeyInv(self.key, variant: self.variant) + + fileprivate lazy var sBoxes: (sBox: Array, invSBox: Array) = self.calculateSBox() + fileprivate lazy var sBox: Array = self.sBoxes.sBox + fileprivate lazy var sBoxInv: Array = self.sBoxes.invSBox + + // Parameters for Linear Congruence Generators + fileprivate let Rcon: Array = [ + 0x8d, 0x01, 0x02, 0x04, 0x08, 0x10, 0x20, 0x40, 0x80, 0x1b, 0x36, 0x6c, 0xd8, 0xab, 0x4d, 0x9a, + 0x2f, 0x5e, 0xbc, 0x63, 0xc6, 0x97, 0x35, 0x6a, 0xd4, 0xb3, 0x7d, 0xfa, 0xef, 0xc5, 0x91, 0x39, + 0x72, 0xe4, 0xd3, 0xbd, 0x61, 0xc2, 0x9f, 0x25, 0x4a, 0x94, 0x33, 0x66, 0xcc, 0x83, 0x1d, 0x3a, + 0x74, 0xe8, 0xcb, 0x8d, 0x01, 0x02, 0x04, 0x08, 0x10, 0x20, 0x40, 0x80, 0x1b, 0x36, 0x6c, 0xd8, + 0xab, 0x4d, 0x9a, 0x2f, 0x5e, 0xbc, 0x63, 0xc6, 0x97, 0x35, 0x6a, 0xd4, 0xb3, 0x7d, 0xfa, 0xef, + 0xc5, 0x91, 0x39, 0x72, 0xe4, 0xd3, 0xbd, 0x61, 0xc2, 0x9f, 0x25, 0x4a, 0x94, 0x33, 0x66, 0xcc, + 0x83, 0x1d, 0x3a, 0x74, 0xe8, 0xcb, 0x8d, 0x01, 0x02, 0x04, 0x08, 0x10, 0x20, 0x40, 0x80, 0x1b, + 0x36, 0x6c, 0xd8, 0xab, 0x4d, 0x9a, 0x2f, 0x5e, 0xbc, 0x63, 0xc6, 0x97, 0x35, 0x6a, 0xd4, 0xb3, + 0x7d, 0xfa, 0xef, 0xc5, 0x91, 0x39, 0x72, 0xe4, 0xd3, 0xbd, 0x61, 0xc2, 0x9f, 0x25, 0x4a, 0x94, + 0x33, 0x66, 0xcc, 0x83, 0x1d, 0x3a, 0x74, 0xe8, 0xcb, 0x8d, 0x01, 0x02, 0x04, 0x08, 0x10, 0x20, + 0x40, 0x80, 0x1b, 0x36, 0x6c, 0xd8, 0xab, 0x4d, 0x9a, 0x2f, 0x5e, 0xbc, 0x63, 0xc6, 0x97, 0x35, + 0x6a, 0xd4, 0xb3, 0x7d, 0xfa, 0xef, 0xc5, 0x91, 0x39, 0x72, 0xe4, 0xd3, 0xbd, 0x61, 0xc2, 0x9f, + 0x25, 0x4a, 0x94, 0x33, 0x66, 0xcc, 0x83, 0x1d, 0x3a, 0x74, 0xe8, 0xcb, 0x8d, 0x01, 0x02, 0x04, + 0x08, 0x10, 0x20, 0x40, 0x80, 0x1b, 0x36, 0x6c, 0xd8, 0xab, 0x4d, 0x9a, 0x2f, 0x5e, 0xbc, 0x63, + 0xc6, 0x97, 0x35, 0x6a, 0xd4, 0xb3, 0x7d, 0xfa, 0xef, 0xc5, 0x91, 0x39, 0x72, 0xe4, 0xd3, 0xbd, + 0x61, 0xc2, 0x9f, 0x25, 0x4a, 0x94, 0x33, 0x66, 0xcc, 0x83, 0x1d, 0x3a, 0x74, 0xe8, 0xcb, 0x8d] + + fileprivate let T0: Array = [0xa56363c6, 0x847c7cf8, 0x997777ee, 0x8d7b7bf6, 0xdf2f2ff, 0xbd6b6bd6, 0xb16f6fde, 0x54c5c591, 0x50303060, 0x3010102, 0xa96767ce, 0x7d2b2b56, 0x19fefee7, 0x62d7d7b5, 0xe6abab4d, 0x9a7676ec, 0x45caca8f, 0x9d82821f, 0x40c9c989, 0x877d7dfa, 0x15fafaef, 0xeb5959b2, 0xc947478e, 0xbf0f0fb, 0xecadad41, 0x67d4d4b3, 0xfda2a25f, 0xeaafaf45, 0xbf9c9c23, 0xf7a4a453, 0x967272e4, 0x5bc0c09b, 0xc2b7b775, 0x1cfdfde1, 0xae93933d, 0x6a26264c, 0x5a36366c, 0x413f3f7e, 0x2f7f7f5, 0x4fcccc83, 0x5c343468, 0xf4a5a551, 0x34e5e5d1, 0x8f1f1f9, 0x937171e2, 0x73d8d8ab, 0x53313162, 0x3f15152a, 0xc040408, 0x52c7c795, 0x65232346, 0x5ec3c39d, 0x28181830, 0xa1969637, 0xf05050a, 0xb59a9a2f, 0x907070e, 0x36121224, 0x9b80801b, 0x3de2e2df, 0x26ebebcd, 0x6927274e, 0xcdb2b27f, 0x9f7575ea, 0x1b090912, 0x9e83831d, 0x742c2c58, 0x2e1a1a34, 0x2d1b1b36, 0xb26e6edc, 0xee5a5ab4, 0xfba0a05b, 0xf65252a4, 0x4d3b3b76, 0x61d6d6b7, 0xceb3b37d, 0x7b292952, 0x3ee3e3dd, 0x712f2f5e, 0x97848413, 0xf55353a6, 0x68d1d1b9, 0x0, 0x2cededc1, 0x60202040, 0x1ffcfce3, 0xc8b1b179, 0xed5b5bb6, 0xbe6a6ad4, 0x46cbcb8d, 0xd9bebe67, 0x4b393972, 0xde4a4a94, 0xd44c4c98, 0xe85858b0, 0x4acfcf85, 0x6bd0d0bb, 0x2aefefc5, 0xe5aaaa4f, 0x16fbfbed, 0xc5434386, 0xd74d4d9a, 0x55333366, 0x94858511, 0xcf45458a, 0x10f9f9e9, 0x6020204, 0x817f7ffe, 0xf05050a0, 0x443c3c78, 0xba9f9f25, 0xe3a8a84b, 0xf35151a2, 0xfea3a35d, 0xc0404080, 0x8a8f8f05, 0xad92923f, 0xbc9d9d21, 0x48383870, 0x4f5f5f1, 0xdfbcbc63, 0xc1b6b677, 0x75dadaaf, 0x63212142, 0x30101020, 0x1affffe5, 0xef3f3fd, 0x6dd2d2bf, 0x4ccdcd81, 0x140c0c18, 0x35131326, 0x2fececc3, 0xe15f5fbe, 0xa2979735, 0xcc444488, 0x3917172e, 0x57c4c493, 0xf2a7a755, 0x827e7efc, 0x473d3d7a, 0xac6464c8, 0xe75d5dba, 0x2b191932, 0x957373e6, 0xa06060c0, 0x98818119, 0xd14f4f9e, 0x7fdcdca3, 0x66222244, 0x7e2a2a54, 0xab90903b, 0x8388880b, 0xca46468c, 0x29eeeec7, 0xd3b8b86b, 0x3c141428, 0x79dedea7, 0xe25e5ebc, 0x1d0b0b16, 0x76dbdbad, 0x3be0e0db, 0x56323264, 0x4e3a3a74, 0x1e0a0a14, 0xdb494992, 0xa06060c, 0x6c242448, 0xe45c5cb8, 0x5dc2c29f, 0x6ed3d3bd, 0xefacac43, 0xa66262c4, 0xa8919139, 0xa4959531, 0x37e4e4d3, 0x8b7979f2, 0x32e7e7d5, 0x43c8c88b, 0x5937376e, 0xb76d6dda, 0x8c8d8d01, 0x64d5d5b1, 0xd24e4e9c, 0xe0a9a949, 0xb46c6cd8, 0xfa5656ac, 0x7f4f4f3, 0x25eaeacf, 0xaf6565ca, 0x8e7a7af4, 0xe9aeae47, 0x18080810, 0xd5baba6f, 0x887878f0, 0x6f25254a, 0x722e2e5c, 0x241c1c38, 0xf1a6a657, 0xc7b4b473, 0x51c6c697, 0x23e8e8cb, 0x7cdddda1, 0x9c7474e8, 0x211f1f3e, 0xdd4b4b96, 0xdcbdbd61, 0x868b8b0d, 0x858a8a0f, 0x907070e0, 0x423e3e7c, 0xc4b5b571, 0xaa6666cc, 0xd8484890, 0x5030306, 0x1f6f6f7, 0x120e0e1c, 0xa36161c2, 0x5f35356a, 0xf95757ae, 0xd0b9b969, 0x91868617, 0x58c1c199, 0x271d1d3a, 0xb99e9e27, 0x38e1e1d9, 0x13f8f8eb, 0xb398982b, 0x33111122, 0xbb6969d2, 0x70d9d9a9, 0x898e8e07, 0xa7949433, 0xb69b9b2d, 0x221e1e3c, 0x92878715, 0x20e9e9c9, 0x49cece87, 0xff5555aa, 0x78282850, 0x7adfdfa5, 0x8f8c8c03, 0xf8a1a159, 0x80898909, 0x170d0d1a, 0xdabfbf65, 0x31e6e6d7, 0xc6424284, 0xb86868d0, 0xc3414182, 0xb0999929, 0x772d2d5a, 0x110f0f1e, 0xcbb0b07b, 0xfc5454a8, 0xd6bbbb6d, 0x3a16162c] + fileprivate let T0_INV: Array = [0x50a7f451, 0x5365417e, 0xc3a4171a, 0x965e273a, 0xcb6bab3b, 0xf1459d1f, 0xab58faac, 0x9303e34b, 0x55fa3020, 0xf66d76ad, 0x9176cc88, 0x254c02f5, 0xfcd7e54f, 0xd7cb2ac5, 0x80443526, 0x8fa362b5, 0x495ab1de, 0x671bba25, 0x980eea45, 0xe1c0fe5d, 0x2752fc3, 0x12f04c81, 0xa397468d, 0xc6f9d36b, 0xe75f8f03, 0x959c9215, 0xeb7a6dbf, 0xda595295, 0x2d83bed4, 0xd3217458, 0x2969e049, 0x44c8c98e, 0x6a89c275, 0x78798ef4, 0x6b3e5899, 0xdd71b927, 0xb64fe1be, 0x17ad88f0, 0x66ac20c9, 0xb43ace7d, 0x184adf63, 0x82311ae5, 0x60335197, 0x457f5362, 0xe07764b1, 0x84ae6bbb, 0x1ca081fe, 0x942b08f9, 0x58684870, 0x19fd458f, 0x876cde94, 0xb7f87b52, 0x23d373ab, 0xe2024b72, 0x578f1fe3, 0x2aab5566, 0x728ebb2, 0x3c2b52f, 0x9a7bc586, 0xa50837d3, 0xf2872830, 0xb2a5bf23, 0xba6a0302, 0x5c8216ed, 0x2b1ccf8a, 0x92b479a7, 0xf0f207f3, 0xa1e2694e, 0xcdf4da65, 0xd5be0506, 0x1f6234d1, 0x8afea6c4, 0x9d532e34, 0xa055f3a2, 0x32e18a05, 0x75ebf6a4, 0x39ec830b, 0xaaef6040, 0x69f715e, 0x51106ebd, 0xf98a213e, 0x3d06dd96, 0xae053edd, 0x46bde64d, 0xb58d5491, 0x55dc471, 0x6fd40604, 0xff155060, 0x24fb9819, 0x97e9bdd6, 0xcc434089, 0x779ed967, 0xbd42e8b0, 0x888b8907, 0x385b19e7, 0xdbeec879, 0x470a7ca1, 0xe90f427c, 0xc91e84f8, 0x0, 0x83868009, 0x48ed2b32, 0xac70111e, 0x4e725a6c, 0xfbff0efd, 0x5638850f, 0x1ed5ae3d, 0x27392d36, 0x64d90f0a, 0x21a65c68, 0xd1545b9b, 0x3a2e3624, 0xb1670a0c, 0xfe75793, 0xd296eeb4, 0x9e919b1b, 0x4fc5c080, 0xa220dc61, 0x694b775a, 0x161a121c, 0xaba93e2, 0xe52aa0c0, 0x43e0223c, 0x1d171b12, 0xb0d090e, 0xadc78bf2, 0xb9a8b62d, 0xc8a91e14, 0x8519f157, 0x4c0775af, 0xbbdd99ee, 0xfd607fa3, 0x9f2601f7, 0xbcf5725c, 0xc53b6644, 0x347efb5b, 0x7629438b, 0xdcc623cb, 0x68fcedb6, 0x63f1e4b8, 0xcadc31d7, 0x10856342, 0x40229713, 0x2011c684, 0x7d244a85, 0xf83dbbd2, 0x1132f9ae, 0x6da129c7, 0x4b2f9e1d, 0xf330b2dc, 0xec52860d, 0xd0e3c177, 0x6c16b32b, 0x99b970a9, 0xfa489411, 0x2264e947, 0xc48cfca8, 0x1a3ff0a0, 0xd82c7d56, 0xef903322, 0xc74e4987, 0xc1d138d9, 0xfea2ca8c, 0x360bd498, 0xcf81f5a6, 0x28de7aa5, 0x268eb7da, 0xa4bfad3f, 0xe49d3a2c, 0xd927850, 0x9bcc5f6a, 0x62467e54, 0xc2138df6, 0xe8b8d890, 0x5ef7392e, 0xf5afc382, 0xbe805d9f, 0x7c93d069, 0xa92dd56f, 0xb31225cf, 0x3b99acc8, 0xa77d1810, 0x6e639ce8, 0x7bbb3bdb, 0x97826cd, 0xf418596e, 0x1b79aec, 0xa89a4f83, 0x656e95e6, 0x7ee6ffaa, 0x8cfbc21, 0xe6e815ef, 0xd99be7ba, 0xce366f4a, 0xd4099fea, 0xd67cb029, 0xafb2a431, 0x31233f2a, 0x3094a5c6, 0xc066a235, 0x37bc4e74, 0xa6ca82fc, 0xb0d090e0, 0x15d8a733, 0x4a9804f1, 0xf7daec41, 0xe50cd7f, 0x2ff69117, 0x8dd64d76, 0x4db0ef43, 0x544daacc, 0xdf0496e4, 0xe3b5d19e, 0x1b886a4c, 0xb81f2cc1, 0x7f516546, 0x4ea5e9d, 0x5d358c01, 0x737487fa, 0x2e410bfb, 0x5a1d67b3, 0x52d2db92, 0x335610e9, 0x1347d66d, 0x8c61d79a, 0x7a0ca137, 0x8e14f859, 0x893c13eb, 0xee27a9ce, 0x35c961b7, 0xede51ce1, 0x3cb1477a, 0x59dfd29c, 0x3f73f255, 0x79ce1418, 0xbf37c773, 0xeacdf753, 0x5baafd5f, 0x146f3ddf, 0x86db4478, 0x81f3afca, 0x3ec468b9, 0x2c342438, 0x5f40a3c2, 0x72c31d16, 0xc25e2bc, 0x8b493c28, 0x41950dff, 0x7101a839, 0xdeb30c08, 0x9ce4b4d8, 0x90c15664, 0x6184cb7b, 0x70b632d5, 0x745c6c48, 0x4257b8d0] + fileprivate let T1: Array = [0x6363c6a5, 0x7c7cf884, 0x7777ee99, 0x7b7bf68d, 0xf2f2ff0d, 0x6b6bd6bd, 0x6f6fdeb1, 0xc5c59154, 0x30306050, 0x1010203, 0x6767cea9, 0x2b2b567d, 0xfefee719, 0xd7d7b562, 0xabab4de6, 0x7676ec9a, 0xcaca8f45, 0x82821f9d, 0xc9c98940, 0x7d7dfa87, 0xfafaef15, 0x5959b2eb, 0x47478ec9, 0xf0f0fb0b, 0xadad41ec, 0xd4d4b367, 0xa2a25ffd, 0xafaf45ea, 0x9c9c23bf, 0xa4a453f7, 0x7272e496, 0xc0c09b5b, 0xb7b775c2, 0xfdfde11c, 0x93933dae, 0x26264c6a, 0x36366c5a, 0x3f3f7e41, 0xf7f7f502, 0xcccc834f, 0x3434685c, 0xa5a551f4, 0xe5e5d134, 0xf1f1f908, 0x7171e293, 0xd8d8ab73, 0x31316253, 0x15152a3f, 0x404080c, 0xc7c79552, 0x23234665, 0xc3c39d5e, 0x18183028, 0x969637a1, 0x5050a0f, 0x9a9a2fb5, 0x7070e09, 0x12122436, 0x80801b9b, 0xe2e2df3d, 0xebebcd26, 0x27274e69, 0xb2b27fcd, 0x7575ea9f, 0x909121b, 0x83831d9e, 0x2c2c5874, 0x1a1a342e, 0x1b1b362d, 0x6e6edcb2, 0x5a5ab4ee, 0xa0a05bfb, 0x5252a4f6, 0x3b3b764d, 0xd6d6b761, 0xb3b37dce, 0x2929527b, 0xe3e3dd3e, 0x2f2f5e71, 0x84841397, 0x5353a6f5, 0xd1d1b968, 0x0, 0xededc12c, 0x20204060, 0xfcfce31f, 0xb1b179c8, 0x5b5bb6ed, 0x6a6ad4be, 0xcbcb8d46, 0xbebe67d9, 0x3939724b, 0x4a4a94de, 0x4c4c98d4, 0x5858b0e8, 0xcfcf854a, 0xd0d0bb6b, 0xefefc52a, 0xaaaa4fe5, 0xfbfbed16, 0x434386c5, 0x4d4d9ad7, 0x33336655, 0x85851194, 0x45458acf, 0xf9f9e910, 0x2020406, 0x7f7ffe81, 0x5050a0f0, 0x3c3c7844, 0x9f9f25ba, 0xa8a84be3, 0x5151a2f3, 0xa3a35dfe, 0x404080c0, 0x8f8f058a, 0x92923fad, 0x9d9d21bc, 0x38387048, 0xf5f5f104, 0xbcbc63df, 0xb6b677c1, 0xdadaaf75, 0x21214263, 0x10102030, 0xffffe51a, 0xf3f3fd0e, 0xd2d2bf6d, 0xcdcd814c, 0xc0c1814, 0x13132635, 0xececc32f, 0x5f5fbee1, 0x979735a2, 0x444488cc, 0x17172e39, 0xc4c49357, 0xa7a755f2, 0x7e7efc82, 0x3d3d7a47, 0x6464c8ac, 0x5d5dbae7, 0x1919322b, 0x7373e695, 0x6060c0a0, 0x81811998, 0x4f4f9ed1, 0xdcdca37f, 0x22224466, 0x2a2a547e, 0x90903bab, 0x88880b83, 0x46468cca, 0xeeeec729, 0xb8b86bd3, 0x1414283c, 0xdedea779, 0x5e5ebce2, 0xb0b161d, 0xdbdbad76, 0xe0e0db3b, 0x32326456, 0x3a3a744e, 0xa0a141e, 0x494992db, 0x6060c0a, 0x2424486c, 0x5c5cb8e4, 0xc2c29f5d, 0xd3d3bd6e, 0xacac43ef, 0x6262c4a6, 0x919139a8, 0x959531a4, 0xe4e4d337, 0x7979f28b, 0xe7e7d532, 0xc8c88b43, 0x37376e59, 0x6d6ddab7, 0x8d8d018c, 0xd5d5b164, 0x4e4e9cd2, 0xa9a949e0, 0x6c6cd8b4, 0x5656acfa, 0xf4f4f307, 0xeaeacf25, 0x6565caaf, 0x7a7af48e, 0xaeae47e9, 0x8081018, 0xbaba6fd5, 0x7878f088, 0x25254a6f, 0x2e2e5c72, 0x1c1c3824, 0xa6a657f1, 0xb4b473c7, 0xc6c69751, 0xe8e8cb23, 0xdddda17c, 0x7474e89c, 0x1f1f3e21, 0x4b4b96dd, 0xbdbd61dc, 0x8b8b0d86, 0x8a8a0f85, 0x7070e090, 0x3e3e7c42, 0xb5b571c4, 0x6666ccaa, 0x484890d8, 0x3030605, 0xf6f6f701, 0xe0e1c12, 0x6161c2a3, 0x35356a5f, 0x5757aef9, 0xb9b969d0, 0x86861791, 0xc1c19958, 0x1d1d3a27, 0x9e9e27b9, 0xe1e1d938, 0xf8f8eb13, 0x98982bb3, 0x11112233, 0x6969d2bb, 0xd9d9a970, 0x8e8e0789, 0x949433a7, 0x9b9b2db6, 0x1e1e3c22, 0x87871592, 0xe9e9c920, 0xcece8749, 0x5555aaff, 0x28285078, 0xdfdfa57a, 0x8c8c038f, 0xa1a159f8, 0x89890980, 0xd0d1a17, 0xbfbf65da, 0xe6e6d731, 0x424284c6, 0x6868d0b8, 0x414182c3, 0x999929b0, 0x2d2d5a77, 0xf0f1e11, 0xb0b07bcb, 0x5454a8fc, 0xbbbb6dd6, 0x16162c3a] + fileprivate let T1_INV: Array = [0xa7f45150, 0x65417e53, 0xa4171ac3, 0x5e273a96, 0x6bab3bcb, 0x459d1ff1, 0x58faacab, 0x3e34b93, 0xfa302055, 0x6d76adf6, 0x76cc8891, 0x4c02f525, 0xd7e54ffc, 0xcb2ac5d7, 0x44352680, 0xa362b58f, 0x5ab1de49, 0x1bba2567, 0xeea4598, 0xc0fe5de1, 0x752fc302, 0xf04c8112, 0x97468da3, 0xf9d36bc6, 0x5f8f03e7, 0x9c921595, 0x7a6dbfeb, 0x595295da, 0x83bed42d, 0x217458d3, 0x69e04929, 0xc8c98e44, 0x89c2756a, 0x798ef478, 0x3e58996b, 0x71b927dd, 0x4fe1beb6, 0xad88f017, 0xac20c966, 0x3ace7db4, 0x4adf6318, 0x311ae582, 0x33519760, 0x7f536245, 0x7764b1e0, 0xae6bbb84, 0xa081fe1c, 0x2b08f994, 0x68487058, 0xfd458f19, 0x6cde9487, 0xf87b52b7, 0xd373ab23, 0x24b72e2, 0x8f1fe357, 0xab55662a, 0x28ebb207, 0xc2b52f03, 0x7bc5869a, 0x837d3a5, 0x872830f2, 0xa5bf23b2, 0x6a0302ba, 0x8216ed5c, 0x1ccf8a2b, 0xb479a792, 0xf207f3f0, 0xe2694ea1, 0xf4da65cd, 0xbe0506d5, 0x6234d11f, 0xfea6c48a, 0x532e349d, 0x55f3a2a0, 0xe18a0532, 0xebf6a475, 0xec830b39, 0xef6040aa, 0x9f715e06, 0x106ebd51, 0x8a213ef9, 0x6dd963d, 0x53eddae, 0xbde64d46, 0x8d5491b5, 0x5dc47105, 0xd406046f, 0x155060ff, 0xfb981924, 0xe9bdd697, 0x434089cc, 0x9ed96777, 0x42e8b0bd, 0x8b890788, 0x5b19e738, 0xeec879db, 0xa7ca147, 0xf427ce9, 0x1e84f8c9, 0x0, 0x86800983, 0xed2b3248, 0x70111eac, 0x725a6c4e, 0xff0efdfb, 0x38850f56, 0xd5ae3d1e, 0x392d3627, 0xd90f0a64, 0xa65c6821, 0x545b9bd1, 0x2e36243a, 0x670a0cb1, 0xe757930f, 0x96eeb4d2, 0x919b1b9e, 0xc5c0804f, 0x20dc61a2, 0x4b775a69, 0x1a121c16, 0xba93e20a, 0x2aa0c0e5, 0xe0223c43, 0x171b121d, 0xd090e0b, 0xc78bf2ad, 0xa8b62db9, 0xa91e14c8, 0x19f15785, 0x775af4c, 0xdd99eebb, 0x607fa3fd, 0x2601f79f, 0xf5725cbc, 0x3b6644c5, 0x7efb5b34, 0x29438b76, 0xc623cbdc, 0xfcedb668, 0xf1e4b863, 0xdc31d7ca, 0x85634210, 0x22971340, 0x11c68420, 0x244a857d, 0x3dbbd2f8, 0x32f9ae11, 0xa129c76d, 0x2f9e1d4b, 0x30b2dcf3, 0x52860dec, 0xe3c177d0, 0x16b32b6c, 0xb970a999, 0x489411fa, 0x64e94722, 0x8cfca8c4, 0x3ff0a01a, 0x2c7d56d8, 0x903322ef, 0x4e4987c7, 0xd138d9c1, 0xa2ca8cfe, 0xbd49836, 0x81f5a6cf, 0xde7aa528, 0x8eb7da26, 0xbfad3fa4, 0x9d3a2ce4, 0x9278500d, 0xcc5f6a9b, 0x467e5462, 0x138df6c2, 0xb8d890e8, 0xf7392e5e, 0xafc382f5, 0x805d9fbe, 0x93d0697c, 0x2dd56fa9, 0x1225cfb3, 0x99acc83b, 0x7d1810a7, 0x639ce86e, 0xbb3bdb7b, 0x7826cd09, 0x18596ef4, 0xb79aec01, 0x9a4f83a8, 0x6e95e665, 0xe6ffaa7e, 0xcfbc2108, 0xe815efe6, 0x9be7bad9, 0x366f4ace, 0x99fead4, 0x7cb029d6, 0xb2a431af, 0x233f2a31, 0x94a5c630, 0x66a235c0, 0xbc4e7437, 0xca82fca6, 0xd090e0b0, 0xd8a73315, 0x9804f14a, 0xdaec41f7, 0x50cd7f0e, 0xf691172f, 0xd64d768d, 0xb0ef434d, 0x4daacc54, 0x496e4df, 0xb5d19ee3, 0x886a4c1b, 0x1f2cc1b8, 0x5165467f, 0xea5e9d04, 0x358c015d, 0x7487fa73, 0x410bfb2e, 0x1d67b35a, 0xd2db9252, 0x5610e933, 0x47d66d13, 0x61d79a8c, 0xca1377a, 0x14f8598e, 0x3c13eb89, 0x27a9ceee, 0xc961b735, 0xe51ce1ed, 0xb1477a3c, 0xdfd29c59, 0x73f2553f, 0xce141879, 0x37c773bf, 0xcdf753ea, 0xaafd5f5b, 0x6f3ddf14, 0xdb447886, 0xf3afca81, 0xc468b93e, 0x3424382c, 0x40a3c25f, 0xc31d1672, 0x25e2bc0c, 0x493c288b, 0x950dff41, 0x1a83971, 0xb30c08de, 0xe4b4d89c, 0xc1566490, 0x84cb7b61, 0xb632d570, 0x5c6c4874, 0x57b8d042] + fileprivate let T2: Array = [0x63c6a563, 0x7cf8847c, 0x77ee9977, 0x7bf68d7b, 0xf2ff0df2, 0x6bd6bd6b, 0x6fdeb16f, 0xc59154c5, 0x30605030, 0x1020301, 0x67cea967, 0x2b567d2b, 0xfee719fe, 0xd7b562d7, 0xab4de6ab, 0x76ec9a76, 0xca8f45ca, 0x821f9d82, 0xc98940c9, 0x7dfa877d, 0xfaef15fa, 0x59b2eb59, 0x478ec947, 0xf0fb0bf0, 0xad41ecad, 0xd4b367d4, 0xa25ffda2, 0xaf45eaaf, 0x9c23bf9c, 0xa453f7a4, 0x72e49672, 0xc09b5bc0, 0xb775c2b7, 0xfde11cfd, 0x933dae93, 0x264c6a26, 0x366c5a36, 0x3f7e413f, 0xf7f502f7, 0xcc834fcc, 0x34685c34, 0xa551f4a5, 0xe5d134e5, 0xf1f908f1, 0x71e29371, 0xd8ab73d8, 0x31625331, 0x152a3f15, 0x4080c04, 0xc79552c7, 0x23466523, 0xc39d5ec3, 0x18302818, 0x9637a196, 0x50a0f05, 0x9a2fb59a, 0x70e0907, 0x12243612, 0x801b9b80, 0xe2df3de2, 0xebcd26eb, 0x274e6927, 0xb27fcdb2, 0x75ea9f75, 0x9121b09, 0x831d9e83, 0x2c58742c, 0x1a342e1a, 0x1b362d1b, 0x6edcb26e, 0x5ab4ee5a, 0xa05bfba0, 0x52a4f652, 0x3b764d3b, 0xd6b761d6, 0xb37dceb3, 0x29527b29, 0xe3dd3ee3, 0x2f5e712f, 0x84139784, 0x53a6f553, 0xd1b968d1, 0x0, 0xedc12ced, 0x20406020, 0xfce31ffc, 0xb179c8b1, 0x5bb6ed5b, 0x6ad4be6a, 0xcb8d46cb, 0xbe67d9be, 0x39724b39, 0x4a94de4a, 0x4c98d44c, 0x58b0e858, 0xcf854acf, 0xd0bb6bd0, 0xefc52aef, 0xaa4fe5aa, 0xfbed16fb, 0x4386c543, 0x4d9ad74d, 0x33665533, 0x85119485, 0x458acf45, 0xf9e910f9, 0x2040602, 0x7ffe817f, 0x50a0f050, 0x3c78443c, 0x9f25ba9f, 0xa84be3a8, 0x51a2f351, 0xa35dfea3, 0x4080c040, 0x8f058a8f, 0x923fad92, 0x9d21bc9d, 0x38704838, 0xf5f104f5, 0xbc63dfbc, 0xb677c1b6, 0xdaaf75da, 0x21426321, 0x10203010, 0xffe51aff, 0xf3fd0ef3, 0xd2bf6dd2, 0xcd814ccd, 0xc18140c, 0x13263513, 0xecc32fec, 0x5fbee15f, 0x9735a297, 0x4488cc44, 0x172e3917, 0xc49357c4, 0xa755f2a7, 0x7efc827e, 0x3d7a473d, 0x64c8ac64, 0x5dbae75d, 0x19322b19, 0x73e69573, 0x60c0a060, 0x81199881, 0x4f9ed14f, 0xdca37fdc, 0x22446622, 0x2a547e2a, 0x903bab90, 0x880b8388, 0x468cca46, 0xeec729ee, 0xb86bd3b8, 0x14283c14, 0xdea779de, 0x5ebce25e, 0xb161d0b, 0xdbad76db, 0xe0db3be0, 0x32645632, 0x3a744e3a, 0xa141e0a, 0x4992db49, 0x60c0a06, 0x24486c24, 0x5cb8e45c, 0xc29f5dc2, 0xd3bd6ed3, 0xac43efac, 0x62c4a662, 0x9139a891, 0x9531a495, 0xe4d337e4, 0x79f28b79, 0xe7d532e7, 0xc88b43c8, 0x376e5937, 0x6ddab76d, 0x8d018c8d, 0xd5b164d5, 0x4e9cd24e, 0xa949e0a9, 0x6cd8b46c, 0x56acfa56, 0xf4f307f4, 0xeacf25ea, 0x65caaf65, 0x7af48e7a, 0xae47e9ae, 0x8101808, 0xba6fd5ba, 0x78f08878, 0x254a6f25, 0x2e5c722e, 0x1c38241c, 0xa657f1a6, 0xb473c7b4, 0xc69751c6, 0xe8cb23e8, 0xdda17cdd, 0x74e89c74, 0x1f3e211f, 0x4b96dd4b, 0xbd61dcbd, 0x8b0d868b, 0x8a0f858a, 0x70e09070, 0x3e7c423e, 0xb571c4b5, 0x66ccaa66, 0x4890d848, 0x3060503, 0xf6f701f6, 0xe1c120e, 0x61c2a361, 0x356a5f35, 0x57aef957, 0xb969d0b9, 0x86179186, 0xc19958c1, 0x1d3a271d, 0x9e27b99e, 0xe1d938e1, 0xf8eb13f8, 0x982bb398, 0x11223311, 0x69d2bb69, 0xd9a970d9, 0x8e07898e, 0x9433a794, 0x9b2db69b, 0x1e3c221e, 0x87159287, 0xe9c920e9, 0xce8749ce, 0x55aaff55, 0x28507828, 0xdfa57adf, 0x8c038f8c, 0xa159f8a1, 0x89098089, 0xd1a170d, 0xbf65dabf, 0xe6d731e6, 0x4284c642, 0x68d0b868, 0x4182c341, 0x9929b099, 0x2d5a772d, 0xf1e110f, 0xb07bcbb0, 0x54a8fc54, 0xbb6dd6bb, 0x162c3a16] + fileprivate let T2_INV: Array = [0xf45150a7, 0x417e5365, 0x171ac3a4, 0x273a965e, 0xab3bcb6b, 0x9d1ff145, 0xfaacab58, 0xe34b9303, 0x302055fa, 0x76adf66d, 0xcc889176, 0x2f5254c, 0xe54ffcd7, 0x2ac5d7cb, 0x35268044, 0x62b58fa3, 0xb1de495a, 0xba25671b, 0xea45980e, 0xfe5de1c0, 0x2fc30275, 0x4c8112f0, 0x468da397, 0xd36bc6f9, 0x8f03e75f, 0x9215959c, 0x6dbfeb7a, 0x5295da59, 0xbed42d83, 0x7458d321, 0xe0492969, 0xc98e44c8, 0xc2756a89, 0x8ef47879, 0x58996b3e, 0xb927dd71, 0xe1beb64f, 0x88f017ad, 0x20c966ac, 0xce7db43a, 0xdf63184a, 0x1ae58231, 0x51976033, 0x5362457f, 0x64b1e077, 0x6bbb84ae, 0x81fe1ca0, 0x8f9942b, 0x48705868, 0x458f19fd, 0xde94876c, 0x7b52b7f8, 0x73ab23d3, 0x4b72e202, 0x1fe3578f, 0x55662aab, 0xebb20728, 0xb52f03c2, 0xc5869a7b, 0x37d3a508, 0x2830f287, 0xbf23b2a5, 0x302ba6a, 0x16ed5c82, 0xcf8a2b1c, 0x79a792b4, 0x7f3f0f2, 0x694ea1e2, 0xda65cdf4, 0x506d5be, 0x34d11f62, 0xa6c48afe, 0x2e349d53, 0xf3a2a055, 0x8a0532e1, 0xf6a475eb, 0x830b39ec, 0x6040aaef, 0x715e069f, 0x6ebd5110, 0x213ef98a, 0xdd963d06, 0x3eddae05, 0xe64d46bd, 0x5491b58d, 0xc471055d, 0x6046fd4, 0x5060ff15, 0x981924fb, 0xbdd697e9, 0x4089cc43, 0xd967779e, 0xe8b0bd42, 0x8907888b, 0x19e7385b, 0xc879dbee, 0x7ca1470a, 0x427ce90f, 0x84f8c91e, 0x0, 0x80098386, 0x2b3248ed, 0x111eac70, 0x5a6c4e72, 0xefdfbff, 0x850f5638, 0xae3d1ed5, 0x2d362739, 0xf0a64d9, 0x5c6821a6, 0x5b9bd154, 0x36243a2e, 0xa0cb167, 0x57930fe7, 0xeeb4d296, 0x9b1b9e91, 0xc0804fc5, 0xdc61a220, 0x775a694b, 0x121c161a, 0x93e20aba, 0xa0c0e52a, 0x223c43e0, 0x1b121d17, 0x90e0b0d, 0x8bf2adc7, 0xb62db9a8, 0x1e14c8a9, 0xf1578519, 0x75af4c07, 0x99eebbdd, 0x7fa3fd60, 0x1f79f26, 0x725cbcf5, 0x6644c53b, 0xfb5b347e, 0x438b7629, 0x23cbdcc6, 0xedb668fc, 0xe4b863f1, 0x31d7cadc, 0x63421085, 0x97134022, 0xc6842011, 0x4a857d24, 0xbbd2f83d, 0xf9ae1132, 0x29c76da1, 0x9e1d4b2f, 0xb2dcf330, 0x860dec52, 0xc177d0e3, 0xb32b6c16, 0x70a999b9, 0x9411fa48, 0xe9472264, 0xfca8c48c, 0xf0a01a3f, 0x7d56d82c, 0x3322ef90, 0x4987c74e, 0x38d9c1d1, 0xca8cfea2, 0xd498360b, 0xf5a6cf81, 0x7aa528de, 0xb7da268e, 0xad3fa4bf, 0x3a2ce49d, 0x78500d92, 0x5f6a9bcc, 0x7e546246, 0x8df6c213, 0xd890e8b8, 0x392e5ef7, 0xc382f5af, 0x5d9fbe80, 0xd0697c93, 0xd56fa92d, 0x25cfb312, 0xacc83b99, 0x1810a77d, 0x9ce86e63, 0x3bdb7bbb, 0x26cd0978, 0x596ef418, 0x9aec01b7, 0x4f83a89a, 0x95e6656e, 0xffaa7ee6, 0xbc2108cf, 0x15efe6e8, 0xe7bad99b, 0x6f4ace36, 0x9fead409, 0xb029d67c, 0xa431afb2, 0x3f2a3123, 0xa5c63094, 0xa235c066, 0x4e7437bc, 0x82fca6ca, 0x90e0b0d0, 0xa73315d8, 0x4f14a98, 0xec41f7da, 0xcd7f0e50, 0x91172ff6, 0x4d768dd6, 0xef434db0, 0xaacc544d, 0x96e4df04, 0xd19ee3b5, 0x6a4c1b88, 0x2cc1b81f, 0x65467f51, 0x5e9d04ea, 0x8c015d35, 0x87fa7374, 0xbfb2e41, 0x67b35a1d, 0xdb9252d2, 0x10e93356, 0xd66d1347, 0xd79a8c61, 0xa1377a0c, 0xf8598e14, 0x13eb893c, 0xa9ceee27, 0x61b735c9, 0x1ce1ede5, 0x477a3cb1, 0xd29c59df, 0xf2553f73, 0x141879ce, 0xc773bf37, 0xf753eacd, 0xfd5f5baa, 0x3ddf146f, 0x447886db, 0xafca81f3, 0x68b93ec4, 0x24382c34, 0xa3c25f40, 0x1d1672c3, 0xe2bc0c25, 0x3c288b49, 0xdff4195, 0xa8397101, 0xc08deb3, 0xb4d89ce4, 0x566490c1, 0xcb7b6184, 0x32d570b6, 0x6c48745c, 0xb8d04257] + fileprivate let T3: Array = [0xc6a56363, 0xf8847c7c, 0xee997777, 0xf68d7b7b, 0xff0df2f2, 0xd6bd6b6b, 0xdeb16f6f, 0x9154c5c5, 0x60503030, 0x2030101, 0xcea96767, 0x567d2b2b, 0xe719fefe, 0xb562d7d7, 0x4de6abab, 0xec9a7676, 0x8f45caca, 0x1f9d8282, 0x8940c9c9, 0xfa877d7d, 0xef15fafa, 0xb2eb5959, 0x8ec94747, 0xfb0bf0f0, 0x41ecadad, 0xb367d4d4, 0x5ffda2a2, 0x45eaafaf, 0x23bf9c9c, 0x53f7a4a4, 0xe4967272, 0x9b5bc0c0, 0x75c2b7b7, 0xe11cfdfd, 0x3dae9393, 0x4c6a2626, 0x6c5a3636, 0x7e413f3f, 0xf502f7f7, 0x834fcccc, 0x685c3434, 0x51f4a5a5, 0xd134e5e5, 0xf908f1f1, 0xe2937171, 0xab73d8d8, 0x62533131, 0x2a3f1515, 0x80c0404, 0x9552c7c7, 0x46652323, 0x9d5ec3c3, 0x30281818, 0x37a19696, 0xa0f0505, 0x2fb59a9a, 0xe090707, 0x24361212, 0x1b9b8080, 0xdf3de2e2, 0xcd26ebeb, 0x4e692727, 0x7fcdb2b2, 0xea9f7575, 0x121b0909, 0x1d9e8383, 0x58742c2c, 0x342e1a1a, 0x362d1b1b, 0xdcb26e6e, 0xb4ee5a5a, 0x5bfba0a0, 0xa4f65252, 0x764d3b3b, 0xb761d6d6, 0x7dceb3b3, 0x527b2929, 0xdd3ee3e3, 0x5e712f2f, 0x13978484, 0xa6f55353, 0xb968d1d1, 0x0, 0xc12ceded, 0x40602020, 0xe31ffcfc, 0x79c8b1b1, 0xb6ed5b5b, 0xd4be6a6a, 0x8d46cbcb, 0x67d9bebe, 0x724b3939, 0x94de4a4a, 0x98d44c4c, 0xb0e85858, 0x854acfcf, 0xbb6bd0d0, 0xc52aefef, 0x4fe5aaaa, 0xed16fbfb, 0x86c54343, 0x9ad74d4d, 0x66553333, 0x11948585, 0x8acf4545, 0xe910f9f9, 0x4060202, 0xfe817f7f, 0xa0f05050, 0x78443c3c, 0x25ba9f9f, 0x4be3a8a8, 0xa2f35151, 0x5dfea3a3, 0x80c04040, 0x58a8f8f, 0x3fad9292, 0x21bc9d9d, 0x70483838, 0xf104f5f5, 0x63dfbcbc, 0x77c1b6b6, 0xaf75dada, 0x42632121, 0x20301010, 0xe51affff, 0xfd0ef3f3, 0xbf6dd2d2, 0x814ccdcd, 0x18140c0c, 0x26351313, 0xc32fecec, 0xbee15f5f, 0x35a29797, 0x88cc4444, 0x2e391717, 0x9357c4c4, 0x55f2a7a7, 0xfc827e7e, 0x7a473d3d, 0xc8ac6464, 0xbae75d5d, 0x322b1919, 0xe6957373, 0xc0a06060, 0x19988181, 0x9ed14f4f, 0xa37fdcdc, 0x44662222, 0x547e2a2a, 0x3bab9090, 0xb838888, 0x8cca4646, 0xc729eeee, 0x6bd3b8b8, 0x283c1414, 0xa779dede, 0xbce25e5e, 0x161d0b0b, 0xad76dbdb, 0xdb3be0e0, 0x64563232, 0x744e3a3a, 0x141e0a0a, 0x92db4949, 0xc0a0606, 0x486c2424, 0xb8e45c5c, 0x9f5dc2c2, 0xbd6ed3d3, 0x43efacac, 0xc4a66262, 0x39a89191, 0x31a49595, 0xd337e4e4, 0xf28b7979, 0xd532e7e7, 0x8b43c8c8, 0x6e593737, 0xdab76d6d, 0x18c8d8d, 0xb164d5d5, 0x9cd24e4e, 0x49e0a9a9, 0xd8b46c6c, 0xacfa5656, 0xf307f4f4, 0xcf25eaea, 0xcaaf6565, 0xf48e7a7a, 0x47e9aeae, 0x10180808, 0x6fd5baba, 0xf0887878, 0x4a6f2525, 0x5c722e2e, 0x38241c1c, 0x57f1a6a6, 0x73c7b4b4, 0x9751c6c6, 0xcb23e8e8, 0xa17cdddd, 0xe89c7474, 0x3e211f1f, 0x96dd4b4b, 0x61dcbdbd, 0xd868b8b, 0xf858a8a, 0xe0907070, 0x7c423e3e, 0x71c4b5b5, 0xccaa6666, 0x90d84848, 0x6050303, 0xf701f6f6, 0x1c120e0e, 0xc2a36161, 0x6a5f3535, 0xaef95757, 0x69d0b9b9, 0x17918686, 0x9958c1c1, 0x3a271d1d, 0x27b99e9e, 0xd938e1e1, 0xeb13f8f8, 0x2bb39898, 0x22331111, 0xd2bb6969, 0xa970d9d9, 0x7898e8e, 0x33a79494, 0x2db69b9b, 0x3c221e1e, 0x15928787, 0xc920e9e9, 0x8749cece, 0xaaff5555, 0x50782828, 0xa57adfdf, 0x38f8c8c, 0x59f8a1a1, 0x9808989, 0x1a170d0d, 0x65dabfbf, 0xd731e6e6, 0x84c64242, 0xd0b86868, 0x82c34141, 0x29b09999, 0x5a772d2d, 0x1e110f0f, 0x7bcbb0b0, 0xa8fc5454, 0x6dd6bbbb, 0x2c3a1616] + fileprivate let T3_INV: Array = [0x5150a7f4, 0x7e536541, 0x1ac3a417, 0x3a965e27, 0x3bcb6bab, 0x1ff1459d, 0xacab58fa, 0x4b9303e3, 0x2055fa30, 0xadf66d76, 0x889176cc, 0xf5254c02, 0x4ffcd7e5, 0xc5d7cb2a, 0x26804435, 0xb58fa362, 0xde495ab1, 0x25671bba, 0x45980eea, 0x5de1c0fe, 0xc302752f, 0x8112f04c, 0x8da39746, 0x6bc6f9d3, 0x3e75f8f, 0x15959c92, 0xbfeb7a6d, 0x95da5952, 0xd42d83be, 0x58d32174, 0x492969e0, 0x8e44c8c9, 0x756a89c2, 0xf478798e, 0x996b3e58, 0x27dd71b9, 0xbeb64fe1, 0xf017ad88, 0xc966ac20, 0x7db43ace, 0x63184adf, 0xe582311a, 0x97603351, 0x62457f53, 0xb1e07764, 0xbb84ae6b, 0xfe1ca081, 0xf9942b08, 0x70586848, 0x8f19fd45, 0x94876cde, 0x52b7f87b, 0xab23d373, 0x72e2024b, 0xe3578f1f, 0x662aab55, 0xb20728eb, 0x2f03c2b5, 0x869a7bc5, 0xd3a50837, 0x30f28728, 0x23b2a5bf, 0x2ba6a03, 0xed5c8216, 0x8a2b1ccf, 0xa792b479, 0xf3f0f207, 0x4ea1e269, 0x65cdf4da, 0x6d5be05, 0xd11f6234, 0xc48afea6, 0x349d532e, 0xa2a055f3, 0x532e18a, 0xa475ebf6, 0xb39ec83, 0x40aaef60, 0x5e069f71, 0xbd51106e, 0x3ef98a21, 0x963d06dd, 0xddae053e, 0x4d46bde6, 0x91b58d54, 0x71055dc4, 0x46fd406, 0x60ff1550, 0x1924fb98, 0xd697e9bd, 0x89cc4340, 0x67779ed9, 0xb0bd42e8, 0x7888b89, 0xe7385b19, 0x79dbeec8, 0xa1470a7c, 0x7ce90f42, 0xf8c91e84, 0x0, 0x9838680, 0x3248ed2b, 0x1eac7011, 0x6c4e725a, 0xfdfbff0e, 0xf563885, 0x3d1ed5ae, 0x3627392d, 0xa64d90f, 0x6821a65c, 0x9bd1545b, 0x243a2e36, 0xcb1670a, 0x930fe757, 0xb4d296ee, 0x1b9e919b, 0x804fc5c0, 0x61a220dc, 0x5a694b77, 0x1c161a12, 0xe20aba93, 0xc0e52aa0, 0x3c43e022, 0x121d171b, 0xe0b0d09, 0xf2adc78b, 0x2db9a8b6, 0x14c8a91e, 0x578519f1, 0xaf4c0775, 0xeebbdd99, 0xa3fd607f, 0xf79f2601, 0x5cbcf572, 0x44c53b66, 0x5b347efb, 0x8b762943, 0xcbdcc623, 0xb668fced, 0xb863f1e4, 0xd7cadc31, 0x42108563, 0x13402297, 0x842011c6, 0x857d244a, 0xd2f83dbb, 0xae1132f9, 0xc76da129, 0x1d4b2f9e, 0xdcf330b2, 0xdec5286, 0x77d0e3c1, 0x2b6c16b3, 0xa999b970, 0x11fa4894, 0x472264e9, 0xa8c48cfc, 0xa01a3ff0, 0x56d82c7d, 0x22ef9033, 0x87c74e49, 0xd9c1d138, 0x8cfea2ca, 0x98360bd4, 0xa6cf81f5, 0xa528de7a, 0xda268eb7, 0x3fa4bfad, 0x2ce49d3a, 0x500d9278, 0x6a9bcc5f, 0x5462467e, 0xf6c2138d, 0x90e8b8d8, 0x2e5ef739, 0x82f5afc3, 0x9fbe805d, 0x697c93d0, 0x6fa92dd5, 0xcfb31225, 0xc83b99ac, 0x10a77d18, 0xe86e639c, 0xdb7bbb3b, 0xcd097826, 0x6ef41859, 0xec01b79a, 0x83a89a4f, 0xe6656e95, 0xaa7ee6ff, 0x2108cfbc, 0xefe6e815, 0xbad99be7, 0x4ace366f, 0xead4099f, 0x29d67cb0, 0x31afb2a4, 0x2a31233f, 0xc63094a5, 0x35c066a2, 0x7437bc4e, 0xfca6ca82, 0xe0b0d090, 0x3315d8a7, 0xf14a9804, 0x41f7daec, 0x7f0e50cd, 0x172ff691, 0x768dd64d, 0x434db0ef, 0xcc544daa, 0xe4df0496, 0x9ee3b5d1, 0x4c1b886a, 0xc1b81f2c, 0x467f5165, 0x9d04ea5e, 0x15d358c, 0xfa737487, 0xfb2e410b, 0xb35a1d67, 0x9252d2db, 0xe9335610, 0x6d1347d6, 0x9a8c61d7, 0x377a0ca1, 0x598e14f8, 0xeb893c13, 0xceee27a9, 0xb735c961, 0xe1ede51c, 0x7a3cb147, 0x9c59dfd2, 0x553f73f2, 0x1879ce14, 0x73bf37c7, 0x53eacdf7, 0x5f5baafd, 0xdf146f3d, 0x7886db44, 0xca81f3af, 0xb93ec468, 0x382c3424, 0xc25f40a3, 0x1672c31d, 0xbc0c25e2, 0x288b493c, 0xff41950d, 0x397101a8, 0x8deb30c, 0xd89ce4b4, 0x6490c156, 0x7b6184cb, 0xd570b632, 0x48745c6c, 0xd04257b8] + fileprivate var U1: Array = [0x0, 0xb0d090e, 0x161a121c, 0x1d171b12, 0x2c342438, 0x27392d36, 0x3a2e3624, 0x31233f2a, 0x58684870, 0x5365417e, 0x4e725a6c, 0x457f5362, 0x745c6c48, 0x7f516546, 0x62467e54, 0x694b775a, 0xb0d090e0, 0xbbdd99ee, 0xa6ca82fc, 0xadc78bf2, 0x9ce4b4d8, 0x97e9bdd6, 0x8afea6c4, 0x81f3afca, 0xe8b8d890, 0xe3b5d19e, 0xfea2ca8c, 0xf5afc382, 0xc48cfca8, 0xcf81f5a6, 0xd296eeb4, 0xd99be7ba, 0x7bbb3bdb, 0x70b632d5, 0x6da129c7, 0x66ac20c9, 0x578f1fe3, 0x5c8216ed, 0x41950dff, 0x4a9804f1, 0x23d373ab, 0x28de7aa5, 0x35c961b7, 0x3ec468b9, 0xfe75793, 0x4ea5e9d, 0x19fd458f, 0x12f04c81, 0xcb6bab3b, 0xc066a235, 0xdd71b927, 0xd67cb029, 0xe75f8f03, 0xec52860d, 0xf1459d1f, 0xfa489411, 0x9303e34b, 0x980eea45, 0x8519f157, 0x8e14f859, 0xbf37c773, 0xb43ace7d, 0xa92dd56f, 0xa220dc61, 0xf66d76ad, 0xfd607fa3, 0xe07764b1, 0xeb7a6dbf, 0xda595295, 0xd1545b9b, 0xcc434089, 0xc74e4987, 0xae053edd, 0xa50837d3, 0xb81f2cc1, 0xb31225cf, 0x82311ae5, 0x893c13eb, 0x942b08f9, 0x9f2601f7, 0x46bde64d, 0x4db0ef43, 0x50a7f451, 0x5baafd5f, 0x6a89c275, 0x6184cb7b, 0x7c93d069, 0x779ed967, 0x1ed5ae3d, 0x15d8a733, 0x8cfbc21, 0x3c2b52f, 0x32e18a05, 0x39ec830b, 0x24fb9819, 0x2ff69117, 0x8dd64d76, 0x86db4478, 0x9bcc5f6a, 0x90c15664, 0xa1e2694e, 0xaaef6040, 0xb7f87b52, 0xbcf5725c, 0xd5be0506, 0xdeb30c08, 0xc3a4171a, 0xc8a91e14, 0xf98a213e, 0xf2872830, 0xef903322, 0xe49d3a2c, 0x3d06dd96, 0x360bd498, 0x2b1ccf8a, 0x2011c684, 0x1132f9ae, 0x1a3ff0a0, 0x728ebb2, 0xc25e2bc, 0x656e95e6, 0x6e639ce8, 0x737487fa, 0x78798ef4, 0x495ab1de, 0x4257b8d0, 0x5f40a3c2, 0x544daacc, 0xf7daec41, 0xfcd7e54f, 0xe1c0fe5d, 0xeacdf753, 0xdbeec879, 0xd0e3c177, 0xcdf4da65, 0xc6f9d36b, 0xafb2a431, 0xa4bfad3f, 0xb9a8b62d, 0xb2a5bf23, 0x83868009, 0x888b8907, 0x959c9215, 0x9e919b1b, 0x470a7ca1, 0x4c0775af, 0x51106ebd, 0x5a1d67b3, 0x6b3e5899, 0x60335197, 0x7d244a85, 0x7629438b, 0x1f6234d1, 0x146f3ddf, 0x97826cd, 0x2752fc3, 0x335610e9, 0x385b19e7, 0x254c02f5, 0x2e410bfb, 0x8c61d79a, 0x876cde94, 0x9a7bc586, 0x9176cc88, 0xa055f3a2, 0xab58faac, 0xb64fe1be, 0xbd42e8b0, 0xd4099fea, 0xdf0496e4, 0xc2138df6, 0xc91e84f8, 0xf83dbbd2, 0xf330b2dc, 0xee27a9ce, 0xe52aa0c0, 0x3cb1477a, 0x37bc4e74, 0x2aab5566, 0x21a65c68, 0x10856342, 0x1b886a4c, 0x69f715e, 0xd927850, 0x64d90f0a, 0x6fd40604, 0x72c31d16, 0x79ce1418, 0x48ed2b32, 0x43e0223c, 0x5ef7392e, 0x55fa3020, 0x1b79aec, 0xaba93e2, 0x17ad88f0, 0x1ca081fe, 0x2d83bed4, 0x268eb7da, 0x3b99acc8, 0x3094a5c6, 0x59dfd29c, 0x52d2db92, 0x4fc5c080, 0x44c8c98e, 0x75ebf6a4, 0x7ee6ffaa, 0x63f1e4b8, 0x68fcedb6, 0xb1670a0c, 0xba6a0302, 0xa77d1810, 0xac70111e, 0x9d532e34, 0x965e273a, 0x8b493c28, 0x80443526, 0xe90f427c, 0xe2024b72, 0xff155060, 0xf418596e, 0xc53b6644, 0xce366f4a, 0xd3217458, 0xd82c7d56, 0x7a0ca137, 0x7101a839, 0x6c16b32b, 0x671bba25, 0x5638850f, 0x5d358c01, 0x40229713, 0x4b2f9e1d, 0x2264e947, 0x2969e049, 0x347efb5b, 0x3f73f255, 0xe50cd7f, 0x55dc471, 0x184adf63, 0x1347d66d, 0xcadc31d7, 0xc1d138d9, 0xdcc623cb, 0xd7cb2ac5, 0xe6e815ef, 0xede51ce1, 0xf0f207f3, 0xfbff0efd, 0x92b479a7, 0x99b970a9, 0x84ae6bbb, 0x8fa362b5, 0xbe805d9f, 0xb58d5491, 0xa89a4f83, 0xa397468d] + fileprivate var U2: Array = [0x0, 0xd090e0b, 0x1a121c16, 0x171b121d, 0x3424382c, 0x392d3627, 0x2e36243a, 0x233f2a31, 0x68487058, 0x65417e53, 0x725a6c4e, 0x7f536245, 0x5c6c4874, 0x5165467f, 0x467e5462, 0x4b775a69, 0xd090e0b0, 0xdd99eebb, 0xca82fca6, 0xc78bf2ad, 0xe4b4d89c, 0xe9bdd697, 0xfea6c48a, 0xf3afca81, 0xb8d890e8, 0xb5d19ee3, 0xa2ca8cfe, 0xafc382f5, 0x8cfca8c4, 0x81f5a6cf, 0x96eeb4d2, 0x9be7bad9, 0xbb3bdb7b, 0xb632d570, 0xa129c76d, 0xac20c966, 0x8f1fe357, 0x8216ed5c, 0x950dff41, 0x9804f14a, 0xd373ab23, 0xde7aa528, 0xc961b735, 0xc468b93e, 0xe757930f, 0xea5e9d04, 0xfd458f19, 0xf04c8112, 0x6bab3bcb, 0x66a235c0, 0x71b927dd, 0x7cb029d6, 0x5f8f03e7, 0x52860dec, 0x459d1ff1, 0x489411fa, 0x3e34b93, 0xeea4598, 0x19f15785, 0x14f8598e, 0x37c773bf, 0x3ace7db4, 0x2dd56fa9, 0x20dc61a2, 0x6d76adf6, 0x607fa3fd, 0x7764b1e0, 0x7a6dbfeb, 0x595295da, 0x545b9bd1, 0x434089cc, 0x4e4987c7, 0x53eddae, 0x837d3a5, 0x1f2cc1b8, 0x1225cfb3, 0x311ae582, 0x3c13eb89, 0x2b08f994, 0x2601f79f, 0xbde64d46, 0xb0ef434d, 0xa7f45150, 0xaafd5f5b, 0x89c2756a, 0x84cb7b61, 0x93d0697c, 0x9ed96777, 0xd5ae3d1e, 0xd8a73315, 0xcfbc2108, 0xc2b52f03, 0xe18a0532, 0xec830b39, 0xfb981924, 0xf691172f, 0xd64d768d, 0xdb447886, 0xcc5f6a9b, 0xc1566490, 0xe2694ea1, 0xef6040aa, 0xf87b52b7, 0xf5725cbc, 0xbe0506d5, 0xb30c08de, 0xa4171ac3, 0xa91e14c8, 0x8a213ef9, 0x872830f2, 0x903322ef, 0x9d3a2ce4, 0x6dd963d, 0xbd49836, 0x1ccf8a2b, 0x11c68420, 0x32f9ae11, 0x3ff0a01a, 0x28ebb207, 0x25e2bc0c, 0x6e95e665, 0x639ce86e, 0x7487fa73, 0x798ef478, 0x5ab1de49, 0x57b8d042, 0x40a3c25f, 0x4daacc54, 0xdaec41f7, 0xd7e54ffc, 0xc0fe5de1, 0xcdf753ea, 0xeec879db, 0xe3c177d0, 0xf4da65cd, 0xf9d36bc6, 0xb2a431af, 0xbfad3fa4, 0xa8b62db9, 0xa5bf23b2, 0x86800983, 0x8b890788, 0x9c921595, 0x919b1b9e, 0xa7ca147, 0x775af4c, 0x106ebd51, 0x1d67b35a, 0x3e58996b, 0x33519760, 0x244a857d, 0x29438b76, 0x6234d11f, 0x6f3ddf14, 0x7826cd09, 0x752fc302, 0x5610e933, 0x5b19e738, 0x4c02f525, 0x410bfb2e, 0x61d79a8c, 0x6cde9487, 0x7bc5869a, 0x76cc8891, 0x55f3a2a0, 0x58faacab, 0x4fe1beb6, 0x42e8b0bd, 0x99fead4, 0x496e4df, 0x138df6c2, 0x1e84f8c9, 0x3dbbd2f8, 0x30b2dcf3, 0x27a9ceee, 0x2aa0c0e5, 0xb1477a3c, 0xbc4e7437, 0xab55662a, 0xa65c6821, 0x85634210, 0x886a4c1b, 0x9f715e06, 0x9278500d, 0xd90f0a64, 0xd406046f, 0xc31d1672, 0xce141879, 0xed2b3248, 0xe0223c43, 0xf7392e5e, 0xfa302055, 0xb79aec01, 0xba93e20a, 0xad88f017, 0xa081fe1c, 0x83bed42d, 0x8eb7da26, 0x99acc83b, 0x94a5c630, 0xdfd29c59, 0xd2db9252, 0xc5c0804f, 0xc8c98e44, 0xebf6a475, 0xe6ffaa7e, 0xf1e4b863, 0xfcedb668, 0x670a0cb1, 0x6a0302ba, 0x7d1810a7, 0x70111eac, 0x532e349d, 0x5e273a96, 0x493c288b, 0x44352680, 0xf427ce9, 0x24b72e2, 0x155060ff, 0x18596ef4, 0x3b6644c5, 0x366f4ace, 0x217458d3, 0x2c7d56d8, 0xca1377a, 0x1a83971, 0x16b32b6c, 0x1bba2567, 0x38850f56, 0x358c015d, 0x22971340, 0x2f9e1d4b, 0x64e94722, 0x69e04929, 0x7efb5b34, 0x73f2553f, 0x50cd7f0e, 0x5dc47105, 0x4adf6318, 0x47d66d13, 0xdc31d7ca, 0xd138d9c1, 0xc623cbdc, 0xcb2ac5d7, 0xe815efe6, 0xe51ce1ed, 0xf207f3f0, 0xff0efdfb, 0xb479a792, 0xb970a999, 0xae6bbb84, 0xa362b58f, 0x805d9fbe, 0x8d5491b5, 0x9a4f83a8, 0x97468da3] + fileprivate var U3: Array = [0x0, 0x90e0b0d, 0x121c161a, 0x1b121d17, 0x24382c34, 0x2d362739, 0x36243a2e, 0x3f2a3123, 0x48705868, 0x417e5365, 0x5a6c4e72, 0x5362457f, 0x6c48745c, 0x65467f51, 0x7e546246, 0x775a694b, 0x90e0b0d0, 0x99eebbdd, 0x82fca6ca, 0x8bf2adc7, 0xb4d89ce4, 0xbdd697e9, 0xa6c48afe, 0xafca81f3, 0xd890e8b8, 0xd19ee3b5, 0xca8cfea2, 0xc382f5af, 0xfca8c48c, 0xf5a6cf81, 0xeeb4d296, 0xe7bad99b, 0x3bdb7bbb, 0x32d570b6, 0x29c76da1, 0x20c966ac, 0x1fe3578f, 0x16ed5c82, 0xdff4195, 0x4f14a98, 0x73ab23d3, 0x7aa528de, 0x61b735c9, 0x68b93ec4, 0x57930fe7, 0x5e9d04ea, 0x458f19fd, 0x4c8112f0, 0xab3bcb6b, 0xa235c066, 0xb927dd71, 0xb029d67c, 0x8f03e75f, 0x860dec52, 0x9d1ff145, 0x9411fa48, 0xe34b9303, 0xea45980e, 0xf1578519, 0xf8598e14, 0xc773bf37, 0xce7db43a, 0xd56fa92d, 0xdc61a220, 0x76adf66d, 0x7fa3fd60, 0x64b1e077, 0x6dbfeb7a, 0x5295da59, 0x5b9bd154, 0x4089cc43, 0x4987c74e, 0x3eddae05, 0x37d3a508, 0x2cc1b81f, 0x25cfb312, 0x1ae58231, 0x13eb893c, 0x8f9942b, 0x1f79f26, 0xe64d46bd, 0xef434db0, 0xf45150a7, 0xfd5f5baa, 0xc2756a89, 0xcb7b6184, 0xd0697c93, 0xd967779e, 0xae3d1ed5, 0xa73315d8, 0xbc2108cf, 0xb52f03c2, 0x8a0532e1, 0x830b39ec, 0x981924fb, 0x91172ff6, 0x4d768dd6, 0x447886db, 0x5f6a9bcc, 0x566490c1, 0x694ea1e2, 0x6040aaef, 0x7b52b7f8, 0x725cbcf5, 0x506d5be, 0xc08deb3, 0x171ac3a4, 0x1e14c8a9, 0x213ef98a, 0x2830f287, 0x3322ef90, 0x3a2ce49d, 0xdd963d06, 0xd498360b, 0xcf8a2b1c, 0xc6842011, 0xf9ae1132, 0xf0a01a3f, 0xebb20728, 0xe2bc0c25, 0x95e6656e, 0x9ce86e63, 0x87fa7374, 0x8ef47879, 0xb1de495a, 0xb8d04257, 0xa3c25f40, 0xaacc544d, 0xec41f7da, 0xe54ffcd7, 0xfe5de1c0, 0xf753eacd, 0xc879dbee, 0xc177d0e3, 0xda65cdf4, 0xd36bc6f9, 0xa431afb2, 0xad3fa4bf, 0xb62db9a8, 0xbf23b2a5, 0x80098386, 0x8907888b, 0x9215959c, 0x9b1b9e91, 0x7ca1470a, 0x75af4c07, 0x6ebd5110, 0x67b35a1d, 0x58996b3e, 0x51976033, 0x4a857d24, 0x438b7629, 0x34d11f62, 0x3ddf146f, 0x26cd0978, 0x2fc30275, 0x10e93356, 0x19e7385b, 0x2f5254c, 0xbfb2e41, 0xd79a8c61, 0xde94876c, 0xc5869a7b, 0xcc889176, 0xf3a2a055, 0xfaacab58, 0xe1beb64f, 0xe8b0bd42, 0x9fead409, 0x96e4df04, 0x8df6c213, 0x84f8c91e, 0xbbd2f83d, 0xb2dcf330, 0xa9ceee27, 0xa0c0e52a, 0x477a3cb1, 0x4e7437bc, 0x55662aab, 0x5c6821a6, 0x63421085, 0x6a4c1b88, 0x715e069f, 0x78500d92, 0xf0a64d9, 0x6046fd4, 0x1d1672c3, 0x141879ce, 0x2b3248ed, 0x223c43e0, 0x392e5ef7, 0x302055fa, 0x9aec01b7, 0x93e20aba, 0x88f017ad, 0x81fe1ca0, 0xbed42d83, 0xb7da268e, 0xacc83b99, 0xa5c63094, 0xd29c59df, 0xdb9252d2, 0xc0804fc5, 0xc98e44c8, 0xf6a475eb, 0xffaa7ee6, 0xe4b863f1, 0xedb668fc, 0xa0cb167, 0x302ba6a, 0x1810a77d, 0x111eac70, 0x2e349d53, 0x273a965e, 0x3c288b49, 0x35268044, 0x427ce90f, 0x4b72e202, 0x5060ff15, 0x596ef418, 0x6644c53b, 0x6f4ace36, 0x7458d321, 0x7d56d82c, 0xa1377a0c, 0xa8397101, 0xb32b6c16, 0xba25671b, 0x850f5638, 0x8c015d35, 0x97134022, 0x9e1d4b2f, 0xe9472264, 0xe0492969, 0xfb5b347e, 0xf2553f73, 0xcd7f0e50, 0xc471055d, 0xdf63184a, 0xd66d1347, 0x31d7cadc, 0x38d9c1d1, 0x23cbdcc6, 0x2ac5d7cb, 0x15efe6e8, 0x1ce1ede5, 0x7f3f0f2, 0xefdfbff, 0x79a792b4, 0x70a999b9, 0x6bbb84ae, 0x62b58fa3, 0x5d9fbe80, 0x5491b58d, 0x4f83a89a, 0x468da397] + fileprivate var U4: Array = [0x0, 0xe0b0d09, 0x1c161a12, 0x121d171b, 0x382c3424, 0x3627392d, 0x243a2e36, 0x2a31233f, 0x70586848, 0x7e536541, 0x6c4e725a, 0x62457f53, 0x48745c6c, 0x467f5165, 0x5462467e, 0x5a694b77, 0xe0b0d090, 0xeebbdd99, 0xfca6ca82, 0xf2adc78b, 0xd89ce4b4, 0xd697e9bd, 0xc48afea6, 0xca81f3af, 0x90e8b8d8, 0x9ee3b5d1, 0x8cfea2ca, 0x82f5afc3, 0xa8c48cfc, 0xa6cf81f5, 0xb4d296ee, 0xbad99be7, 0xdb7bbb3b, 0xd570b632, 0xc76da129, 0xc966ac20, 0xe3578f1f, 0xed5c8216, 0xff41950d, 0xf14a9804, 0xab23d373, 0xa528de7a, 0xb735c961, 0xb93ec468, 0x930fe757, 0x9d04ea5e, 0x8f19fd45, 0x8112f04c, 0x3bcb6bab, 0x35c066a2, 0x27dd71b9, 0x29d67cb0, 0x3e75f8f, 0xdec5286, 0x1ff1459d, 0x11fa4894, 0x4b9303e3, 0x45980eea, 0x578519f1, 0x598e14f8, 0x73bf37c7, 0x7db43ace, 0x6fa92dd5, 0x61a220dc, 0xadf66d76, 0xa3fd607f, 0xb1e07764, 0xbfeb7a6d, 0x95da5952, 0x9bd1545b, 0x89cc4340, 0x87c74e49, 0xddae053e, 0xd3a50837, 0xc1b81f2c, 0xcfb31225, 0xe582311a, 0xeb893c13, 0xf9942b08, 0xf79f2601, 0x4d46bde6, 0x434db0ef, 0x5150a7f4, 0x5f5baafd, 0x756a89c2, 0x7b6184cb, 0x697c93d0, 0x67779ed9, 0x3d1ed5ae, 0x3315d8a7, 0x2108cfbc, 0x2f03c2b5, 0x532e18a, 0xb39ec83, 0x1924fb98, 0x172ff691, 0x768dd64d, 0x7886db44, 0x6a9bcc5f, 0x6490c156, 0x4ea1e269, 0x40aaef60, 0x52b7f87b, 0x5cbcf572, 0x6d5be05, 0x8deb30c, 0x1ac3a417, 0x14c8a91e, 0x3ef98a21, 0x30f28728, 0x22ef9033, 0x2ce49d3a, 0x963d06dd, 0x98360bd4, 0x8a2b1ccf, 0x842011c6, 0xae1132f9, 0xa01a3ff0, 0xb20728eb, 0xbc0c25e2, 0xe6656e95, 0xe86e639c, 0xfa737487, 0xf478798e, 0xde495ab1, 0xd04257b8, 0xc25f40a3, 0xcc544daa, 0x41f7daec, 0x4ffcd7e5, 0x5de1c0fe, 0x53eacdf7, 0x79dbeec8, 0x77d0e3c1, 0x65cdf4da, 0x6bc6f9d3, 0x31afb2a4, 0x3fa4bfad, 0x2db9a8b6, 0x23b2a5bf, 0x9838680, 0x7888b89, 0x15959c92, 0x1b9e919b, 0xa1470a7c, 0xaf4c0775, 0xbd51106e, 0xb35a1d67, 0x996b3e58, 0x97603351, 0x857d244a, 0x8b762943, 0xd11f6234, 0xdf146f3d, 0xcd097826, 0xc302752f, 0xe9335610, 0xe7385b19, 0xf5254c02, 0xfb2e410b, 0x9a8c61d7, 0x94876cde, 0x869a7bc5, 0x889176cc, 0xa2a055f3, 0xacab58fa, 0xbeb64fe1, 0xb0bd42e8, 0xead4099f, 0xe4df0496, 0xf6c2138d, 0xf8c91e84, 0xd2f83dbb, 0xdcf330b2, 0xceee27a9, 0xc0e52aa0, 0x7a3cb147, 0x7437bc4e, 0x662aab55, 0x6821a65c, 0x42108563, 0x4c1b886a, 0x5e069f71, 0x500d9278, 0xa64d90f, 0x46fd406, 0x1672c31d, 0x1879ce14, 0x3248ed2b, 0x3c43e022, 0x2e5ef739, 0x2055fa30, 0xec01b79a, 0xe20aba93, 0xf017ad88, 0xfe1ca081, 0xd42d83be, 0xda268eb7, 0xc83b99ac, 0xc63094a5, 0x9c59dfd2, 0x9252d2db, 0x804fc5c0, 0x8e44c8c9, 0xa475ebf6, 0xaa7ee6ff, 0xb863f1e4, 0xb668fced, 0xcb1670a, 0x2ba6a03, 0x10a77d18, 0x1eac7011, 0x349d532e, 0x3a965e27, 0x288b493c, 0x26804435, 0x7ce90f42, 0x72e2024b, 0x60ff1550, 0x6ef41859, 0x44c53b66, 0x4ace366f, 0x58d32174, 0x56d82c7d, 0x377a0ca1, 0x397101a8, 0x2b6c16b3, 0x25671bba, 0xf563885, 0x15d358c, 0x13402297, 0x1d4b2f9e, 0x472264e9, 0x492969e0, 0x5b347efb, 0x553f73f2, 0x7f0e50cd, 0x71055dc4, 0x63184adf, 0x6d1347d6, 0xd7cadc31, 0xd9c1d138, 0xcbdcc623, 0xc5d7cb2a, 0xefe6e815, 0xe1ede51c, 0xf3f0f207, 0xfdfbff0e, 0xa792b479, 0xa999b970, 0xbb84ae6b, 0xb58fa362, 0x9fbe805d, 0x91b58d54, 0x83a89a4f, 0x8da39746] + + /// Initialize AES with variant calculated out of key length: + /// - 16 bytes (AES-128) + /// - 24 bytes (AES-192) + /// - 32 bytes (AES-256) + /// + /// - parameter key: Key. Length of the key decides on AES variant. + /// - parameter iv: Initialization Vector (Optional for some blockMode values) + /// - parameter blockMode: Cipher mode of operation + /// - parameter padding: Padding method. PKCS7(), NoPadding(), ZeroPadding(), ... + /// + /// - throws: AES.Error + /// + /// - returns: Instance + public init(key: Array, iv: Array? = nil, blockMode: BlockMode = .CBC, padding: Padding = PKCS7()) throws { + self.key = Key(bytes: key) + self.blockMode = blockMode + self.padding = padding + + if let iv = iv, !iv.isEmpty { + self.iv = iv + } else { + let defaultIV = Array(repeating: 0, count: AES.blockSize) + self.iv = defaultIV + } + + if (blockMode.options.contains(.InitializationVectorRequired) && self.iv.count != AES.blockSize) { + assert(false, "Block size and Initialization Vector must be the same length!") + throw Error.invalidInitializationVector + } + } +} + +// MARK: Private +fileprivate extension AES { + + func encrypt(block: Array) -> Array? { + + if blockMode.options.contains(.PaddingRequired) && block.count != AES.blockSize { + return block + } + + let rounds = self.variant.Nr + let rk = self.expandedKey + var b = block[block.indices].toUInt32Array() + + var t = Array(repeating: 0, count: 4) + + for r in 0 ..< rounds - 1 { + t[0] = b[0] ^ rk[r][0] + t[1] = b[1] ^ rk[r][1] + t[2] = b[2] ^ rk[r][2] + t[3] = b[3] ^ rk[r][3] + + let lb00 = T0[Int(t[0] & 0xFF)] + let lb01 = T1[Int((t[1] >> 8) & 0xFF)] + let lb02 = T2[Int((t[2] >> 16) & 0xFF)] + let lb03 = T3[Int(t[3] >> 24)] + b[0] = lb00 ^ lb01 ^ lb02 ^ lb03 + + let lb10 = T0[Int(t[1] & 0xFF)] + let lb11 = T1[Int((t[2] >> 8) & 0xFF)] + let lb12 = T2[Int((t[3] >> 16) & 0xFF)] + let lb13 = T3[Int(t[0] >> 24)] + b[1] = lb10 ^ lb11 ^ lb12 ^ lb13 + + let lb20 = T0[Int(t[2] & 0xFF)] + let lb21 = T1[Int((t[3] >> 8) & 0xFF)] + let lb22 = T2[Int((t[0] >> 16) & 0xFF)] + let lb23 = T3[Int(t[1] >> 24)] + b[2] = lb20 ^ lb21 ^ lb22 ^ lb23 + + let lb30 = T0[Int(t[3] & 0xFF)] + let lb31 = T1[Int((t[0] >> 8) & 0xFF)] + let lb32 = T2[Int((t[1] >> 16) & 0xFF)] + let lb33 = T3[Int(t[2] >> 24)] + b[3] = lb30 ^ lb31 ^ lb32 ^ lb33 + } + + // last round + let r = rounds - 1 + + t[0] = b[0] ^ rk[r][0] + t[1] = b[1] ^ rk[r][1] + t[2] = b[2] ^ rk[r][2] + t[3] = b[3] ^ rk[r][3] + + // rounds + b[0] = F1(t[0], t[1], t[2], t[3]) ^ rk[rounds][0] + b[1] = F1(t[1], t[2], t[3], t[0]) ^ rk[rounds][1] + b[2] = F1(t[2], t[3], t[0], t[1]) ^ rk[rounds][2] + b[3] = F1(t[3], t[0], t[1], t[2]) ^ rk[rounds][3] + + var out = Array() + out.reserveCapacity(b.count * 4) + for num in b { + out.append(UInt8(num & 0xFF)) + out.append(UInt8((num >> 8) & 0xFF)) + out.append(UInt8((num >> 16) & 0xFF)) + out.append(UInt8((num >> 24) & 0xFF)) + } + + return out + } + + func decrypt(block: Array) -> Array? { + + if blockMode.options.contains(.PaddingRequired) && block.count != AES.blockSize { + return block + } + + let rounds = self.variant.Nr + let rk = self.expandedKeyInv + var b = block[block.indices].toUInt32Array() + + var t = Array(repeating: 0, count: 4) + + for r in (2 ... rounds).reversed() { + t[0] = b[0] ^ rk[r][0] + t[1] = b[1] ^ rk[r][1] + t[2] = b[2] ^ rk[r][2] + t[3] = b[3] ^ rk[r][3] + + let b00 = T0_INV[Int(t[0] & 0xFF)] + let b01 = T1_INV[Int((t[3] >> 8) & 0xFF)] + let b02 = T2_INV[Int((t[2] >> 16) & 0xFF)] + let b03 = T3_INV[Int(t[1] >> 24)] + b[0] = b00 ^ b01 ^ b02 ^ b03 + + let b10 = T0_INV[Int(t[1] & 0xFF)] + let b11 = T1_INV[Int((t[0] >> 8) & 0xFF)] + let b12 = T2_INV[Int((t[3] >> 16) & 0xFF)] + let b13 = T3_INV[Int(t[2] >> 24)] + b[1] = b10 ^ b11 ^ b12 ^ b13 + + let b20 = T0_INV[Int(t[2] & 0xFF)] + let b21 = T1_INV[Int((t[1] >> 8) & 0xFF)] + let b22 = T2_INV[Int((t[0] >> 16) & 0xFF)] + let b23 = T3_INV[Int(t[3] >> 24)] + b[2] = b20 ^ b21 ^ b22 ^ b23 + + let b30 = T0_INV[Int(t[3] & 0xFF)] + let b31 = T1_INV[Int((t[2] >> 8) & 0xFF)] + let b32 = T2_INV[Int((t[1] >> 16) & 0xFF)] + let b33 = T3_INV[Int(t[0] >> 24)] + b[3] = b30 ^ b31 ^ b32 ^ b33 + } + + // last round + t[0] = b[0] ^ rk[1][0] + t[1] = b[1] ^ rk[1][1] + t[2] = b[2] ^ rk[1][2] + t[3] = b[3] ^ rk[1][3] + + // rounds + + let lb00 = sBoxInv[Int(B0(t[0]))] + let lb01 = (sBoxInv[Int(B1(t[3]))] << 8) + let lb02 = (sBoxInv[Int(B2(t[2]))] << 16) + let lb03 = (sBoxInv[Int(B3(t[1]))] << 24) + b[0] = lb00 | lb01 | lb02 | lb03 ^ rk[0][0] + + let lb10 = sBoxInv[Int(B0(t[1]))] + let lb11 = (sBoxInv[Int(B1(t[0]))] << 8) + let lb12 = (sBoxInv[Int(B2(t[3]))] << 16) + let lb13 = (sBoxInv[Int(B3(t[2]))] << 24) + b[1] = lb10 | lb11 | lb12 | lb13 ^ rk[0][1] + + let lb20 = sBoxInv[Int(B0(t[2]))] + let lb21 = (sBoxInv[Int(B1(t[1]))] << 8) + let lb22 = (sBoxInv[Int(B2(t[0]))] << 16) + let lb23 = (sBoxInv[Int(B3(t[3]))] << 24) + b[2] = lb20 | lb21 | lb22 | lb23 ^ rk[0][2] + + let lb30 = sBoxInv[Int(B0(t[3]))] + let lb31 = (sBoxInv[Int(B1(t[2]))] << 8) + let lb32 = (sBoxInv[Int(B2(t[1]))] << 16) + let lb33 = (sBoxInv[Int(B3(t[0]))] << 24) + b[3] = lb30 | lb31 | lb32 | lb33 ^ rk[0][3] + + var out = Array() + out.reserveCapacity(b.count * 4) + for num in b { + out.append(UInt8(num & 0xFF)) + out.append(UInt8((num >> 8) & 0xFF)) + out.append(UInt8((num >> 16) & 0xFF)) + out.append(UInt8((num >> 24) & 0xFF)) + } + + return out + } + + func expandKeyInv(_ key: Key, variant: Variant) -> Array> { + let rounds = variant.Nr + var rk2: Array> = expandKey(key, variant: variant) + + for r in 1 ..< rounds { + var w: UInt32 + + w = rk2[r][0] + rk2[r][0] = U1[Int(B0(w))] ^ U2[Int(B1(w))] ^ U3[Int(B2(w))] ^ U4[Int(B3(w))] + + w = rk2[r][1] + rk2[r][1] = U1[Int(B0(w))] ^ U2[Int(B1(w))] ^ U3[Int(B2(w))] ^ U4[Int(B3(w))] + + w = rk2[r][2] + rk2[r][2] = U1[Int(B0(w))] ^ U2[Int(B1(w))] ^ U3[Int(B2(w))] ^ U4[Int(B3(w))] + + w = rk2[r][3] + rk2[r][3] = U1[Int(B0(w))] ^ U2[Int(B1(w))] ^ U3[Int(B2(w))] ^ U4[Int(B3(w))] + } + + return rk2 + } + + func expandKey(_ key: Key, variant: Variant) -> Array> { + + func convertExpandedKey(_ expanded: Array) -> Array> { + var arr = Array() + for idx in stride(from: expanded.startIndex, to: expanded.endIndex, by: 4) { + let four = Array(expanded[idx ..< idx.advanced(by: 4)].reversed()) + let num = UInt32(bytes: four) + arr.append(num) + } + + var allarr = Array>() + for idx in stride(from: arr.startIndex, to: arr.endIndex, by: 4) { + allarr.append(Array(arr[idx ..< idx.advanced(by: 4)])) + } + return allarr + } + + /* + * Function used in the Key Expansion routine that takes a four-byte + * input word and applies an S-box to each of the four bytes to + * produce an output word. + */ + func subWord(_ word: Array) -> Array { + var result = word + for i in 0 ..< 4 { + result[i] = UInt8(sBox[Int(word[i])]) + } + return result + } + + var w = Array(repeating: 0, count: variant.Nb * (variant.Nr + 1) * 4) + for i in 0 ..< variant.Nk { + for wordIdx in 0 ..< 4 { + w[(4 * i) + wordIdx] = key[(4 * i) + wordIdx] + } + } + + var tmp: Array + + for i in variant.Nk ..< variant.Nb * (variant.Nr + 1) { + tmp = Array(repeating: 0, count: 4) + + for wordIdx in 0 ..< 4 { + tmp[wordIdx] = w[4 * (i - 1) + wordIdx] + } + if ((i % variant.Nk) == 0) { + tmp = subWord(rotateLeft(UInt32(bytes: tmp), by: 8).bytes(totalBytes: MemoryLayout.size)) + tmp[0] = tmp.first! ^ Rcon[i / variant.Nk] + } else if (variant.Nk > 6 && (i % variant.Nk) == 4) { + tmp = subWord(tmp) + } + + // xor array of bytes + for wordIdx in 0 ..< 4 { + w[4 * i + wordIdx] = w[4 * (i - variant.Nk) + wordIdx] ^ tmp[wordIdx] + } + } + return convertExpandedKey(w) + } + + func B0(_ x: UInt32) -> UInt32 { + return x & 0xFF + } + + func B1(_ x: UInt32) -> UInt32 { + return (x >> 8) & 0xFF + } + + func B2(_ x: UInt32) -> UInt32 { + return (x >> 16) & 0xFF + } + + func B3(_ x: UInt32) -> UInt32 { + return (x >> 24) & 0xFF + } + + func F1(_ x0: UInt32, _ x1: UInt32, _ x2: UInt32, _ x3: UInt32) -> UInt32 { + var result: UInt32 = 0 + result |= UInt32(B1(T0[Int(x0 & 255)])) + result |= UInt32(B1(T0[Int((x1 >> 8) & 255)])) << 8 + result |= UInt32(B1(T0[Int((x2 >> 16) & 255)])) << 16 + result |= UInt32(B1(T0[Int(x3 >> 24)])) << 24 + return result + } + + func calculateSBox() -> (sBox: Array, invSBox: Array) { + var sbox = Array(repeating: 0, count: 256) + var invsbox = sbox + sbox[0] = 0x63 + + var p: UInt8 = 1, q: UInt8 = 1 + + repeat { + p = p ^ (UInt8(truncatingBitPattern: Int(p) << 1) ^ ((p & 0x80) == 0x80 ? 0x1B : 0)) + q ^= q << 1 + q ^= q << 2 + q ^= q << 4 + q ^= (q & 0x80) == 0x80 ? 0x09 : 0 + + let s = 0x63 ^ q ^ rotateLeft(q, by: 1) ^ rotateLeft(q, by: 2) ^ rotateLeft(q, by: 3) ^ rotateLeft(q, by: 4) + + sbox[Int(p)] = UInt32(s) + invsbox[Int(s)] = UInt32(p) + } while (p != 1) + + return (sBox: sbox, invSBox: invsbox) + } +} + +// MARK: Encryptor +extension AES { + + public struct Encryptor: Updatable { + private var worker: BlockModeWorker + private let padding: Padding + private var accumulated = Array() + private var processedBytesTotalCount: Int = 0 + private let paddingRequired: Bool + + init(aes: AES) { + self.padding = aes.padding + self.worker = aes.blockMode.worker(aes.iv, cipherOperation: aes.encrypt) + self.paddingRequired = aes.blockMode.options.contains(.PaddingRequired) + } + + mutating public func update(withBytes bytes: T, isLast: Bool = false) throws -> Array where T.Iterator.Element == UInt8 { + self.accumulated += bytes + + if isLast { + self.accumulated = padding.add(to: self.accumulated, blockSize: AES.blockSize) + } + + var processedBytes = 0 + var encrypted = Array() + encrypted.reserveCapacity(self.accumulated.count) + for chunk in self.accumulated.chunks(size: AES.blockSize) { + if (isLast || (self.accumulated.count - processedBytes) >= AES.blockSize) { + encrypted += worker.encrypt(chunk) + processedBytes += chunk.count + } + } + self.accumulated.removeFirst(processedBytes) + self.processedBytesTotalCount += processedBytes + return encrypted + } + } +} + +// MARK: Decryptor +extension AES { + + public struct Decryptor: RandomAccessCryptor { + private var worker: BlockModeWorker + private let padding: Padding + private var accumulated = Array() + private var processedBytesTotalCount: Int = 0 + private let paddingRequired: Bool + + private var offset: Int = 0 + private var offsetToRemove: Int = 0 + + init(aes: AES) { + self.padding = aes.padding + + switch (aes.blockMode) { + case .CFB, .OFB, .CTR: + // CFB, OFB, CTR uses encryptBlock to decrypt + self.worker = aes.blockMode.worker(aes.iv, cipherOperation: aes.encrypt) + default: + self.worker = aes.blockMode.worker(aes.iv, cipherOperation: aes.decrypt) + } + + self.paddingRequired = aes.blockMode.options.contains(.PaddingRequired) + } + + mutating public func update(withBytes bytes: T, isLast: Bool = false) throws -> Array where T.Iterator.Element == UInt8 { + // prepend "offset" number of bytes at the begining + if self.offset > 0 { + self.accumulated += Array(repeating: 0, count: offset) + bytes + self.offsetToRemove = offset + self.offset = 0 + } else { + self.accumulated += bytes + } + + var processedBytes = 0 + var plaintext = Array() + plaintext.reserveCapacity(self.accumulated.count) + for chunk in self.accumulated.chunks(size: AES.blockSize) { + if (isLast || (self.accumulated.count - processedBytes) >= AES.blockSize) { + plaintext += self.worker.decrypt(chunk) + + // remove "offset" from the beginning of first chunk + if self.offsetToRemove > 0 { + plaintext.removeFirst(self.offsetToRemove) + self.offsetToRemove = 0 + } + + processedBytes += chunk.count + } + } + self.accumulated.removeFirst(processedBytes) + self.processedBytesTotalCount += processedBytes + + if isLast { + plaintext = padding.remove(from: plaintext, blockSize: AES.blockSize) + } + + return plaintext + } + + @discardableResult mutating public func seek(to position: Int) -> Bool { + guard var worker = self.worker as? RandomAccessBlockModeWorker else { + return false + } + + worker.counter = UInt(position / AES.blockSize) + self.worker = worker + + self.offset = position % AES.blockSize + + self.accumulated = [] + + return true + } + } +} + +// MARK: Cryptors +extension AES: Cryptors { + + public func makeEncryptor() -> AES.Encryptor { + return Encryptor(aes: self) + } + + public func makeDecryptor() -> AES.Decryptor { + return Decryptor(aes: self) + } +} + +// MARK: Cipher +extension AES: Cipher { + + public func encrypt(_ bytes: C) throws -> Array where C.Iterator.Element == UInt8, C.IndexDistance == Int, C.Index == Int { + let chunks = Array(bytes).chunks(size: AES.blockSize) + + var oneTimeCryptor = self.makeEncryptor() + var out = Array() + out.reserveCapacity(bytes.count) + for idx in chunks.indices { + out += try oneTimeCryptor.update(withBytes: chunks[idx], isLast: idx == chunks.endIndex.advanced(by: -1)) + } + + if blockMode.options.contains(.PaddingRequired) && (out.count % AES.blockSize != 0) { + throw Error.dataPaddingRequired + } + + return out + } + + public func decrypt(_ bytes: C) throws -> Array where C.Iterator.Element == UInt8, C.IndexDistance == Int, C.Index == Int { + if blockMode.options.contains(.PaddingRequired) && (bytes.count % AES.blockSize != 0) { + throw Error.dataPaddingRequired + } + + var oneTimeCryptor = self.makeDecryptor() + let chunks = Array(bytes).chunks(size: AES.blockSize) + var out = Array() + out.reserveCapacity(bytes.count) + for idx in chunks.indices { + out += try oneTimeCryptor.update(withBytes: chunks[idx], isLast: idx == chunks.endIndex.advanced(by: -1)) + } + return out + } +} diff --git a/GeneralUtils/GeneralUtils/libs/CryptoSwift/Array+Extension.swift b/GeneralUtils/GeneralUtils/libs/CryptoSwift/Array+Extension.swift new file mode 100644 index 0000000..6ebc818 --- /dev/null +++ b/GeneralUtils/GeneralUtils/libs/CryptoSwift/Array+Extension.swift @@ -0,0 +1,47 @@ +// +// ArrayExtension.swift +// CryptoSwift +// +// Created by Marcin Krzyzanowski on 10/08/14. +// Copyright (c) 2014 Marcin Krzyzanowski. All rights reserved. +// + +extension Array { + init(reserveCapacity: Int) { + self = Array() + self.reserveCapacity(reserveCapacity) + } +} + +extension Array { + + /** split in chunks with given chunk size */ + func chunks(size chunksize: Int) -> Array> { + var words = Array>() + words.reserveCapacity(self.count / chunksize) + for idx in stride(from: chunksize, through: self.count, by: chunksize) { + words.append(Array(self[idx - chunksize ..< idx])) // slow for large table + } + let reminder = self.suffix(self.count % chunksize) + if !reminder.isEmpty { + words.append(Array(reminder)) + } + return words + } +} + +extension Array where Element: Integer, Element.IntegerLiteralType == UInt8 { + + public init(hex: String) { + self.init() + + let utf8 = Array(hex.utf8) + let skip0x = hex.hasPrefix("0x") ? 2 : 0 + for idx in stride(from: utf8.startIndex.advanced(by: skip0x), to: utf8.endIndex, by: utf8.startIndex.advanced(by: 2)) { + let byteHex = "\(UnicodeScalar(utf8[idx]))\(UnicodeScalar(utf8[idx.advanced(by: 1)]))" + if let byte = UInt8(byteHex, radix: 16) { + self.append(byte as! Element) + } + } + } +} diff --git a/GeneralUtils/GeneralUtils/libs/CryptoSwift/Authenticator.swift b/GeneralUtils/GeneralUtils/libs/CryptoSwift/Authenticator.swift new file mode 100644 index 0000000..910c7ea --- /dev/null +++ b/GeneralUtils/GeneralUtils/libs/CryptoSwift/Authenticator.swift @@ -0,0 +1,13 @@ +// +// MAC.swift +// CryptoSwift +// +// Created by Marcin Krzyzanowski on 03/09/14. +// Copyright (c) 2014 Marcin Krzyzanowski. All rights reserved. +// + +/// Message authentication code. +public protocol Authenticator { + /// Calculate Message Authentication Code (MAC) for message. + func authenticate(_ bytes: Array) throws -> Array +} diff --git a/GeneralUtils/GeneralUtils/libs/CryptoSwift/Bit.swift b/GeneralUtils/GeneralUtils/libs/CryptoSwift/Bit.swift new file mode 100644 index 0000000..5f466f2 --- /dev/null +++ b/GeneralUtils/GeneralUtils/libs/CryptoSwift/Bit.swift @@ -0,0 +1,19 @@ +// +// Bit.swift +// CryptoSwift +// +// Created by Pedro Silva on 29/03/16. +// Copyright © 2016 Marcin Krzyzanowski. All rights reserved. +// + +enum Bit: Int { + case zero + case one +} + +extension Bit { + + func inverted() -> Bit { + return self == .zero ? .one : .zero + } +} diff --git a/GeneralUtils/GeneralUtils/libs/CryptoSwift/BlockCipher.swift b/GeneralUtils/GeneralUtils/libs/CryptoSwift/BlockCipher.swift new file mode 100644 index 0000000..a8c1697 --- /dev/null +++ b/GeneralUtils/GeneralUtils/libs/CryptoSwift/BlockCipher.swift @@ -0,0 +1,11 @@ +// +// BlockCipher.swift +// CryptoSwift +// +// Created by Marcin Krzyzanowski on 15/04/16. +// Copyright © 2016 Marcin Krzyzanowski. All rights reserved. +// + +protocol BlockCipher: class { + static var blockSize: Int { get } +} diff --git a/GeneralUtils/GeneralUtils/libs/CryptoSwift/BlockMode/BlockMode.swift b/GeneralUtils/GeneralUtils/libs/CryptoSwift/BlockMode/BlockMode.swift new file mode 100644 index 0000000..3d4e7c8 --- /dev/null +++ b/GeneralUtils/GeneralUtils/libs/CryptoSwift/BlockMode/BlockMode.swift @@ -0,0 +1,47 @@ +// +// BlockMode.swift +// CryptoSwift +// +// Created by Marcin Krzyzanowski on 08/03/16. +// Copyright © 2016 Marcin Krzyzanowski. All rights reserved. +// + +typealias CipherOperationOnBlock = (_ block: Array) -> Array? + +public enum BlockMode { + case ECB, CBC, PCBC, CFB, OFB, CTR + + func worker(_ iv: Array?, cipherOperation: @escaping CipherOperationOnBlock) -> BlockModeWorker { + switch (self) { + case .ECB: + return ECBModeWorker(iv: iv ?? [], cipherOperation: cipherOperation) + case .CBC: + return CBCModeWorker(iv: iv ?? [], cipherOperation: cipherOperation) + case .PCBC: + return PCBCModeWorker(iv: iv ?? [], cipherOperation: cipherOperation) + case .CFB: + return CFBModeWorker(iv: iv ?? [], cipherOperation: cipherOperation) + case .OFB: + return OFBModeWorker(iv: iv ?? [], cipherOperation: cipherOperation) + case .CTR: + return CTRModeWorker(iv: iv ?? [], cipherOperation: cipherOperation) + } + } + + var options: BlockModeOptions { + switch (self) { + case .ECB: + return .PaddingRequired + case .CBC: + return [.InitializationVectorRequired, .PaddingRequired] + case .CFB: + return .InitializationVectorRequired + case .CTR: + return .InitializationVectorRequired + case .OFB: + return .InitializationVectorRequired + case .PCBC: + return [.InitializationVectorRequired, .PaddingRequired] + } + } +} diff --git a/GeneralUtils/GeneralUtils/libs/CryptoSwift/BlockMode/BlockModeOptions.swift b/GeneralUtils/GeneralUtils/libs/CryptoSwift/BlockMode/BlockModeOptions.swift new file mode 100644 index 0000000..58fb977 --- /dev/null +++ b/GeneralUtils/GeneralUtils/libs/CryptoSwift/BlockMode/BlockModeOptions.swift @@ -0,0 +1,15 @@ +// +// BlockModeOptions.swift +// CryptoSwift +// +// Created by Marcin Krzyzanowski on 08/03/16. +// Copyright © 2016 Marcin Krzyzanowski. All rights reserved. +// + +struct BlockModeOptions: OptionSet { + let rawValue: Int + + static let None = BlockModeOptions(rawValue: 0) + static let InitializationVectorRequired = BlockModeOptions(rawValue: 1) + static let PaddingRequired = BlockModeOptions(rawValue: 2) +} diff --git a/GeneralUtils/GeneralUtils/libs/CryptoSwift/BlockMode/BlockModeWorker.swift b/GeneralUtils/GeneralUtils/libs/CryptoSwift/BlockMode/BlockModeWorker.swift new file mode 100644 index 0000000..bcfc797 --- /dev/null +++ b/GeneralUtils/GeneralUtils/libs/CryptoSwift/BlockMode/BlockModeWorker.swift @@ -0,0 +1,13 @@ +// +// BlockModeWorker.swift +// CryptoSwift +// +// Created by Marcin Krzyzanowski on 06/05/16. +// Copyright © 2016 Marcin Krzyzanowski. All rights reserved. +// + +protocol BlockModeWorker { + var cipherOperation: CipherOperationOnBlock { get } + mutating func encrypt(_ plaintext: Array) -> Array + mutating func decrypt(_ ciphertext: Array) -> Array +} diff --git a/GeneralUtils/GeneralUtils/libs/CryptoSwift/BlockMode/CBC.swift b/GeneralUtils/GeneralUtils/libs/CryptoSwift/BlockMode/CBC.swift new file mode 100644 index 0000000..9a4435b --- /dev/null +++ b/GeneralUtils/GeneralUtils/libs/CryptoSwift/BlockMode/CBC.swift @@ -0,0 +1,39 @@ +// +// CBC.swift +// CryptoSwift +// +// Created by Marcin Krzyzanowski on 08/03/16. +// Copyright © 2016 Marcin Krzyzanowski. All rights reserved. +// +// Cipher-block chaining (CBC) +// + +struct CBCModeWorker: BlockModeWorker { + typealias Element = Array + + let cipherOperation: CipherOperationOnBlock + private let iv: Element + private var prev: Element? + + init(iv: Array, cipherOperation: @escaping CipherOperationOnBlock) { + self.iv = iv + self.cipherOperation = cipherOperation + } + + mutating func encrypt(_ plaintext: Array) -> Array { + guard let ciphertext = cipherOperation(xor(prev ?? iv, plaintext)) else { + return plaintext + } + prev = ciphertext + return ciphertext + } + + mutating func decrypt(_ ciphertext: Array) -> Array { + guard let plaintext = cipherOperation(ciphertext) else { + return ciphertext + } + let result = xor(prev ?? iv, plaintext) + self.prev = ciphertext + return result + } +} diff --git a/GeneralUtils/GeneralUtils/libs/CryptoSwift/BlockMode/CFB.swift b/GeneralUtils/GeneralUtils/libs/CryptoSwift/BlockMode/CFB.swift new file mode 100644 index 0000000..82cbb09 --- /dev/null +++ b/GeneralUtils/GeneralUtils/libs/CryptoSwift/BlockMode/CFB.swift @@ -0,0 +1,39 @@ +// +// CFB.swift +// CryptoSwift +// +// Created by Marcin Krzyzanowski on 08/03/16. +// Copyright © 2016 Marcin Krzyzanowski. All rights reserved. +// +// Cipher feedback (CFB) +// + +struct CFBModeWorker: BlockModeWorker { + typealias Element = Array + + let cipherOperation: CipherOperationOnBlock + private let iv: Element + private var prev: Element? + + init(iv: Array, cipherOperation: @escaping CipherOperationOnBlock) { + self.iv = iv + self.cipherOperation = cipherOperation + } + + mutating func encrypt(_ plaintext: Array) -> Array { + guard let ciphertext = cipherOperation(prev ?? iv) else { + return plaintext + } + prev = xor(plaintext, ciphertext) + return prev ?? [] + } + + mutating func decrypt(_ ciphertext: Array) -> Array { + guard let plaintext = cipherOperation(prev ?? iv) else { + return ciphertext + } + let result = xor(plaintext, ciphertext) + self.prev = ciphertext + return result + } +} diff --git a/GeneralUtils/GeneralUtils/libs/CryptoSwift/BlockMode/CTR.swift b/GeneralUtils/GeneralUtils/libs/CryptoSwift/BlockMode/CTR.swift new file mode 100644 index 0000000..9e4c676 --- /dev/null +++ b/GeneralUtils/GeneralUtils/libs/CryptoSwift/BlockMode/CTR.swift @@ -0,0 +1,45 @@ +// +// CTR.swift +// CryptoSwift +// +// Created by Marcin Krzyzanowski on 08/03/16. +// Copyright © 2016 Marcin Krzyzanowski. All rights reserved. +// +// Counter (CTR) +// + +struct CTRModeWorker: RandomAccessBlockModeWorker { + typealias Element = Array + + let cipherOperation: CipherOperationOnBlock + private let iv: Element + var counter: UInt = 0 + + init(iv: Array, cipherOperation: @escaping CipherOperationOnBlock) { + self.iv = iv + self.cipherOperation = cipherOperation + } + + mutating func encrypt(_ plaintext: Array) -> Array { + let nonce = buildNonce(iv, counter: UInt64(counter)) + counter = counter + 1 + + guard let ciphertext = cipherOperation(nonce) else { + return plaintext + } + + return xor(plaintext, ciphertext) + } + + mutating func decrypt(_ ciphertext: Array) -> Array { + return encrypt(ciphertext) + } +} + +private func buildNonce(_ iv: Array, counter: UInt64) -> Array { + let noncePartLen = AES.blockSize / 2 + let noncePrefix = Array(iv[0 ..< noncePartLen]) + let nonceSuffix = Array(iv[noncePartLen ..< iv.count]) + let c = UInt64(bytes: nonceSuffix) + counter + return noncePrefix + c.bytes() +} diff --git a/GeneralUtils/GeneralUtils/libs/CryptoSwift/BlockMode/ECB.swift b/GeneralUtils/GeneralUtils/libs/CryptoSwift/BlockMode/ECB.swift new file mode 100644 index 0000000..cfbce31 --- /dev/null +++ b/GeneralUtils/GeneralUtils/libs/CryptoSwift/BlockMode/ECB.swift @@ -0,0 +1,29 @@ +// +// BlockMode.swift +// CryptoSwift +// +// Created by Marcin Krzyzanowski on 27/12/14. +// Copyright (c) 2014 Marcin Krzyzanowski. All rights reserved. +// +// Electronic codebook (ECB) +// + +struct ECBModeWorker: BlockModeWorker { + typealias Element = Array + let cipherOperation: CipherOperationOnBlock + + init(iv: Array, cipherOperation: @escaping CipherOperationOnBlock) { + self.cipherOperation = cipherOperation + } + + mutating func encrypt(_ plaintext: Array) -> Array { + guard let ciphertext = cipherOperation(plaintext) else { + return plaintext + } + return ciphertext + } + + mutating func decrypt(_ ciphertext: Array) -> Array { + return encrypt(ciphertext) + } +} diff --git a/GeneralUtils/GeneralUtils/libs/CryptoSwift/BlockMode/OFB.swift b/GeneralUtils/GeneralUtils/libs/CryptoSwift/BlockMode/OFB.swift new file mode 100644 index 0000000..93d521e --- /dev/null +++ b/GeneralUtils/GeneralUtils/libs/CryptoSwift/BlockMode/OFB.swift @@ -0,0 +1,39 @@ +// +// OFB.swift +// CryptoSwift +// +// Created by Marcin Krzyzanowski on 08/03/16. +// Copyright © 2016 Marcin Krzyzanowski. All rights reserved. +// +// Output Feedback (OFB) +// + +struct OFBModeWorker: BlockModeWorker { + typealias Element = Array + + let cipherOperation: CipherOperationOnBlock + private let iv: Element + private var prev: Element? + + init(iv: Array, cipherOperation: @escaping CipherOperationOnBlock) { + self.iv = iv + self.cipherOperation = cipherOperation + } + + mutating func encrypt(_ plaintext: Array) -> Array { + guard let ciphertext = cipherOperation(prev ?? iv) else { + return plaintext + } + prev = ciphertext + return xor(plaintext, ciphertext) + } + + mutating func decrypt(_ ciphertext: Array) -> Array { + guard let decrypted = cipherOperation(prev ?? iv) else { + return ciphertext + } + let plaintext = xor(decrypted, ciphertext) + self.prev = decrypted + return plaintext + } +} diff --git a/GeneralUtils/GeneralUtils/libs/CryptoSwift/BlockMode/PCBC.swift b/GeneralUtils/GeneralUtils/libs/CryptoSwift/BlockMode/PCBC.swift new file mode 100644 index 0000000..0c97be8 --- /dev/null +++ b/GeneralUtils/GeneralUtils/libs/CryptoSwift/BlockMode/PCBC.swift @@ -0,0 +1,39 @@ +// +// PCBM.swift +// CryptoSwift +// +// Created by Marcin Krzyzanowski on 08/03/16. +// Copyright © 2016 Marcin Krzyzanowski. All rights reserved. +// +// Propagating Cipher Block Chaining (PCBC) +// + +struct PCBCModeWorker: BlockModeWorker { + typealias Element = Array + + let cipherOperation: CipherOperationOnBlock + private let iv: Element + private var prev: Element? + + init(iv: Array, cipherOperation: @escaping CipherOperationOnBlock) { + self.iv = iv + self.cipherOperation = cipherOperation + } + + mutating func encrypt(_ plaintext: Array) -> Array { + guard let ciphertext = cipherOperation(xor(prev ?? iv, plaintext)) else { + return plaintext + } + prev = xor(plaintext, ciphertext) + return ciphertext + } + + mutating func decrypt(_ ciphertext: Array) -> Array { + guard let plaintext = cipherOperation(ciphertext) else { + return ciphertext + } + let result = xor(prev ?? iv, plaintext) + self.prev = xor(plaintext, ciphertext) + return result + } +} diff --git a/GeneralUtils/GeneralUtils/libs/CryptoSwift/BlockMode/RandomAccessBlockModeWorker.swift b/GeneralUtils/GeneralUtils/libs/CryptoSwift/BlockMode/RandomAccessBlockModeWorker.swift new file mode 100644 index 0000000..775c63d --- /dev/null +++ b/GeneralUtils/GeneralUtils/libs/CryptoSwift/BlockMode/RandomAccessBlockModeWorker.swift @@ -0,0 +1,11 @@ +// +// RandomAccessBlockModeWorker.swift +// CryptoSwift +// +// Created by Marcin Krzyzanowski on 29/07/16. +// Copyright © 2016 Marcin Krzyzanowski. All rights reserved. +// + +protocol RandomAccessBlockModeWorker: BlockModeWorker { + var counter: UInt { set get } +} diff --git a/GeneralUtils/GeneralUtils/libs/CryptoSwift/Blowfish.swift b/GeneralUtils/GeneralUtils/libs/CryptoSwift/Blowfish.swift new file mode 100644 index 0000000..96b5a75 --- /dev/null +++ b/GeneralUtils/GeneralUtils/libs/CryptoSwift/Blowfish.swift @@ -0,0 +1,506 @@ +// +// Blowfish.swift +// CryptoSwift +// +// Created by Marcin Krzyzanowski on 26/10/16. +// Copyright © 2016 Marcin Krzyzanowski. All rights reserved. +// +// https://en.wikipedia.org/wiki/Blowfish_(cipher) +// Based on Paul Kocher implementation +// + +public final class Blowfish { + + public enum Error: Swift.Error { + /// Data padding is required + case dataPaddingRequired + /// Invalid key or IV + case invalidKeyOrInitializationVector + /// Invalid IV + case invalidInitializationVector + } + + public static let blockSize: Int = 8 // 64 bit + fileprivate let iv: Array + fileprivate let blockMode: BlockMode + fileprivate let padding: Padding + fileprivate lazy var decryptWorker: BlockModeWorker = { + return self.blockMode.worker(self.iv, cipherOperation: self.decrypt) + }() + fileprivate lazy var encryptWorker: BlockModeWorker = { + return self.blockMode.worker(self.iv, cipherOperation: self.encrypt) + }() + + private let N = 16 // rounds + private var P: Array + private var S: Array> + private let origP: Array = [0x243f6a88, 0x85a308d3, 0x13198a2e, 0x03707344, 0xa4093822, + 0x299f31d0, 0x082efa98, 0xec4e6c89, 0x452821e6, 0x38d01377, + 0xbe5466cf, 0x34e90c6c, 0xc0ac29b7, 0xc97c50dd, 0x3f84d5b5, + 0xb5470917, 0x9216d5d9, 0x8979fb1b] + + private let origS: Array> = [ + [0xD1310BA6, 0x98DFB5AC, 0x2FFD72DB, 0xD01ADFB7, + 0xB8E1AFED, 0x6A267E96, 0xBA7C9045, 0xF12C7F99, + 0x24A19947, 0xB3916CF7, 0x0801F2E2, 0x858EFC16, + 0x636920D8, 0x71574E69, 0xA458FEA3, 0xF4933D7E, + 0x0D95748F, 0x728EB658, 0x718BCD58, 0x82154AEE, + 0x7B54A41D, 0xC25A59B5, 0x9C30D539, 0x2AF26013, + 0xC5D1B023, 0x286085F0, 0xCA417918, 0xB8DB38EF, + 0x8E79DCB0, 0x603A180E, 0x6C9E0E8B, 0xB01E8A3E, + 0xD71577C1, 0xBD314B27, 0x78AF2FDA, 0x55605C60, + 0xE65525F3, 0xAA55AB94, 0x57489862, 0x63E81440, + 0x55CA396A, 0x2AAB10B6, 0xB4CC5C34, 0x1141E8CE, + 0xA15486AF, 0x7C72E993, 0xB3EE1411, 0x636FBC2A, + 0x2BA9C55D, 0x741831F6, 0xCE5C3E16, 0x9B87931E, + 0xAFD6BA33, 0x6C24CF5C, 0x7A325381, 0x28958677, + 0x3B8F4898, 0x6B4BB9AF, 0xC4BFE81B, 0x66282193, + 0x61D809CC, 0xFB21A991, 0x487CAC60, 0x5DEC8032, + 0xEF845D5D, 0xE98575B1, 0xDC262302, 0xEB651B88, + 0x23893E81, 0xD396ACC5, 0x0F6D6FF3, 0x83F44239, + 0x2E0B4482, 0xA4842004, 0x69C8F04A, 0x9E1F9B5E, + 0x21C66842, 0xF6E96C9A, 0x670C9C61, 0xABD388F0, + 0x6A51A0D2, 0xD8542F68, 0x960FA728, 0xAB5133A3, + 0x6EEF0B6C, 0x137A3BE4, 0xBA3BF050, 0x7EFB2A98, + 0xA1F1651D, 0x39AF0176, 0x66CA593E, 0x82430E88, + 0x8CEE8619, 0x456F9FB4, 0x7D84A5C3, 0x3B8B5EBE, + 0xE06F75D8, 0x85C12073, 0x401A449F, 0x56C16AA6, + 0x4ED3AA62, 0x363F7706, 0x1BFEDF72, 0x429B023D, + 0x37D0D724, 0xD00A1248, 0xDB0FEAD3, 0x49F1C09B, + 0x075372C9, 0x80991B7B, 0x25D479D8, 0xF6E8DEF7, + 0xE3FE501A, 0xB6794C3B, 0x976CE0BD, 0x04C006BA, + 0xC1A94FB6, 0x409F60C4, 0x5E5C9EC2, 0x196A2463, + 0x68FB6FAF, 0x3E6C53B5, 0x1339B2EB, 0x3B52EC6F, + 0x6DFC511F, 0x9B30952C, 0xCC814544, 0xAF5EBD09, + 0xBEE3D004, 0xDE334AFD, 0x660F2807, 0x192E4BB3, + 0xC0CBA857, 0x45C8740F, 0xD20B5F39, 0xB9D3FBDB, + 0x5579C0BD, 0x1A60320A, 0xD6A100C6, 0x402C7279, + 0x679F25FE, 0xFB1FA3CC, 0x8EA5E9F8, 0xDB3222F8, + 0x3C7516DF, 0xFD616B15, 0x2F501EC8, 0xAD0552AB, + 0x323DB5FA, 0xFD238760, 0x53317B48, 0x3E00DF82, + 0x9E5C57BB, 0xCA6F8CA0, 0x1A87562E, 0xDF1769DB, + 0xD542A8F6, 0x287EFFC3, 0xAC6732C6, 0x8C4F5573, + 0x695B27B0, 0xBBCA58C8, 0xE1FFA35D, 0xB8F011A0, + 0x10FA3D98, 0xFD2183B8, 0x4AFCB56C, 0x2DD1D35B, + 0x9A53E479, 0xB6F84565, 0xD28E49BC, 0x4BFB9790, + 0xE1DDF2DA, 0xA4CB7E33, 0x62FB1341, 0xCEE4C6E8, + 0xEF20CADA, 0x36774C01, 0xD07E9EFE, 0x2BF11FB4, + 0x95DBDA4D, 0xAE909198, 0xEAAD8E71, 0x6B93D5A0, + 0xD08ED1D0, 0xAFC725E0, 0x8E3C5B2F, 0x8E7594B7, + 0x8FF6E2FB, 0xF2122B64, 0x8888B812, 0x900DF01C, + 0x4FAD5EA0, 0x688FC31C, 0xD1CFF191, 0xB3A8C1AD, + 0x2F2F2218, 0xBE0E1777, 0xEA752DFE, 0x8B021FA1, + 0xE5A0CC0F, 0xB56F74E8, 0x18ACF3D6, 0xCE89E299, + 0xB4A84FE0, 0xFD13E0B7, 0x7CC43B81, 0xD2ADA8D9, + 0x165FA266, 0x80957705, 0x93CC7314, 0x211A1477, + 0xE6AD2065, 0x77B5FA86, 0xC75442F5, 0xFB9D35CF, + 0xEBCDAF0C, 0x7B3E89A0, 0xD6411BD3, 0xAE1E7E49, + 0x00250E2D, 0x2071B35E, 0x226800BB, 0x57B8E0AF, + 0x2464369B, 0xF009B91E, 0x5563911D, 0x59DFA6AA, + 0x78C14389, 0xD95A537F, 0x207D5BA2, 0x02E5B9C5, + 0x83260376, 0x6295CFA9, 0x11C81968, 0x4E734A41, + 0xB3472DCA, 0x7B14A94A, 0x1B510052, 0x9A532915, + 0xD60F573F, 0xBC9BC6E4, 0x2B60A476, 0x81E67400, + 0x08BA6FB5, 0x571BE91F, 0xF296EC6B, 0x2A0DD915, + 0xB6636521, 0xE7B9F9B6, 0xFF34052E, 0xC5855664, + 0x53B02D5D, 0xA99F8FA1, 0x08BA4799, 0x6E85076A], + [0x4B7A70E9, 0xB5B32944, 0xDB75092E, 0xC4192623, + 0xAD6EA6B0, 0x49A7DF7D, 0x9CEE60B8, 0x8FEDB266, + 0xECAA8C71, 0x699A17FF, 0x5664526C, 0xC2B19EE1, + 0x193602A5, 0x75094C29, 0xA0591340, 0xE4183A3E, + 0x3F54989A, 0x5B429D65, 0x6B8FE4D6, 0x99F73FD6, + 0xA1D29C07, 0xEFE830F5, 0x4D2D38E6, 0xF0255DC1, + 0x4CDD2086, 0x8470EB26, 0x6382E9C6, 0x021ECC5E, + 0x09686B3F, 0x3EBAEFC9, 0x3C971814, 0x6B6A70A1, + 0x687F3584, 0x52A0E286, 0xB79C5305, 0xAA500737, + 0x3E07841C, 0x7FDEAE5C, 0x8E7D44EC, 0x5716F2B8, + 0xB03ADA37, 0xF0500C0D, 0xF01C1F04, 0x0200B3FF, + 0xAE0CF51A, 0x3CB574B2, 0x25837A58, 0xDC0921BD, + 0xD19113F9, 0x7CA92FF6, 0x94324773, 0x22F54701, + 0x3AE5E581, 0x37C2DADC, 0xC8B57634, 0x9AF3DDA7, + 0xA9446146, 0x0FD0030E, 0xECC8C73E, 0xA4751E41, + 0xE238CD99, 0x3BEA0E2F, 0x3280BBA1, 0x183EB331, + 0x4E548B38, 0x4F6DB908, 0x6F420D03, 0xF60A04BF, + 0x2CB81290, 0x24977C79, 0x5679B072, 0xBCAF89AF, + 0xDE9A771F, 0xD9930810, 0xB38BAE12, 0xDCCF3F2E, + 0x5512721F, 0x2E6B7124, 0x501ADDE6, 0x9F84CD87, + 0x7A584718, 0x7408DA17, 0xBC9F9ABC, 0xE94B7D8C, + 0xEC7AEC3A, 0xDB851DFA, 0x63094366, 0xC464C3D2, + 0xEF1C1847, 0x3215D908, 0xDD433B37, 0x24C2BA16, + 0x12A14D43, 0x2A65C451, 0x50940002, 0x133AE4DD, + 0x71DFF89E, 0x10314E55, 0x81AC77D6, 0x5F11199B, + 0x043556F1, 0xD7A3C76B, 0x3C11183B, 0x5924A509, + 0xF28FE6ED, 0x97F1FBFA, 0x9EBABF2C, 0x1E153C6E, + 0x86E34570, 0xEAE96FB1, 0x860E5E0A, 0x5A3E2AB3, + 0x771FE71C, 0x4E3D06FA, 0x2965DCB9, 0x99E71D0F, + 0x803E89D6, 0x5266C825, 0x2E4CC978, 0x9C10B36A, + 0xC6150EBA, 0x94E2EA78, 0xA5FC3C53, 0x1E0A2DF4, + 0xF2F74EA7, 0x361D2B3D, 0x1939260F, 0x19C27960, + 0x5223A708, 0xF71312B6, 0xEBADFE6E, 0xEAC31F66, + 0xE3BC4595, 0xA67BC883, 0xB17F37D1, 0x018CFF28, + 0xC332DDEF, 0xBE6C5AA5, 0x65582185, 0x68AB9802, + 0xEECEA50F, 0xDB2F953B, 0x2AEF7DAD, 0x5B6E2F84, + 0x1521B628, 0x29076170, 0xECDD4775, 0x619F1510, + 0x13CCA830, 0xEB61BD96, 0x0334FE1E, 0xAA0363CF, + 0xB5735C90, 0x4C70A239, 0xD59E9E0B, 0xCBAADE14, + 0xEECC86BC, 0x60622CA7, 0x9CAB5CAB, 0xB2F3846E, + 0x648B1EAF, 0x19BDF0CA, 0xA02369B9, 0x655ABB50, + 0x40685A32, 0x3C2AB4B3, 0x319EE9D5, 0xC021B8F7, + 0x9B540B19, 0x875FA099, 0x95F7997E, 0x623D7DA8, + 0xF837889A, 0x97E32D77, 0x11ED935F, 0x16681281, + 0x0E358829, 0xC7E61FD6, 0x96DEDFA1, 0x7858BA99, + 0x57F584A5, 0x1B227263, 0x9B83C3FF, 0x1AC24696, + 0xCDB30AEB, 0x532E3054, 0x8FD948E4, 0x6DBC3128, + 0x58EBF2EF, 0x34C6FFEA, 0xFE28ED61, 0xEE7C3C73, + 0x5D4A14D9, 0xE864B7E3, 0x42105D14, 0x203E13E0, + 0x45EEE2B6, 0xA3AAABEA, 0xDB6C4F15, 0xFACB4FD0, + 0xC742F442, 0xEF6ABBB5, 0x654F3B1D, 0x41CD2105, + 0xD81E799E, 0x86854DC7, 0xE44B476A, 0x3D816250, + 0xCF62A1F2, 0x5B8D2646, 0xFC8883A0, 0xC1C7B6A3, + 0x7F1524C3, 0x69CB7492, 0x47848A0B, 0x5692B285, + 0x095BBF00, 0xAD19489D, 0x1462B174, 0x23820E00, + 0x58428D2A, 0x0C55F5EA, 0x1DADF43E, 0x233F7061, + 0x3372F092, 0x8D937E41, 0xD65FECF1, 0x6C223BDB, + 0x7CDE3759, 0xCBEE7460, 0x4085F2A7, 0xCE77326E, + 0xA6078084, 0x19F8509E, 0xE8EFD855, 0x61D99735, + 0xA969A7AA, 0xC50C06C2, 0x5A04ABFC, 0x800BCADC, + 0x9E447A2E, 0xC3453484, 0xFDD56705, 0x0E1E9EC9, + 0xDB73DBD3, 0x105588CD, 0x675FDA79, 0xE3674340, + 0xC5C43465, 0x713E38D8, 0x3D28F89E, 0xF16DFF20, + 0x153E21E7, 0x8FB03D4A, 0xE6E39F2B, 0xDB83ADF7], + [0xE93D5A68, 0x948140F7, 0xF64C261C, 0x94692934, + 0x411520F7, 0x7602D4F7, 0xBCF46B2E, 0xD4A20068, + 0xD4082471, 0x3320F46A, 0x43B7D4B7, 0x500061AF, + 0x1E39F62E, 0x97244546, 0x14214F74, 0xBF8B8840, + 0x4D95FC1D, 0x96B591AF, 0x70F4DDD3, 0x66A02F45, + 0xBFBC09EC, 0x03BD9785, 0x7FAC6DD0, 0x31CB8504, + 0x96EB27B3, 0x55FD3941, 0xDA2547E6, 0xABCA0A9A, + 0x28507825, 0x530429F4, 0x0A2C86DA, 0xE9B66DFB, + 0x68DC1462, 0xD7486900, 0x680EC0A4, 0x27A18DEE, + 0x4F3FFEA2, 0xE887AD8C, 0xB58CE006, 0x7AF4D6B6, + 0xAACE1E7C, 0xD3375FEC, 0xCE78A399, 0x406B2A42, + 0x20FE9E35, 0xD9F385B9, 0xEE39D7AB, 0x3B124E8B, + 0x1DC9FAF7, 0x4B6D1856, 0x26A36631, 0xEAE397B2, + 0x3A6EFA74, 0xDD5B4332, 0x6841E7F7, 0xCA7820FB, + 0xFB0AF54E, 0xD8FEB397, 0x454056AC, 0xBA489527, + 0x55533A3A, 0x20838D87, 0xFE6BA9B7, 0xD096954B, + 0x55A867BC, 0xA1159A58, 0xCCA92963, 0x99E1DB33, + 0xA62A4A56, 0x3F3125F9, 0x5EF47E1C, 0x9029317C, + 0xFDF8E802, 0x04272F70, 0x80BB155C, 0x05282CE3, + 0x95C11548, 0xE4C66D22, 0x48C1133F, 0xC70F86DC, + 0x07F9C9EE, 0x41041F0F, 0x404779A4, 0x5D886E17, + 0x325F51EB, 0xD59BC0D1, 0xF2BCC18F, 0x41113564, + 0x257B7834, 0x602A9C60, 0xDFF8E8A3, 0x1F636C1B, + 0x0E12B4C2, 0x02E1329E, 0xAF664FD1, 0xCAD18115, + 0x6B2395E0, 0x333E92E1, 0x3B240B62, 0xEEBEB922, + 0x85B2A20E, 0xE6BA0D99, 0xDE720C8C, 0x2DA2F728, + 0xD0127845, 0x95B794FD, 0x647D0862, 0xE7CCF5F0, + 0x5449A36F, 0x877D48FA, 0xC39DFD27, 0xF33E8D1E, + 0x0A476341, 0x992EFF74, 0x3A6F6EAB, 0xF4F8FD37, + 0xA812DC60, 0xA1EBDDF8, 0x991BE14C, 0xDB6E6B0D, + 0xC67B5510, 0x6D672C37, 0x2765D43B, 0xDCD0E804, + 0xF1290DC7, 0xCC00FFA3, 0xB5390F92, 0x690FED0B, + 0x667B9FFB, 0xCEDB7D9C, 0xA091CF0B, 0xD9155EA3, + 0xBB132F88, 0x515BAD24, 0x7B9479BF, 0x763BD6EB, + 0x37392EB3, 0xCC115979, 0x8026E297, 0xF42E312D, + 0x6842ADA7, 0xC66A2B3B, 0x12754CCC, 0x782EF11C, + 0x6A124237, 0xB79251E7, 0x06A1BBE6, 0x4BFB6350, + 0x1A6B1018, 0x11CAEDFA, 0x3D25BDD8, 0xE2E1C3C9, + 0x44421659, 0x0A121386, 0xD90CEC6E, 0xD5ABEA2A, + 0x64AF674E, 0xDA86A85F, 0xBEBFE988, 0x64E4C3FE, + 0x9DBC8057, 0xF0F7C086, 0x60787BF8, 0x6003604D, + 0xD1FD8346, 0xF6381FB0, 0x7745AE04, 0xD736FCCC, + 0x83426B33, 0xF01EAB71, 0xB0804187, 0x3C005E5F, + 0x77A057BE, 0xBDE8AE24, 0x55464299, 0xBF582E61, + 0x4E58F48F, 0xF2DDFDA2, 0xF474EF38, 0x8789BDC2, + 0x5366F9C3, 0xC8B38E74, 0xB475F255, 0x46FCD9B9, + 0x7AEB2661, 0x8B1DDF84, 0x846A0E79, 0x915F95E2, + 0x466E598E, 0x20B45770, 0x8CD55591, 0xC902DE4C, + 0xB90BACE1, 0xBB8205D0, 0x11A86248, 0x7574A99E, + 0xB77F19B6, 0xE0A9DC09, 0x662D09A1, 0xC4324633, + 0xE85A1F02, 0x09F0BE8C, 0x4A99A025, 0x1D6EFE10, + 0x1AB93D1D, 0x0BA5A4DF, 0xA186F20F, 0x2868F169, + 0xDCB7DA83, 0x573906FE, 0xA1E2CE9B, 0x4FCD7F52, + 0x50115E01, 0xA70683FA, 0xA002B5C4, 0x0DE6D027, + 0x9AF88C27, 0x773F8641, 0xC3604C06, 0x61A806B5, + 0xF0177A28, 0xC0F586E0, 0x006058AA, 0x30DC7D62, + 0x11E69ED7, 0x2338EA63, 0x53C2DD94, 0xC2C21634, + 0xBBCBEE56, 0x90BCB6DE, 0xEBFC7DA1, 0xCE591D76, + 0x6F05E409, 0x4B7C0188, 0x39720A3D, 0x7C927C24, + 0x86E3725F, 0x724D9DB9, 0x1AC15BB4, 0xD39EB8FC, + 0xED545578, 0x08FCA5B5, 0xD83D7CD3, 0x4DAD0FC4, + 0x1E50EF5E, 0xB161E6F8, 0xA28514D9, 0x6C51133C, + 0x6FD5C7E7, 0x56E14EC4, 0x362ABFCE, 0xDDC6C837, + 0xD79A3234, 0x92638212, 0x670EFA8E, 0x406000E0], + [0x3A39CE37, 0xD3FAF5CF, 0xABC27737, 0x5AC52D1B, + 0x5CB0679E, 0x4FA33742, 0xD3822740, 0x99BC9BBE, + 0xD5118E9D, 0xBF0F7315, 0xD62D1C7E, 0xC700C47B, + 0xB78C1B6B, 0x21A19045, 0xB26EB1BE, 0x6A366EB4, + 0x5748AB2F, 0xBC946E79, 0xC6A376D2, 0x6549C2C8, + 0x530FF8EE, 0x468DDE7D, 0xD5730A1D, 0x4CD04DC6, + 0x2939BBDB, 0xA9BA4650, 0xAC9526E8, 0xBE5EE304, + 0xA1FAD5F0, 0x6A2D519A, 0x63EF8CE2, 0x9A86EE22, + 0xC089C2B8, 0x43242EF6, 0xA51E03AA, 0x9CF2D0A4, + 0x83C061BA, 0x9BE96A4D, 0x8FE51550, 0xBA645BD6, + 0x2826A2F9, 0xA73A3AE1, 0x4BA99586, 0xEF5562E9, + 0xC72FEFD3, 0xF752F7DA, 0x3F046F69, 0x77FA0A59, + 0x80E4A915, 0x87B08601, 0x9B09E6AD, 0x3B3EE593, + 0xE990FD5A, 0x9E34D797, 0x2CF0B7D9, 0x022B8B51, + 0x96D5AC3A, 0x017DA67D, 0xD1CF3ED6, 0x7C7D2D28, + 0x1F9F25CF, 0xADF2B89B, 0x5AD6B472, 0x5A88F54C, + 0xE029AC71, 0xE019A5E6, 0x47B0ACFD, 0xED93FA9B, + 0xE8D3C48D, 0x283B57CC, 0xF8D56629, 0x79132E28, + 0x785F0191, 0xED756055, 0xF7960E44, 0xE3D35E8C, + 0x15056DD4, 0x88F46DBA, 0x03A16125, 0x0564F0BD, + 0xC3EB9E15, 0x3C9057A2, 0x97271AEC, 0xA93A072A, + 0x1B3F6D9B, 0x1E6321F5, 0xF59C66FB, 0x26DCF319, + 0x7533D928, 0xB155FDF5, 0x03563482, 0x8ABA3CBB, + 0x28517711, 0xC20AD9F8, 0xABCC5167, 0xCCAD925F, + 0x4DE81751, 0x3830DC8E, 0x379D5862, 0x9320F991, + 0xEA7A90C2, 0xFB3E7BCE, 0x5121CE64, 0x774FBE32, + 0xA8B6E37E, 0xC3293D46, 0x48DE5369, 0x6413E680, + 0xA2AE0810, 0xDD6DB224, 0x69852DFD, 0x09072166, + 0xB39A460A, 0x6445C0DD, 0x586CDECF, 0x1C20C8AE, + 0x5BBEF7DD, 0x1B588D40, 0xCCD2017F, 0x6BB4E3BB, + 0xDDA26A7E, 0x3A59FF45, 0x3E350A44, 0xBCB4CDD5, + 0x72EACEA8, 0xFA6484BB, 0x8D6612AE, 0xBF3C6F47, + 0xD29BE463, 0x542F5D9E, 0xAEC2771B, 0xF64E6370, + 0x740E0D8D, 0xE75B1357, 0xF8721671, 0xAF537D5D, + 0x4040CB08, 0x4EB4E2CC, 0x34D2466A, 0x0115AF84, + 0xE1B00428, 0x95983A1D, 0x06B89FB4, 0xCE6EA048, + 0x6F3F3B82, 0x3520AB82, 0x011A1D4B, 0x277227F8, + 0x611560B1, 0xE7933FDC, 0xBB3A792B, 0x344525BD, + 0xA08839E1, 0x51CE794B, 0x2F32C9B7, 0xA01FBAC9, + 0xE01CC87E, 0xBCC7D1F6, 0xCF0111C3, 0xA1E8AAC7, + 0x1A908749, 0xD44FBD9A, 0xD0DADECB, 0xD50ADA38, + 0x0339C32A, 0xC6913667, 0x8DF9317C, 0xE0B12B4F, + 0xF79E59B7, 0x43F5BB3A, 0xF2D519FF, 0x27D9459C, + 0xBF97222C, 0x15E6FC2A, 0x0F91FC71, 0x9B941525, + 0xFAE59361, 0xCEB69CEB, 0xC2A86459, 0x12BAA8D1, + 0xB6C1075E, 0xE3056A0C, 0x10D25065, 0xCB03A442, + 0xE0EC6E0E, 0x1698DB3B, 0x4C98A0BE, 0x3278E964, + 0x9F1F9532, 0xE0D392DF, 0xD3A0342B, 0x8971F21E, + 0x1B0A7441, 0x4BA3348C, 0xC5BE7120, 0xC37632D8, + 0xDF359F8D, 0x9B992F2E, 0xE60B6F47, 0x0FE3F11D, + 0xE54CDA54, 0x1EDAD891, 0xCE6279CF, 0xCD3E7E6F, + 0x1618B166, 0xFD2C1D05, 0x848FD2C5, 0xF6FB2299, + 0xF523F357, 0xA6327623, 0x93A83531, 0x56CCCD02, + 0xACF08162, 0x5A75EBB5, 0x6E163697, 0x88D273CC, + 0xDE966292, 0x81B949D0, 0x4C50901B, 0x71C65614, + 0xE6C6C7BD, 0x327A140A, 0x45E1D006, 0xC3F27B9A, + 0xC9AA53FD, 0x62A80F00, 0xBB25BFE2, 0x35BDD2F6, + 0x71126905, 0xB2040222, 0xB6CBCF7C, 0xCD769C2B, + 0x53113EC0, 0x1640E3D3, 0x38ABBD60, 0x2547ADF0, + 0xBA38209C, 0xF746CE76, 0x77AFA1C5, 0x20756060, + 0x85CBFE4E, 0x8AE88DD8, 0x7AAAF9B0, 0x4CF9AA7E, + 0x1948C25C, 0x02FB8A8C, 0x01C36AE4, 0xD6EBE1F9, + 0x90D4F869, 0xA65CDEA0, 0x3F09252D, 0xC208E69F, + 0xB74E6132, 0xCE77E25B, 0x578FDFE3, 0x3AC372E6] + ] + + public init(key: Array, iv: Array? = nil, blockMode: BlockMode = .CBC, padding: Padding) throws { + precondition(key.count >= 8 && key.count <= 56) + + self.blockMode = blockMode + self.padding = padding + + self.S = self.origS + self.P = self.origP + + if let iv = iv, !iv.isEmpty { + self.iv = iv + } else { + self.iv = Array(repeating: 0, count: Blowfish.blockSize) + } + + if (blockMode.options.contains(.InitializationVectorRequired) && self.iv.count != Blowfish.blockSize) { + assert(false, "Block size and Initialization Vector must be the same length!") + throw Error.invalidInitializationVector + } + + self.expandKey(key: key) + } + + private func reset() { + self.S = self.origS + self.P = self.origP + // todo expand key + } + + private func expandKey(key: Array) { + var j = 0 + for i in 0 ..< (self.N + 2) { + var data: UInt32 = 0x0 + for _ in 0 ..< 4 { + data = (data << 8) | UInt32(key[j]) + j += 1 + if j >= key.count { + j = 0 + } + } + self.P[i] ^= data + } + + var datal: UInt32 = 0 + var datar: UInt32 = 0 + + for i in stride(from: 0, to: self.N + 2, by: 2) { + self.encryptBlowfishBlock(l: &datal, r: &datar) + self.P[i] = datal + self.P[i + 1] = datar + } + + for i in 0 ..< 4 { + for j in stride(from: 0, to: 256, by: 2) { + self.encryptBlowfishBlock(l: &datal, r: &datar) + self.S[i][j] = datal + self.S[i][j + 1] = datar + } + } + } + + fileprivate func encrypt(block: Array) -> Array? { + var result = Array() + + var l = UInt32(bytes: block[0..<4]) + var r = UInt32(bytes: block[4..<8]) + + self.encryptBlowfishBlock(l: &l, r: &r) + + // because everything is too complex to be solved in reasonable time o_O + result += [UInt8((l >> 24) & 0xFF), + UInt8((l >> 16) & 0xFF)] + result += [UInt8((l >> 8) & 0xFF), + UInt8((l >> 0) & 0xFF)] + result += [UInt8((r >> 24) & 0xFF), + UInt8((r >> 16) & 0xFF)] + result += [UInt8((r >> 8) & 0xFF), + UInt8((r >> 0) & 0xFF)] + + return result + } + + fileprivate func decrypt(block: Array) -> Array? { + var result = Array() + + var l = UInt32(bytes: block[0..<4]) + var r = UInt32(bytes: block[4..<8]) + + self.decryptBlowfishBlock(l: &l, r: &r) + + // because everything is too complex to be solved in reasonable time o_O + result += [UInt8((l >> 24) & 0xFF), + UInt8((l >> 16) & 0xFF)] + result += [UInt8((l >> 8) & 0xFF), + UInt8((l >> 0) & 0xFF)] + result += [UInt8((r >> 24) & 0xFF), + UInt8((r >> 16) & 0xFF)] + result += [UInt8((r >> 8) & 0xFF), + UInt8((r >> 0) & 0xFF)] + return result + } + + /// Encrypts the 8-byte padded buffer + /// + /// - Parameters: + /// - l: left half + /// - r: right half + fileprivate func encryptBlowfishBlock(l: inout UInt32, r: inout UInt32) { + var Xl = l + var Xr = r + + for i in 0 ..< self.N { + Xl = Xl ^ self.P[i] + Xr = F(x: Xl) ^ Xr + + (Xl, Xr) = (Xr, Xl) + } + + (Xl, Xr) = (Xr, Xl) + + Xr = Xr ^ self.P[self.N] + Xl = Xl ^ self.P[self.N + 1] + + l = Xl + r = Xr + } + + /// Decrypts the 8-byte padded buffer + /// + /// - Parameters: + /// - l: left half + /// - r: right half + fileprivate func decryptBlowfishBlock(l: inout UInt32, r: inout UInt32) { + var Xl = l + var Xr = r + + for i in (2 ... self.N + 1).reversed() { + Xl = Xl ^ self.P[i] + Xr = F(x: Xl) ^ Xr + + (Xl, Xr) = (Xr, Xl) + } + + (Xl, Xr) = (Xr, Xl) + + Xr = Xr ^ self.P[1] + Xl = Xl ^ self.P[0] + + l = Xl + r = Xr + } + + private func F(x: UInt32) -> UInt32 { + return ((self.S[0][Int(x >> 24) & 0xFF] &+ self.S[1][Int(x >> 16) & 0xFF]) ^ self.S[2][Int(x >> 8) & 0xFF]) &+ self.S[3][Int(x) & 0xFF] + } +} + +extension Blowfish: Cipher { + /// Encrypt the 8-byte padded buffer, block by block. Note that for amounts of data larger than a block, it is not safe to just call encrypt() on successive blocks. + /// + /// - Parameter bytes: Plaintext data + /// - Returns: Encrypted data + public func encrypt(_ bytes: C) throws -> Array where C.Iterator.Element == UInt8, C.IndexDistance == Int, C.Index == Int { + + let bytes = padding.add(to: Array(bytes), blockSize: Blowfish.blockSize) //FIXME: Array(bytes) copies + + var out = Array() + out.reserveCapacity(bytes.count) + + for chunk in BytesSequence(chunkSize: Blowfish.blockSize, data: bytes) { + out += self.encryptWorker.encrypt(Array(chunk)) //FIXME: copying here is innefective + } + + if blockMode.options.contains(.PaddingRequired) && (out.count % Blowfish.blockSize != 0) { + throw Error.dataPaddingRequired + } + + return out + } + + + /// Decrypt the 8-byte padded buffer + /// + /// - Parameter bytes: Ciphertext data + /// - Returns: Plaintext data + public func decrypt(_ bytes: C) throws -> Array where C.Iterator.Element == UInt8, C.IndexDistance == Int, C.Index == Int { + + if blockMode.options.contains(.PaddingRequired) && (bytes.count % Blowfish.blockSize != 0) { + throw Error.dataPaddingRequired + } + + var out = Array() + out.reserveCapacity(bytes.count) + + for chunk in BytesSequence(chunkSize: Blowfish.blockSize, data: Array(bytes)) { + out += self.decryptWorker.decrypt(Array(chunk)) //FIXME: copying here is innefective + } + + out = padding.remove(from: out, blockSize: Blowfish.blockSize) + + return out + } +} + + + diff --git a/GeneralUtils/GeneralUtils/libs/CryptoSwift/BytesSequence.swift b/GeneralUtils/GeneralUtils/libs/CryptoSwift/BytesSequence.swift new file mode 100644 index 0000000..8705c26 --- /dev/null +++ b/GeneralUtils/GeneralUtils/libs/CryptoSwift/BytesSequence.swift @@ -0,0 +1,45 @@ +// +// BytesSequence.swift +// CryptoSwift +// +// Created by Marcin Krzyzanowski on 26/09/15. +// Copyright © 2015 Marcin Krzyzanowski. All rights reserved. +// + +/// Generic version of BytesSequence is slower, therefore specialized version is in use +/// +// struct BytesSequence: Sequence where D.Iterator.Element == UInt8, D.IndexDistance == Int, D.SubSequence.IndexDistance == Int, D.Index == Int { +// let chunkSize: D.IndexDistance +// let data: D +// +// func makeIterator() -> AnyIterator { +// var offset = data.startIndex +// return AnyIterator { +// let end = Swift.min(self.chunkSize, self.data.count - offset) +// let result = self.data[offset...IndexDistance + let data: Array + + func makeIterator() -> AnyIterator> { + var offset = data.startIndex + return AnyIterator { + let end = Swift.min(self.chunkSize, self.data.count &- offset) + let result = self.data[offset ..< offset &+ end] + offset = offset.advanced(by: result.count) + if !result.isEmpty { + return result + } + return nil + } + } +} diff --git a/GeneralUtils/GeneralUtils/libs/CryptoSwift/CSArrayType+Extensions.swift b/GeneralUtils/GeneralUtils/libs/CryptoSwift/CSArrayType+Extensions.swift new file mode 100644 index 0000000..35a65b5 --- /dev/null +++ b/GeneralUtils/GeneralUtils/libs/CryptoSwift/CSArrayType+Extensions.swift @@ -0,0 +1,86 @@ +// +// _ArrayType+Extensions.swift +// CryptoSwift +// +// Created by Marcin Krzyzanowski on 08/10/15. +// Copyright © 2015 Marcin Krzyzanowski. All rights reserved. +// + +public protocol CSArrayType: Collection, RangeReplaceableCollection { + func cs_arrayValue() -> [Iterator.Element] +} + +extension Array: CSArrayType { + + public func cs_arrayValue() -> [Iterator.Element] { + return self + } +} + +public extension CSArrayType where Iterator.Element == UInt8 { + + public func toHexString() -> String { + return self.lazy.reduce("") { + var s = String($1, radix: 16) + if s.characters.count == 1 { + s = "0" + s + } + return $0 + s + } + } +} + +public extension CSArrayType where Iterator.Element == UInt8 { + + public func md5() -> [Iterator.Element] { + return Digest.md5(cs_arrayValue()) + } + + public func sha1() -> [Iterator.Element] { + return Digest.sha1(cs_arrayValue()) + } + + public func sha224() -> [Iterator.Element] { + return Digest.sha224(cs_arrayValue()) + } + + public func sha256() -> [Iterator.Element] { + return Digest.sha256(cs_arrayValue()) + } + + public func sha384() -> [Iterator.Element] { + return Digest.sha384(cs_arrayValue()) + } + + public func sha512() -> [Iterator.Element] { + return Digest.sha512(cs_arrayValue()) + } + + public func sha2(_ variant: SHA2.Variant) -> [Iterator.Element] { + return Digest.sha2(cs_arrayValue(), variant: variant) + } + + public func sha3(_ variant: SHA3.Variant) -> [Iterator.Element] { + return Digest.sha3(cs_arrayValue(), variant: variant) + } + + public func crc32(seed: UInt32? = nil, reflect: Bool = true) -> UInt32 { + return Checksum.crc32(cs_arrayValue(), seed: seed, reflect: reflect) + } + + public func crc16(seed: UInt16? = nil) -> UInt16 { + return Checksum.crc16(cs_arrayValue(), seed: seed) + } + + public func encrypt(cipher: Cipher) throws -> [Iterator.Element] { + return try cipher.encrypt(cs_arrayValue()) + } + + public func decrypt(cipher: Cipher) throws -> [Iterator.Element] { + return try cipher.decrypt(cs_arrayValue()) + } + + public func authenticate(with authenticator: A) throws -> [Iterator.Element] { + return try authenticator.authenticate(cs_arrayValue()) + } +} diff --git a/GeneralUtils/GeneralUtils/libs/CryptoSwift/ChaCha20.swift b/GeneralUtils/GeneralUtils/libs/CryptoSwift/ChaCha20.swift new file mode 100644 index 0000000..95be8d7 --- /dev/null +++ b/GeneralUtils/GeneralUtils/libs/CryptoSwift/ChaCha20.swift @@ -0,0 +1,343 @@ +// +// ChaCha20.swift +// CryptoSwift +// +// Created by Marcin Krzyzanowski on 25/08/14. +// Copyright (c) 2014 Marcin Krzyzanowski. All rights reserved. +// + +private typealias Key = SecureBytes + +public final class ChaCha20: BlockCipher { + + public enum Error: Swift.Error { + case invalidKeyOrInitializationVector + } + + public static let blockSize = 64 // 512 / 8 + + fileprivate let key: Key + fileprivate var counter: Array + + public init(key: Array, iv nonce: Array) throws { + precondition(nonce.count == 12 || nonce.count == 8) + + let kbits = key.count * 8 + + if (kbits != 128 && kbits != 256) { + throw Error.invalidKeyOrInitializationVector + } + + self.key = Key(bytes: key) + + if nonce.count == 8 { + self.counter = [0,0,0,0,0,0,0,0] + nonce + } else { + self.counter = [0,0,0,0] + nonce + } + + assert(self.counter.count == 16) + } + + /// https://tools.ietf.org/html/rfc7539#section-2.3. + fileprivate func core(block: inout Array, counter: Array, key: Array) { + precondition(block.count == ChaCha20.blockSize) + precondition(counter.count == 16) + precondition(key.count == 32) + + let j0: UInt32 = 0x61707865 + let j1: UInt32 = 0x3320646e // 0x3620646e sigma/tau + let j2: UInt32 = 0x79622d32 + let j3: UInt32 = 0x6b206574 + let j4: UInt32 = UInt32(bytes: key[0..<4]).bigEndian + let j5: UInt32 = UInt32(bytes: key[4..<8]).bigEndian + let j6: UInt32 = UInt32(bytes: key[8..<12]).bigEndian + let j7: UInt32 = UInt32(bytes: key[12..<16]).bigEndian + let j8: UInt32 = UInt32(bytes: key[16..<20]).bigEndian + let j9: UInt32 = UInt32(bytes: key[20..<24]).bigEndian + let j10: UInt32 = UInt32(bytes: key[24..<28]).bigEndian + let j11: UInt32 = UInt32(bytes: key[28..<32]).bigEndian + let j12: UInt32 = UInt32(bytes: counter[0..<4]).bigEndian + let j13: UInt32 = UInt32(bytes: counter[4..<8]).bigEndian + let j14: UInt32 = UInt32(bytes: counter[8..<12]).bigEndian + let j15: UInt32 = UInt32(bytes: counter[12..<16]).bigEndian + + var (x0, x1, x2, x3, x4, x5, x6, x7) = (j0, j1, j2, j3, j4, j5, j6, j7) + var (x8, x9, x10, x11, x12, x13, x14, x15) = (j8, j9, j10, j11, j12, j13, j14, j15) + + for _ in 0..<10 { // 20 rounds + x0 = x0 &+ x4 + x12 ^= x0 + x12 = (x12 << 16) | (x12 >> (16)) + x8 = x8 &+ x12 + x4 ^= x8 + x4 = (x4 << 12) | (x4 >> (20)) + x0 = x0 &+ x4 + x12 ^= x0 + x12 = (x12 << 8) | (x12 >> (24)) + x8 = x8 &+ x12 + x4 ^= x8 + x4 = (x4 << 7) | (x4 >> (25)) + x1 = x1 &+ x5 + x13 ^= x1 + x13 = (x13 << 16) | (x13 >> 16) + x9 = x9 &+ x13 + x5 ^= x9 + x5 = (x5 << 12) | (x5 >> 20) + x1 = x1 &+ x5 + x13 ^= x1 + x13 = (x13 << 8) | (x13 >> 24) + x9 = x9 &+ x13 + x5 ^= x9 + x5 = (x5 << 7) | (x5 >> 25) + x2 = x2 &+ x6 + x14 ^= x2 + x14 = (x14 << 16) | (x14 >> 16) + x10 = x10 &+ x14 + x6 ^= x10 + x6 = (x6 << 12) | (x6 >> 20) + x2 = x2 &+ x6 + x14 ^= x2 + x14 = (x14 << 8) | (x14 >> 24) + x10 = x10 &+ x14 + x6 ^= x10 + x6 = (x6 << 7) | (x6 >> 25) + x3 = x3 &+ x7 + x15 ^= x3 + x15 = (x15 << 16) | (x15 >> 16) + x11 = x11 &+ x15 + x7 ^= x11 + x7 = (x7 << 12) | (x7 >> 20) + x3 = x3 &+ x7 + x15 ^= x3 + x15 = (x15 << 8) | (x15 >> 24) + x11 = x11 &+ x15 + x7 ^= x11 + x7 = (x7 << 7) | (x7 >> 25) + x0 = x0 &+ x5 + x15 ^= x0 + x15 = (x15 << 16) | (x15 >> 16) + x10 = x10 &+ x15 + x5 ^= x10 + x5 = (x5 << 12) | (x5 >> 20) + x0 = x0 &+ x5 + x15 ^= x0 + x15 = (x15 << 8) | (x15 >> 24) + x10 = x10 &+ x15 + x5 ^= x10 + x5 = (x5 << 7) | (x5 >> 25) + x1 = x1 &+ x6 + x12 ^= x1 + x12 = (x12 << 16) | (x12 >> 16) + x11 = x11 &+ x12 + x6 ^= x11 + x6 = (x6 << 12) | (x6 >> 20) + x1 = x1 &+ x6 + x12 ^= x1 + x12 = (x12 << 8) | (x12 >> 24) + x11 = x11 &+ x12 + x6 ^= x11 + x6 = (x6 << 7) | (x6 >> 25) + x2 = x2 &+ x7 + x13 ^= x2 + x13 = (x13 << 16) | (x13 >> 16) + x8 = x8 &+ x13 + x7 ^= x8 + x7 = (x7 << 12) | (x7 >> 20) + x2 = x2 &+ x7 + x13 ^= x2 + x13 = (x13 << 8) | (x13 >> 24) + x8 = x8 &+ x13 + x7 ^= x8 + x7 = (x7 << 7) | (x7 >> 25) + x3 = x3 &+ x4 + x14 ^= x3 + x14 = (x14 << 16) | (x14 >> 16) + x9 = x9 &+ x14 + x4 ^= x9 + x4 = (x4 << 12) | (x4 >> 20) + x3 = x3 &+ x4 + x14 ^= x3 + x14 = (x14 << 8) | (x14 >> 24) + x9 = x9 &+ x14 + x4 ^= x9 + x4 = (x4 << 7) | (x4 >> 25) + } + + x0 = x0 &+ j0 + x1 = x1 &+ j1 + x2 = x2 &+ j2 + x3 = x3 &+ j3 + x4 = x4 &+ j4 + x5 = x5 &+ j5 + x6 = x6 &+ j6 + x7 = x7 &+ j7 + x8 = x8 &+ j8 + x9 = x9 &+ j9 + x10 = x10 &+ j10 + x11 = x11 &+ j11 + x12 = x12 &+ j12 + x13 = x13 &+ j13 + x14 = x14 &+ j14 + x15 = x15 &+ j15 + + block.replaceSubrange(0..<4, with: x0.bigEndian.bytes()) + block.replaceSubrange(4..<8, with: x1.bigEndian.bytes()) + block.replaceSubrange(8..<12, with: x2.bigEndian.bytes()) + block.replaceSubrange(12..<16, with: x3.bigEndian.bytes()) + block.replaceSubrange(16..<20, with: x4.bigEndian.bytes()) + block.replaceSubrange(20..<24, with: x5.bigEndian.bytes()) + block.replaceSubrange(24..<28, with: x6.bigEndian.bytes()) + block.replaceSubrange(28..<32, with: x7.bigEndian.bytes()) + block.replaceSubrange(32..<36, with: x8.bigEndian.bytes()) + block.replaceSubrange(36..<40, with: x9.bigEndian.bytes()) + block.replaceSubrange(40..<44, with: x10.bigEndian.bytes()) + block.replaceSubrange(44..<48, with: x11.bigEndian.bytes()) + block.replaceSubrange(48..<52, with: x12.bigEndian.bytes()) + block.replaceSubrange(52..<56, with: x13.bigEndian.bytes()) + block.replaceSubrange(56..<60, with: x14.bigEndian.bytes()) + block.replaceSubrange(60..<64, with: x15.bigEndian.bytes()) + } + + // XORKeyStream + func process(bytes: Array, counter: inout Array, key: Array) -> Array { + precondition(counter.count == 16) + precondition(key.count == 32) + + var block = Array(repeating: 0, count: ChaCha20.blockSize) + var bytes = bytes //TODO: check bytes[bytes.indices] + var out = Array.init(reserveCapacity: bytes.count) + + while bytes.count >= ChaCha20.blockSize { + self.core(block: &block, counter: counter, key: key) + for (i,x) in block.enumerated() { + out.append(bytes[i] ^ x) + } + var u: UInt32 = 1 + for i in 0..<4 { + u += UInt32(counter[i]) + counter[i] = UInt8(u) + u >>= 8 + } + bytes = Array(bytes[ChaCha20.blockSize.. 0 { + self.core(block: &block, counter: counter, key: key) + for (i, v) in bytes.enumerated() { + out.append(v ^ block[i]) + } + } + return out + } +} + +// MARK: Cipher +extension ChaCha20: Cipher { + + public func encrypt(_ bytes: C) throws -> Array where C.Iterator.Element == UInt8, C.IndexDistance == Int, C.Index == Int { + return process(bytes: Array(bytes), counter: &self.counter, key: Array(self.key)) + } + + public func decrypt(_ bytes: C) throws -> Array where C.Iterator.Element == UInt8, C.IndexDistance == Int, C.Index == Int { + return try encrypt(bytes) + } +} + +// MARK: Encryptor +extension ChaCha20 { + + public struct Encryptor: Updatable { + private var accumulated = Array() + private let chacha: ChaCha20 + + init(chacha: ChaCha20) { + self.chacha = chacha + } + + mutating public func update(withBytes bytes: T, isLast: Bool = false) throws -> Array where T.Iterator.Element == UInt8 { + self.accumulated += bytes + + var encrypted = Array() + encrypted.reserveCapacity(self.accumulated.count) + for chunk in BytesSequence(chunkSize: ChaCha20.blockSize, data: self.accumulated) { + if (isLast || self.accumulated.count >= ChaCha20.blockSize) { + encrypted += try chacha.encrypt(chunk) + self.accumulated.removeFirst(chunk.count) //TODO: improve performance + } + } + return encrypted + } + } +} + +// MARK: Decryptor +extension ChaCha20 { + + public struct Decryptor: Updatable { + private var accumulated = Array() + + private var offset: Int = 0 + private var offsetToRemove: Int = 0 + private let chacha: ChaCha20 + + init(chacha: ChaCha20) { + self.chacha = chacha + } + + mutating public func update(withBytes bytes: T, isLast: Bool = true) throws -> Array where T.Iterator.Element == UInt8 { + // prepend "offset" number of bytes at the begining + if self.offset > 0 { + self.accumulated += Array(repeating: 0, count: offset) + bytes + self.offsetToRemove = offset + self.offset = 0 + } else { + self.accumulated += bytes + } + + var plaintext = Array() + plaintext.reserveCapacity(self.accumulated.count) + for chunk in BytesSequence(chunkSize: ChaCha20.blockSize, data: self.accumulated) { + if (isLast || self.accumulated.count >= ChaCha20.blockSize) { + plaintext += try chacha.decrypt(chunk) + + // remove "offset" from the beginning of first chunk + if self.offsetToRemove > 0 { + plaintext.removeFirst(self.offsetToRemove) //TODO: improve performance + self.offsetToRemove = 0 + } + + self.accumulated.removeFirst(chunk.count) + } + } + + return plaintext + } + } +} + +// MARK: Cryptors +extension ChaCha20: Cryptors { + + public func makeEncryptor() -> ChaCha20.Encryptor { + return Encryptor(chacha: self) + } + + public func makeDecryptor() -> ChaCha20.Decryptor { + return Decryptor(chacha: self) + } +} + +// MARK: Helpers + +/// Change array to number. It's here because arrayOfBytes is too slow +//TODO: check if it should replace arrayOfBytes +//private func wordNumber(_ bytes: T) -> UInt32 where T.Iterator.Element == UInt8, T.IndexDistance == Int { +// var value: UInt32 = 0 +// for i: UInt32 in 0 ..< 4 { +// let j = bytes.index(bytes.startIndex, offsetBy: Int(i)) +// value = value | UInt32(bytes[j]) << (8 * i) +// } +// +// return value +//} diff --git a/GeneralUtils/GeneralUtils/libs/CryptoSwift/Checksum.swift b/GeneralUtils/GeneralUtils/libs/CryptoSwift/Checksum.swift new file mode 100644 index 0000000..3a41f9b --- /dev/null +++ b/GeneralUtils/GeneralUtils/libs/CryptoSwift/Checksum.swift @@ -0,0 +1,122 @@ +// +// Checksum.swift +// CryptoSwift +// +// Created by Marcin Krzyzanowski on 25/08/14. +// Copyright (c) 2014 Marcin Krzyzanowski. All rights reserved. +// + +/// CRC - cyclic redundancy check code. +public final class Checksum { + private static let table32: Array = [0x00000000, 0x77073096, 0xee0e612c, 0x990951ba, 0x076dc419, 0x706af48f, 0xe963a535, 0x9e6495a3, + 0x0edb8832, 0x79dcb8a4, 0xe0d5e91e, 0x97d2d988, 0x09b64c2b, 0x7eb17cbd, 0xe7b82d07, 0x90bf1d91, + 0x1db71064, 0x6ab020f2, 0xf3b97148, 0x84be41de, 0x1adad47d, 0x6ddde4eb, 0xf4d4b551, 0x83d385c7, + 0x136c9856, 0x646ba8c0, 0xfd62f97a, 0x8a65c9ec, 0x14015c4f, 0x63066cd9, 0xfa0f3d63, 0x8d080df5, + 0x3b6e20c8, 0x4c69105e, 0xd56041e4, 0xa2677172, 0x3c03e4d1, 0x4b04d447, 0xd20d85fd, 0xa50ab56b, + 0x35b5a8fa, 0x42b2986c, 0xdbbbc9d6, 0xacbcf940, 0x32d86ce3, 0x45df5c75, 0xdcd60dcf, 0xabd13d59, + 0x26d930ac, 0x51de003a, 0xc8d75180, 0xbfd06116, 0x21b4f4b5, 0x56b3c423, 0xcfba9599, 0xb8bda50f, + 0x2802b89e, 0x5f058808, 0xc60cd9b2, 0xb10be924, 0x2f6f7c87, 0x58684c11, 0xc1611dab, 0xb6662d3d, + 0x76dc4190, 0x01db7106, 0x98d220bc, 0xefd5102a, 0x71b18589, 0x06b6b51f, 0x9fbfe4a5, 0xe8b8d433, + 0x7807c9a2, 0x0f00f934, 0x9609a88e, 0xe10e9818, 0x7f6a0dbb, 0x086d3d2d, 0x91646c97, 0xe6635c01, + 0x6b6b51f4, 0x1c6c6162, 0x856530d8, 0xf262004e, 0x6c0695ed, 0x1b01a57b, 0x8208f4c1, 0xf50fc457, + 0x65b0d9c6, 0x12b7e950, 0x8bbeb8ea, 0xfcb9887c, 0x62dd1ddf, 0x15da2d49, 0x8cd37cf3, 0xfbd44c65, + 0x4db26158, 0x3ab551ce, 0xa3bc0074, 0xd4bb30e2, 0x4adfa541, 0x3dd895d7, 0xa4d1c46d, 0xd3d6f4fb, + 0x4369e96a, 0x346ed9fc, 0xad678846, 0xda60b8d0, 0x44042d73, 0x33031de5, 0xaa0a4c5f, 0xdd0d7cc9, + 0x5005713c, 0x270241aa, 0xbe0b1010, 0xc90c2086, 0x5768b525, 0x206f85b3, 0xb966d409, 0xce61e49f, + 0x5edef90e, 0x29d9c998, 0xb0d09822, 0xc7d7a8b4, 0x59b33d17, 0x2eb40d81, 0xb7bd5c3b, 0xc0ba6cad, + 0xedb88320, 0x9abfb3b6, 0x03b6e20c, 0x74b1d29a, 0xead54739, 0x9dd277af, 0x04db2615, 0x73dc1683, + 0xe3630b12, 0x94643b84, 0x0d6d6a3e, 0x7a6a5aa8, 0xe40ecf0b, 0x9309ff9d, 0x0a00ae27, 0x7d079eb1, + 0xf00f9344, 0x8708a3d2, 0x1e01f268, 0x6906c2fe, 0xf762575d, 0x806567cb, 0x196c3671, 0x6e6b06e7, + 0xfed41b76, 0x89d32be0, 0x10da7a5a, 0x67dd4acc, 0xf9b9df6f, 0x8ebeeff9, 0x17b7be43, 0x60b08ed5, + 0xd6d6a3e8, 0xa1d1937e, 0x38d8c2c4, 0x4fdff252, 0xd1bb67f1, 0xa6bc5767, 0x3fb506dd, 0x48b2364b, + 0xd80d2bda, 0xaf0a1b4c, 0x36034af6, 0x41047a60, 0xdf60efc3, 0xa867df55, 0x316e8eef, 0x4669be79, + 0xcb61b38c, 0xbc66831a, 0x256fd2a0, 0x5268e236, 0xcc0c7795, 0xbb0b4703, 0x220216b9, 0x5505262f, + 0xc5ba3bbe, 0xb2bd0b28, 0x2bb45a92, 0x5cb36a04, 0xc2d7ffa7, 0xb5d0cf31, 0x2cd99e8b, 0x5bdeae1d, + 0x9b64c2b0, 0xec63f226, 0x756aa39c, 0x026d930a, 0x9c0906a9, 0xeb0e363f, 0x72076785, 0x05005713, + 0x95bf4a82, 0xe2b87a14, 0x7bb12bae, 0x0cb61b38, 0x92d28e9b, 0xe5d5be0d, 0x7cdcefb7, 0x0bdbdf21, + 0x86d3d2d4, 0xf1d4e242, 0x68ddb3f8, 0x1fda836e, 0x81be16cd, 0xf6b9265b, 0x6fb077e1, 0x18b74777, + 0x88085ae6, 0xff0f6a70, 0x66063bca, 0x11010b5c, 0x8f659eff, 0xf862ae69, 0x616bffd3, 0x166ccf45, + 0xa00ae278, 0xd70dd2ee, 0x4e048354, 0x3903b3c2, 0xa7672661, 0xd06016f7, 0x4969474d, 0x3e6e77db, + 0xaed16a4a, 0xd9d65adc, 0x40df0b66, 0x37d83bf0, 0xa9bcae53, 0xdebb9ec5, 0x47b2cf7f, 0x30b5ffe9, + 0xbdbdf21c, 0xcabac28a, 0x53b39330, 0x24b4a3a6, 0xbad03605, 0xcdd70693, 0x54de5729, 0x23d967bf, + 0xb3667a2e, 0xc4614ab8, 0x5d681b02, 0x2a6f2b94, 0xb40bbe37, 0xc30c8ea1, 0x5a05df1b, 0x2d02ef8d] + + private static let table16: [UInt16] = [0x0000, 0xC0C1, 0xC181, 0x0140, 0xC301, 0x03C0, 0x0280, 0xC241, + 0xC601, 0x06C0, 0x0780, 0xC741, 0x0500, 0xC5C1, 0xC481, 0x0440, + 0xCC01, 0x0CC0, 0x0D80, 0xCD41, 0x0F00, 0xCFC1, 0xCE81, 0x0E40, + 0x0A00, 0xCAC1, 0xCB81, 0x0B40, 0xC901, 0x09C0, 0x0880, 0xC841, + 0xD801, 0x18C0, 0x1980, 0xD941, 0x1B00, 0xDBC1, 0xDA81, 0x1A40, + 0x1E00, 0xDEC1, 0xDF81, 0x1F40, 0xDD01, 0x1DC0, 0x1C80, 0xDC41, + 0x1400, 0xD4C1, 0xD581, 0x1540, 0xD701, 0x17C0, 0x1680, 0xD641, + 0xD201, 0x12C0, 0x1380, 0xD341, 0x1100, 0xD1C1, 0xD081, 0x1040, + 0xF001, 0x30C0, 0x3180, 0xF141, 0x3300, 0xF3C1, 0xF281, 0x3240, + 0x3600, 0xF6C1, 0xF781, 0x3740, 0xF501, 0x35C0, 0x3480, 0xF441, + 0x3C00, 0xFCC1, 0xFD81, 0x3D40, 0xFF01, 0x3FC0, 0x3E80, 0xFE41, + 0xFA01, 0x3AC0, 0x3B80, 0xFB41, 0x3900, 0xF9C1, 0xF881, 0x3840, + 0x2800, 0xE8C1, 0xE981, 0x2940, 0xEB01, 0x2BC0, 0x2A80, 0xEA41, + 0xEE01, 0x2EC0, 0x2F80, 0xEF41, 0x2D00, 0xEDC1, 0xEC81, 0x2C40, + 0xE401, 0x24C0, 0x2580, 0xE541, 0x2700, 0xE7C1, 0xE681, 0x2640, + 0x2200, 0xE2C1, 0xE381, 0x2340, 0xE101, 0x21C0, 0x2080, 0xE041, + 0xA001, 0x60C0, 0x6180, 0xA141, 0x6300, 0xA3C1, 0xA281, 0x6240, + 0x6600, 0xA6C1, 0xA781, 0x6740, 0xA501, 0x65C0, 0x6480, 0xA441, + 0x6C00, 0xACC1, 0xAD81, 0x6D40, 0xAF01, 0x6FC0, 0x6E80, 0xAE41, + 0xAA01, 0x6AC0, 0x6B80, 0xAB41, 0x6900, 0xA9C1, 0xA881, 0x6840, + 0x7800, 0xB8C1, 0xB981, 0x7940, 0xBB01, 0x7BC0, 0x7A80, 0xBA41, + 0xBE01, 0x7EC0, 0x7F80, 0xBF41, 0x7D00, 0xBDC1, 0xBC81, 0x7C40, + 0xB401, 0x74C0, 0x7580, 0xB541, 0x7700, 0xB7C1, 0xB681, 0x7640, + 0x7200, 0xB2C1, 0xB381, 0x7340, 0xB101, 0x71C0, 0x7080, 0xB041, + 0x5000, 0x90C1, 0x9181, 0x5140, 0x9301, 0x53C0, 0x5280, 0x9241, + 0x9601, 0x56C0, 0x5780, 0x9741, 0x5500, 0x95C1, 0x9481, 0x5440, + 0x9C01, 0x5CC0, 0x5D80, 0x9D41, 0x5F00, 0x9FC1, 0x9E81, 0x5E40, + 0x5A00, 0x9AC1, 0x9B81, 0x5B40, 0x9901, 0x59C0, 0x5880, 0x9841, + 0x8801, 0x48C0, 0x4980, 0x8941, 0x4B00, 0x8BC1, 0x8A81, 0x4A40, + 0x4E00, 0x8EC1, 0x8F81, 0x4F40, 0x8D01, 0x4DC0, 0x4C80, 0x8C41, + 0x4400, 0x84C1, 0x8581, 0x4540, 0x8701, 0x47C0, 0x4680, 0x8641, + 0x8201, 0x42C0, 0x4380, 0x8341, 0x4100, 0x81C1, 0x8081, 0x4040] + + func crc32(_ message: Array, seed: UInt32? = nil, reflect: Bool = true) -> UInt32 { + var crc: UInt32 = seed != nil ? seed! : 0xffffffff + for chunk in BytesSequence(chunkSize: 256, data: message) { + for b in chunk { + let idx = Int((crc ^ UInt32(reflect ? b : reversed(b))) & 0xff) + crc = (crc >> 8) ^ Checksum.table32[idx] + } + } + return (reflect ? crc : reversed(crc)) ^ 0xffffffff + } + + func crc16(_ message: Array, seed: UInt16? = nil) -> UInt16 { + var crc: UInt16 = seed != nil ? seed! : 0x0000 + for chunk in BytesSequence(chunkSize: 256, data: message) { + for b in chunk { + crc = (crc >> 8) ^ Checksum.table16[Int((crc ^ UInt16(b)) & 0xFF)] + } + } + return crc + } +} + +// MARK: Public interface +public extension Checksum { + + /// Calculate CRC32 + /// + /// - parameter message: Message + /// - parameter seed: Seed value (Optional) + /// - parameter reflect: is reflect (default true) + /// + /// - returns: Calculated code + static func crc32(_ message: Array, seed: UInt32? = nil, reflect: Bool = true) -> UInt32 { + return Checksum().crc32(message, seed: seed, reflect: reflect) + } + + /// Calculate CRC16 + /// + /// - parameter message: Message + /// - parameter seed: Seed value (Optional) + /// + /// - returns: Calculated code + static func crc16(_ message: Array, seed: UInt16? = nil) -> UInt16 { + return Checksum().crc16(message, seed: seed) + } +} diff --git a/GeneralUtils/GeneralUtils/libs/CryptoSwift/Cipher.swift b/GeneralUtils/GeneralUtils/libs/CryptoSwift/Cipher.swift new file mode 100644 index 0000000..d77178b --- /dev/null +++ b/GeneralUtils/GeneralUtils/libs/CryptoSwift/Cipher.swift @@ -0,0 +1,26 @@ +// +// Cipher.swift +// CryptoSwift +// +// Created by Marcin Krzyzanowski on 29/05/16. +// Copyright © 2016 Marcin Krzyzanowski. All rights reserved. +// + +public enum CipherError: Error { + case encrypt + case decrypt +} + +public protocol Cipher: class { + /// Encrypt given bytes at once + /// + /// - parameter bytes: Plaintext data + /// - returns: Encrypted data + func encrypt(_ bytes: C) throws -> Array where C.Iterator.Element == UInt8, C.IndexDistance == Int, C.Index == Int + + /// Decrypt given bytes at once + /// + /// - parameter bytes: Ciphertext data + /// - returns: Plaintext data + func decrypt(_ bytes: C) throws -> Array where C.Iterator.Element == UInt8, C.IndexDistance == Int, C.Index == Int +} diff --git a/GeneralUtils/GeneralUtils/libs/CryptoSwift/Collection+Extension.swift b/GeneralUtils/GeneralUtils/libs/CryptoSwift/Collection+Extension.swift new file mode 100644 index 0000000..05217d1 --- /dev/null +++ b/GeneralUtils/GeneralUtils/libs/CryptoSwift/Collection+Extension.swift @@ -0,0 +1,71 @@ +// +// Collection+Extension.swift +// CryptoSwift +// +// Created by Marcin Krzyzanowski on 02/08/16. +// Copyright © 2016 Marcin Krzyzanowski. All rights reserved. +// + +extension Collection where Self.Iterator.Element == UInt8, Self.Index == Int { + + func toUInt32Array() -> Array { + var result = Array() + result.reserveCapacity(16) + for idx in stride(from: self.startIndex, to: self.endIndex, by: MemoryLayout.size) { + var val: UInt32 = 0 + val |= self.count > 3 ? UInt32(self[idx.advanced(by: 3)]) << 24 : 0 + val |= self.count > 2 ? UInt32(self[idx.advanced(by: 2)]) << 16 : 0 + val |= self.count > 1 ? UInt32(self[idx.advanced(by: 1)]) << 8 : 0 + val |= self.count > 0 ? UInt32(self[idx]) : 0 + result.append(val) + } + + return result + } + + func toUInt64Array() -> Array { + var result = Array() + result.reserveCapacity(32) + for idx in stride(from: self.startIndex, to: self.endIndex, by: MemoryLayout.size) { + var val: UInt64 = 0 + val |= self.count > 7 ? UInt64(self[idx.advanced(by: 7)]) << 56 : 0 + val |= self.count > 6 ? UInt64(self[idx.advanced(by: 6)]) << 48 : 0 + val |= self.count > 5 ? UInt64(self[idx.advanced(by: 5)]) << 40 : 0 + val |= self.count > 4 ? UInt64(self[idx.advanced(by: 4)]) << 32 : 0 + val |= self.count > 3 ? UInt64(self[idx.advanced(by: 3)]) << 24 : 0 + val |= self.count > 2 ? UInt64(self[idx.advanced(by: 2)]) << 16 : 0 + val |= self.count > 1 ? UInt64(self[idx.advanced(by: 1)]) << 8 : 0 + val |= self.count > 0 ? UInt64(self[idx.advanced(by: 0)]) << 0 : 0 + result.append(val) + } + + return result + } + + /// Initialize integer from array of bytes. Caution: may be slow! + @available(*, deprecated: 0.6.0, message: "Dont use it. Too generic to be fast") + func toInteger() -> T where T: ByteConvertible, T: BitshiftOperationsType { + if self.count == 0 { + return 0 + } + + let size = MemoryLayout.size + var bytes = self.reversed() // FIXME: check it this is equivalent of Array(...) + if bytes.count < size { + let paddingCount = size - bytes.count + if (paddingCount > 0) { + bytes += Array(repeating: 0, count: paddingCount) + } + } + + if size == 1 { + return T(truncatingBitPattern: UInt64(bytes[0])) + } + + var result: T = 0 + for byte in bytes.reversed() { + result = result << 8 | T(byte) + } + return result + } +} diff --git a/GeneralUtils/GeneralUtils/libs/CryptoSwift/Cryptors.swift b/GeneralUtils/GeneralUtils/libs/CryptoSwift/Cryptors.swift new file mode 100644 index 0000000..c9b23eb --- /dev/null +++ b/GeneralUtils/GeneralUtils/libs/CryptoSwift/Cryptors.swift @@ -0,0 +1,40 @@ +// +// Cryptors.swift +// CryptoSwift +// +// Created by Marcin Krzyzanowski on 30/08/14. +// Copyright (c) 2014 Marcin Krzyzanowski. All rights reserved. +// + +#if os(Linux) || os(Android) || os(FreeBSD) + import Glibc +#else + import Darwin +#endif + +/// Worker cryptor/decryptor of `Updatable` types +public protocol Cryptors: class { + associatedtype EncryptorType: Updatable + associatedtype DecryptorType: Updatable + + /// Cryptor suitable for encryption + func makeEncryptor() -> EncryptorType + + /// Cryptor suitable for decryption + func makeDecryptor() -> DecryptorType + + /// Generate array of random bytes. Helper function. + static func randomIV(_ blockSize: Int) -> Array +} + +extension Cryptors { + + public static func randomIV(_ blockSize: Int) -> Array { + var randomIV: Array = Array() + randomIV.reserveCapacity(blockSize) + for randomByte in RandomBytesSequence(size: blockSize) { + randomIV.append(randomByte) + } + return randomIV + } +} diff --git a/GeneralUtils/GeneralUtils/libs/CryptoSwift/Digest.swift b/GeneralUtils/GeneralUtils/libs/CryptoSwift/Digest.swift new file mode 100644 index 0000000..96378a4 --- /dev/null +++ b/GeneralUtils/GeneralUtils/libs/CryptoSwift/Digest.swift @@ -0,0 +1,73 @@ +// +// Hash.swift +// CryptoSwift +// +// Created by Marcin Krzyzanowski on 07/08/14. +// Copyright (c) 2014 Marcin Krzyzanowski. All rights reserved. +// + +@available(*, deprecated: 0.6.0, renamed: "Digest") +public typealias Hash = Digest + +/// Hash functions to calculate Digest. +public struct Digest { + + /// Calculate MD5 Digest + /// - parameter bytes: input message + /// - returns: Digest bytes + public static func md5(_ bytes: Array) -> Array { + return MD5().calculate(for: bytes) + } + + /// Calculate SHA1 Digest + /// - parameter bytes: input message + /// - returns: Digest bytes + public static func sha1(_ bytes: Array) -> Array { + return SHA1().calculate(for: bytes) + } + + /// Calculate SHA2-224 Digest + /// - parameter bytes: input message + /// - returns: Digest bytes + public static func sha224(_ bytes: Array) -> Array { + return sha2(bytes, variant: .sha224) + } + + /// Calculate SHA2-256 Digest + /// - parameter bytes: input message + /// - returns: Digest bytes + public static func sha256(_ bytes: Array) -> Array { + return sha2(bytes, variant: .sha256) + } + + /// Calculate SHA2-384 Digest + /// - parameter bytes: input message + /// - returns: Digest bytes + public static func sha384(_ bytes: Array) -> Array { + return sha2(bytes, variant: .sha384) + } + + /// Calculate SHA2-512 Digest + /// - parameter bytes: input message + /// - returns: Digest bytes + public static func sha512(_ bytes: Array) -> Array { + return sha2(bytes, variant: .sha512) + } + + /// Calculate SHA2 Digest + /// - parameter bytes: input message + /// - parameter variant: SHA-2 variant + /// - returns: Digest bytes + public static func sha2(_ bytes: Array, variant: SHA2.Variant) -> Array { + return SHA2(variant: variant).calculate(for: bytes) + } + + + /// Calculate SHA3 Digest + /// - parameter bytes: input message + /// - parameter variant: SHA-3 variant + /// - returns: Digest bytes + public static func sha3(_ bytes: Array, variant: SHA3.Variant) -> Array { + return SHA3(variant: variant).calculate(for: bytes) + } +} diff --git a/GeneralUtils/GeneralUtils/libs/CryptoSwift/DigestType.swift b/GeneralUtils/GeneralUtils/libs/CryptoSwift/DigestType.swift new file mode 100644 index 0000000..068b41a --- /dev/null +++ b/GeneralUtils/GeneralUtils/libs/CryptoSwift/DigestType.swift @@ -0,0 +1,11 @@ +// +// Digest.swift +// CryptoSwift +// +// Created by Marcin Krzyzanowski on 17/08/14. +// Copyright (c) 2014 Marcin Krzyzanowski. All rights reserved. +// + +internal protocol DigestType { + func calculate(for bytes: Array) -> Array +} diff --git a/GeneralUtils/GeneralUtils/libs/CryptoSwift/Foundation/AES+Foundation.swift b/GeneralUtils/GeneralUtils/libs/CryptoSwift/Foundation/AES+Foundation.swift new file mode 100644 index 0000000..b39b699 --- /dev/null +++ b/GeneralUtils/GeneralUtils/libs/CryptoSwift/Foundation/AES+Foundation.swift @@ -0,0 +1,20 @@ +// +// AES+Foundation.swift +// CryptoSwift +// +// Created by Marcin Krzyzanowski on 27/09/15. +// Copyright © 2015 Marcin Krzyzanowski. All rights reserved. +// + +import Foundation + +extension AES { + + public convenience init(key: String, iv: String, blockMode: BlockMode = .CBC, padding: Padding = PKCS7()) throws { + guard let kkey = key.data(using: String.Encoding.utf8, allowLossyConversion: false)?.bytes, let iiv = iv.data(using: String.Encoding.utf8, allowLossyConversion: false)?.bytes else { + throw Error.invalidKeyOrInitializationVector + } + + try self.init(key: kkey, iv: iiv, blockMode: blockMode, padding: padding) + } +} diff --git a/GeneralUtils/GeneralUtils/libs/CryptoSwift/Foundation/Blowfish+Foundation.swift b/GeneralUtils/GeneralUtils/libs/CryptoSwift/Foundation/Blowfish+Foundation.swift new file mode 100644 index 0000000..a3ff521 --- /dev/null +++ b/GeneralUtils/GeneralUtils/libs/CryptoSwift/Foundation/Blowfish+Foundation.swift @@ -0,0 +1,20 @@ +// +// Blowfish+Foundation.swift +// CryptoSwift +// +// Created by Marcin Krzyzanowski on 27/10/16. +// Copyright © 2016 Marcin Krzyzanowski. All rights reserved. +// + +import Foundation + +extension Blowfish { + + public convenience init(key: String, iv: String, blockMode: BlockMode = .CBC, padding: Padding = PKCS7()) throws { + guard let kkey = key.data(using: String.Encoding.utf8, allowLossyConversion: false)?.bytes, let iiv = iv.data(using: String.Encoding.utf8, allowLossyConversion: false)?.bytes else { + throw Error.invalidKeyOrInitializationVector + } + + try self.init(key: kkey, iv: iiv, blockMode: blockMode, padding: padding) + } +} diff --git a/GeneralUtils/GeneralUtils/libs/CryptoSwift/Foundation/CSArrayType+Foundation.swift b/GeneralUtils/GeneralUtils/libs/CryptoSwift/Foundation/CSArrayType+Foundation.swift new file mode 100644 index 0000000..b754640 --- /dev/null +++ b/GeneralUtils/GeneralUtils/libs/CryptoSwift/Foundation/CSArrayType+Foundation.swift @@ -0,0 +1,30 @@ +// +// CSArrayType+Foundation.swift +// CryptoSwift +// +// Created by Marcin Krzyzanowski on 27/04/16. +// Copyright © 2016 Marcin Krzyzanowski. All rights reserved. +// + +import Foundation + +public extension CSArrayType where Iterator.Element == UInt8 { + + public func toBase64() -> String? { + guard let bytesArray = self as? Array else { + return nil + } + + return Data(bytes: bytesArray).base64EncodedString() + } + + public init(base64: String) { + self.init() + + guard let decodedData = Data(base64Encoded: base64) else { + return + } + + self.append(contentsOf: decodedData.bytes) + } +} diff --git a/GeneralUtils/GeneralUtils/libs/CryptoSwift/Foundation/ChaCha20+Foundation.swift b/GeneralUtils/GeneralUtils/libs/CryptoSwift/Foundation/ChaCha20+Foundation.swift new file mode 100644 index 0000000..f4a49a6 --- /dev/null +++ b/GeneralUtils/GeneralUtils/libs/CryptoSwift/Foundation/ChaCha20+Foundation.swift @@ -0,0 +1,19 @@ +// +// ChaCha20+Foundation.swift +// CryptoSwift +// +// Created by Marcin Krzyzanowski on 27/09/15. +// Copyright © 2015 Marcin Krzyzanowski. All rights reserved. +// + +import Foundation + +extension ChaCha20 { + + public convenience init(key: String, iv: String) throws { + guard let kkey = key.data(using: String.Encoding.utf8, allowLossyConversion: false)?.bytes, let iiv = iv.data(using: String.Encoding.utf8, allowLossyConversion: false)?.bytes else { + throw Error.invalidKeyOrInitializationVector + } + try self.init(key: kkey, iv: iiv) + } +} diff --git a/GeneralUtils/GeneralUtils/libs/CryptoSwift/Foundation/Data+Extension.swift b/GeneralUtils/GeneralUtils/libs/CryptoSwift/Foundation/Data+Extension.swift new file mode 100644 index 0000000..f70124e --- /dev/null +++ b/GeneralUtils/GeneralUtils/libs/CryptoSwift/Foundation/Data+Extension.swift @@ -0,0 +1,82 @@ +// +// PGPDataExtension.swift +// SwiftPGP +// +// Created by Marcin Krzyzanowski on 05/07/14. +// Copyright (c) 2014 Marcin Krzyzanowski. All rights reserved. +// + +import Foundation + +extension Data { + + /// Two octet checksum as defined in RFC-4880. Sum of all octets, mod 65536 + public func checksum() -> UInt16 { + var s: UInt32 = 0 + var bytesArray = self.bytes + for i in 0 ..< bytesArray.count { + s = s + UInt32(bytesArray[i]) + } + s = s % 65536 + return UInt16(s) + } + + public func md5() -> Data { + return Data(bytes: Digest.md5(self.bytes)) + } + + public func sha1() -> Data { + return Data(bytes: Digest.sha1(self.bytes)) + } + + public func sha224() -> Data { + return Data(bytes: Digest.sha224(self.bytes)) + } + + public func sha256() -> Data { + return Data(bytes: Digest.sha256(self.bytes)) + } + + public func sha384() -> Data { + return Data(bytes: Digest.sha384(self.bytes)) + } + + public func sha512() -> Data { + return Data(bytes: Digest.sha512(self.bytes)) + } + + public func sha3(_ variant: SHA3.Variant) -> Data { + return Data(bytes: Digest.sha3(self.bytes, variant: variant)) + } + + public func crc32(seed: UInt32? = nil, reflect: Bool = true) -> Data { + return Data(bytes: Checksum.crc32(self.bytes, seed: seed, reflect: reflect).bytes()) + } + + public func crc16(seed: UInt16? = nil) -> Data { + return Data(bytes: Checksum.crc16(self.bytes, seed: seed).bytes()) + } + + public func encrypt(cipher: Cipher) throws -> Data { + return Data(bytes: try cipher.encrypt(self.bytes)) + } + + public func decrypt(cipher: Cipher) throws -> Data { + return Data(bytes: try cipher.decrypt(self.bytes)) + } + + public func authenticate(with authenticator: Authenticator) throws -> Data { + return Data(bytes: try authenticator.authenticate(self.bytes)) + } +} + +extension Data { + + public var bytes: Array { + return Array(self) + } + + public func toHexString() -> String { + return self.bytes.toHexString() + } +} diff --git a/GeneralUtils/GeneralUtils/libs/CryptoSwift/Foundation/HMAC+Foundation.swift b/GeneralUtils/GeneralUtils/libs/CryptoSwift/Foundation/HMAC+Foundation.swift new file mode 100644 index 0000000..55a335c --- /dev/null +++ b/GeneralUtils/GeneralUtils/libs/CryptoSwift/Foundation/HMAC+Foundation.swift @@ -0,0 +1,20 @@ +// +// HMAC+Foundation.swift +// CryptoSwift +// +// Created by Marcin Krzyzanowski on 12/09/16. +// Copyright © 2016 Marcin Krzyzanowski. All rights reserved. +// + +import Foundation + +extension HMAC { + + public convenience init(key: String, variant: HMAC.Variant = .md5) throws { + guard let kkey = key.data(using: String.Encoding.utf8, allowLossyConversion: false)?.bytes else { + throw Error.invalidInput + } + + self.init(key: kkey, variant: variant) + } +} diff --git a/GeneralUtils/GeneralUtils/libs/CryptoSwift/Foundation/Rabbit+Foundation.swift b/GeneralUtils/GeneralUtils/libs/CryptoSwift/Foundation/Rabbit+Foundation.swift new file mode 100644 index 0000000..5d431a4 --- /dev/null +++ b/GeneralUtils/GeneralUtils/libs/CryptoSwift/Foundation/Rabbit+Foundation.swift @@ -0,0 +1,29 @@ +// +// Rabbit+Foundation.swift +// CryptoSwift +// +// Created by Dima Kalachov on 13/11/15. +// Copyright © 2015 Marcin Krzyzanowski. All rights reserved. +// + +import Foundation + +extension Rabbit { + + public convenience init(key: String) throws { + guard let kkey = key.data(using: String.Encoding.utf8, allowLossyConversion: false)?.bytes else { + throw Error.invalidKeyOrInitializationVector + } + try self.init(key: kkey) + } + + public convenience init(key: String, iv: String) throws { + guard let kkey = key.data(using: String.Encoding.utf8, allowLossyConversion: false)?.bytes, + let iiv = iv.data(using: String.Encoding.utf8, allowLossyConversion: false)?.bytes + else { + throw Error.invalidKeyOrInitializationVector + } + + try self.init(key: kkey, iv: iiv) + } +} diff --git a/GeneralUtils/GeneralUtils/libs/CryptoSwift/Foundation/String+FoundationExtension.swift b/GeneralUtils/GeneralUtils/libs/CryptoSwift/Foundation/String+FoundationExtension.swift new file mode 100644 index 0000000..fbf2304 --- /dev/null +++ b/GeneralUtils/GeneralUtils/libs/CryptoSwift/Foundation/String+FoundationExtension.swift @@ -0,0 +1,35 @@ +// +// String+Extension.swift +// CryptoSwift +// +// Created by Marcin Krzyzanowski on 13/10/15. +// Copyright © 2015 Marcin Krzyzanowski. All rights reserved. +// + +import Foundation + +extension String { + + /// Return Base64 back to String + public func decryptBase64ToString(cipher: Cipher) throws -> String { + guard let decodedData = Data(base64Encoded: self, options: []) else { + throw CipherError.decrypt + } + + let decrypted = try decodedData.decrypt(cipher: cipher) + + if let decryptedString = String(data: decrypted, encoding: String.Encoding.utf8) { + return decryptedString + } + + throw CipherError.decrypt + } + + public func decryptBase64(cipher: Cipher) throws -> Array { + guard let decodedData = Data(base64Encoded: self, options: []) else { + throw CipherError.decrypt + } + + return try decodedData.decrypt(cipher: cipher).bytes + } +} diff --git a/GeneralUtils/GeneralUtils/libs/CryptoSwift/Foundation/Utils+Foundation.swift b/GeneralUtils/GeneralUtils/libs/CryptoSwift/Foundation/Utils+Foundation.swift new file mode 100644 index 0000000..011dc62 --- /dev/null +++ b/GeneralUtils/GeneralUtils/libs/CryptoSwift/Foundation/Utils+Foundation.swift @@ -0,0 +1,20 @@ +// +// Utils+Foundation.swift +// CryptoSwift +// +// Created by Marcin Krzyzanowski on 27/09/15. +// Copyright © 2015 Marcin Krzyzanowski. All rights reserved. +// + +import Foundation + +func perf(_ text: String, closure: () -> Void) { + let measurementStart = Date() + + closure() + + let measurementStop = Date() + let executionTime = measurementStop.timeIntervalSince(measurementStart) + + print("\(text) \(executionTime)") +} diff --git a/GeneralUtils/GeneralUtils/libs/CryptoSwift/Generics.swift b/GeneralUtils/GeneralUtils/libs/CryptoSwift/Generics.swift new file mode 100644 index 0000000..2f395e4 --- /dev/null +++ b/GeneralUtils/GeneralUtils/libs/CryptoSwift/Generics.swift @@ -0,0 +1,55 @@ +// +// Generics.swift +// CryptoSwift +// +// Created by Marcin Krzyzanowski on 02/09/14. +// Copyright (c) 2014 Marcin Krzyzanowski. All rights reserved. +// + +/** Protocol and extensions for integerFrom(bits:). Bit hakish for me, but I can't do it in any other way */ +protocol Initiable { + init(_ v: Int) + init(_ v: UInt) +} + +extension Int: Initiable {} +extension UInt: Initiable {} +extension UInt8: Initiable {} +extension UInt16: Initiable {} +extension UInt32: Initiable {} +extension UInt64: Initiable {} + +/** build bit pattern from array of bits */ +@_specialize(UInt8) +func integerFrom(_ bits: Array) -> T { + var bitPattern: T = 0 + for idx in bits.indices { + if bits[idx] == Bit.one { + let bit = T(UIntMax(1) << UIntMax(idx)) + bitPattern = bitPattern | bit + } + } + return bitPattern +} + +/// Array of bytes. Caution: don't use directly because generic is slow. +/// +/// - parameter value: integer value +/// - parameter length: length of output array. By default size of value type +/// +/// - returns: Array of bytes +func arrayOfBytes(value: T, length totalBytes: Int = MemoryLayout.size) -> Array { + let valuePointer = UnsafeMutablePointer.allocate(capacity: 1) + valuePointer.pointee = value + + let bytesPointer = UnsafeMutablePointer(OpaquePointer(valuePointer)) + var bytes = Array(repeating: 0, count: totalBytes) + for j in 0 ..< min(MemoryLayout.size, totalBytes) { + bytes[totalBytes - 1 - j] = (bytesPointer + j).pointee + } + + valuePointer.deinitialize() + valuePointer.deallocate(capacity: 1) + + return bytes +} diff --git a/GeneralUtils/GeneralUtils/libs/CryptoSwift/HMAC.swift b/GeneralUtils/GeneralUtils/libs/CryptoSwift/HMAC.swift new file mode 100644 index 0000000..48fe7e9 --- /dev/null +++ b/GeneralUtils/GeneralUtils/libs/CryptoSwift/HMAC.swift @@ -0,0 +1,99 @@ +// +// HMAC.swift +// CryptoSwift +// +// Created by Marcin Krzyzanowski on 13/01/15. +// Copyright (c) 2015 Marcin Krzyzanowski. All rights reserved. +// + +public final class HMAC: Authenticator { + + public enum Error: Swift.Error { + case authenticateError + case invalidInput + } + + public enum Variant { + case sha1, sha256, sha384, sha512, md5 + + var digestLength: Int { + switch (self) { + case .sha1: + return SHA1.digestLength + case .sha256: + return SHA2.Variant.sha256.digestLength + case .sha384: + return SHA2.Variant.sha384.digestLength + case .sha512: + return SHA2.Variant.sha512.digestLength + case .md5: + return MD5.digestLength + } + } + + func calculateHash(_ bytes: Array) -> Array? { + switch (self) { + case .sha1: + return Digest.sha1(bytes) + case .sha256: + return Digest.sha256(bytes) + case .sha384: + return Digest.sha384(bytes) + case .sha512: + return Digest.sha512(bytes) + case .md5: + return Digest.md5(bytes) + } + } + + func blockSize() -> Int { + switch self { + case .md5: + return MD5.blockSize + case .sha1, .sha256: + return 64 + case .sha384, .sha512: + return 128 + } + } + } + + var key: Array + let variant: Variant + + public init(key: Array, variant: HMAC.Variant = .md5) { + self.variant = variant + self.key = key + + if key.count > variant.blockSize() { + if let hash = variant.calculateHash(key) { + self.key = hash + } + } + + if key.count < variant.blockSize() { + self.key = ZeroPadding().add(to: key, blockSize: variant.blockSize()) + } + } + + // MARK: Authenticator + + public func authenticate(_ bytes: Array) throws -> Array { + var opad = Array(repeating: 0x5c, count: variant.blockSize()) + for idx in key.indices { + opad[idx] = key[idx] ^ opad[idx] + } + var ipad = Array(repeating: 0x36, count: variant.blockSize()) + for idx in key.indices { + ipad[idx] = key[idx] ^ ipad[idx] + } + + guard let ipadAndMessageHash = variant.calculateHash(ipad + bytes), + let result = variant.calculateHash(opad + ipadAndMessageHash) else { + throw Error.authenticateError + } + + // return Array(result[0..<10]) // 80 bits + return result + } +} diff --git a/GeneralUtils/GeneralUtils/libs/CryptoSwift/Int+Extension.swift b/GeneralUtils/GeneralUtils/libs/CryptoSwift/Int+Extension.swift new file mode 100644 index 0000000..7192ae4 --- /dev/null +++ b/GeneralUtils/GeneralUtils/libs/CryptoSwift/Int+Extension.swift @@ -0,0 +1,43 @@ +// +// IntExtension.swift +// CryptoSwift +// +// Created by Marcin Krzyzanowski on 12/08/14. +// Copyright (C) 2014 Marcin Krzyżanowski +// This software is provided 'as-is', without any express or implied warranty. +// +// In no event will the authors be held liable for any damages arising from the use of this software. +// +// Permission is granted to anyone to use this software for any purpose,including commercial applications, and to alter it and redistribute it freely, subject to the following restrictions: +// +// - The origin of this software must not be misrepresented; you must not claim that you wrote the original software. If you use this software in a product, an acknowledgment in the product documentation is required. +// - Altered source versions must be plainly marked as such, and must not be misrepresented as being the original software. +// - This notice may not be removed or altered from any source or binary distribution. + +#if os(Linux) || os(Android) || os(FreeBSD) + import Glibc +#else + import Darwin +#endif + +/* array of bits */ +extension Int { + + init(bits: [Bit]) { + self.init(bitPattern: integerFrom(bits) as UInt) + } +} + +/* array of bytes */ +extension Int { + + /** Int with collection of bytes (little-endian) */ + // init(bytes: T) where T.Iterator.Element == UInt8, T.Index == Int { + // self = bytes.toInteger() + // } + + /** Array of bytes with optional padding */ + func bytes(totalBytes: Int = MemoryLayout.size) -> Array { + return arrayOfBytes(value: self, length: totalBytes) + } +} diff --git a/GeneralUtils/GeneralUtils/libs/CryptoSwift/IntegerConvertible.swift b/GeneralUtils/GeneralUtils/libs/CryptoSwift/IntegerConvertible.swift new file mode 100644 index 0000000..78dbe32 --- /dev/null +++ b/GeneralUtils/GeneralUtils/libs/CryptoSwift/IntegerConvertible.swift @@ -0,0 +1,43 @@ +// +// IntegerConvertible.swift +// CryptoSwift +// +// Created by Marcin Krzyzanowski on 02/06/15. +// Copyright (c) 2015 Marcin Krzyzanowski. All rights reserved. +// + +protocol BitshiftOperationsType { + static func <<(lhs: Self, rhs: Self) -> Self + static func >>(lhs: Self, rhs: Self) -> Self + static func <<=(lhs: inout Self, rhs: Self) + static func >>=(lhs: inout Self, rhs: Self) +} + +protocol ByteConvertible { + init(_ value: UInt8) + init(truncatingBitPattern: UInt64) +} + +extension Int: BitshiftOperationsType, ByteConvertible {} +extension Int8: BitshiftOperationsType, ByteConvertible {} +extension Int16: BitshiftOperationsType, ByteConvertible {} +extension Int32: BitshiftOperationsType, ByteConvertible {} + +extension Int64: BitshiftOperationsType, ByteConvertible { + + init(truncatingBitPattern value: UInt64) { + self = Int64(bitPattern: value) + } +} + +extension UInt: BitshiftOperationsType, ByteConvertible {} +extension UInt8: BitshiftOperationsType, ByteConvertible {} +extension UInt16: BitshiftOperationsType, ByteConvertible {} +extension UInt32: BitshiftOperationsType, ByteConvertible {} + +extension UInt64: BitshiftOperationsType, ByteConvertible { + + init(truncatingBitPattern value: UInt64) { + self = value + } +} diff --git a/GeneralUtils/GeneralUtils/libs/CryptoSwift/MD5.swift b/GeneralUtils/GeneralUtils/libs/CryptoSwift/MD5.swift new file mode 100644 index 0000000..df1942f --- /dev/null +++ b/GeneralUtils/GeneralUtils/libs/CryptoSwift/MD5.swift @@ -0,0 +1,149 @@ +// +// MD5.swift +// CryptoSwift +// +// Created by Marcin Krzyzanowski on 06/08/14. +// Copyright (c) 2014 Marcin Krzyzanowski. All rights reserved. +// + +public final class MD5: DigestType { + static let blockSize: Int = 64 + static let digestLength: Int = 16 // 128 / 8 + fileprivate static let hashInitialValue: Array = [0x67452301, 0xefcdab89, 0x98badcfe, 0x10325476] + + fileprivate var accumulated = Array() + fileprivate var processedBytesTotalCount: Int = 0 + fileprivate var accumulatedHash: Array = MD5.hashInitialValue + + /** specifies the per-round shift amounts */ + private let s: Array = [7, 12, 17, 22, 7, 12, 17, 22, 7, 12, 17, 22, 7, 12, 17, 22, + 5, 9, 14, 20, 5, 9, 14, 20, 5, 9, 14, 20, 5, 9, 14, 20, + 4, 11, 16, 23, 4, 11, 16, 23, 4, 11, 16, 23, 4, 11, 16, 23, + 6, 10, 15, 21, 6, 10, 15, 21, 6, 10, 15, 21, 6, 10, 15, 21] + + /** binary integer part of the sines of integers (Radians) */ + private let k: Array = [0xd76aa478, 0xe8c7b756, 0x242070db, 0xc1bdceee, + 0xf57c0faf, 0x4787c62a, 0xa8304613, 0xfd469501, + 0x698098d8, 0x8b44f7af, 0xffff5bb1, 0x895cd7be, + 0x6b901122, 0xfd987193, 0xa679438e, 0x49b40821, + 0xf61e2562, 0xc040b340, 0x265e5a51, 0xe9b6c7aa, + 0xd62f105d, 0x2441453, 0xd8a1e681, 0xe7d3fbc8, + 0x21e1cde6, 0xc33707d6, 0xf4d50d87, 0x455a14ed, + 0xa9e3e905, 0xfcefa3f8, 0x676f02d9, 0x8d2a4c8a, + 0xfffa3942, 0x8771f681, 0x6d9d6122, 0xfde5380c, + 0xa4beea44, 0x4bdecfa9, 0xf6bb4b60, 0xbebfbc70, + 0x289b7ec6, 0xeaa127fa, 0xd4ef3085, 0x4881d05, + 0xd9d4d039, 0xe6db99e5, 0x1fa27cf8, 0xc4ac5665, + 0xf4292244, 0x432aff97, 0xab9423a7, 0xfc93a039, + 0x655b59c3, 0x8f0ccc92, 0xffeff47d, 0x85845dd1, + 0x6fa87e4f, 0xfe2ce6e0, 0xa3014314, 0x4e0811a1, + 0xf7537e82, 0xbd3af235, 0x2ad7d2bb, 0xeb86d391] + + public init() { + } + + public func calculate(for bytes: Array) -> Array { + do { + return try self.update(withBytes: bytes, isLast: true) + } catch { + fatalError() + } + } + + // mutating currentHash in place is way faster than returning new result + fileprivate func process(block chunk: ArraySlice, currentHash: inout Array) { + + // break chunk into sixteen 32-bit words M[j], 0 ≤ j ≤ 15 + var M = chunk.toUInt32Array() + assert(M.count == 16, "Invalid array") + + // Initialize hash value for this chunk: + var A: UInt32 = currentHash[0] + var B: UInt32 = currentHash[1] + var C: UInt32 = currentHash[2] + var D: UInt32 = currentHash[3] + + var dTemp: UInt32 = 0 + + // Main loop + for j in 0 ..< k.count { + var g = 0 + var F: UInt32 = 0 + + switch (j) { + case 0 ... 15: + F = (B & C) | ((~B) & D) + g = j + break + case 16 ... 31: + F = (D & B) | (~D & C) + g = (5 * j + 1) % 16 + break + case 32 ... 47: + F = B ^ C ^ D + g = (3 * j + 5) % 16 + break + case 48 ... 63: + F = C ^ (B | (~D)) + g = (7 * j) % 16 + break + default: + break + } + dTemp = D + D = C + C = B + B = B &+ rotateLeft(A &+ F &+ k[j] &+ M[g], by: s[j]) + A = dTemp + } + + currentHash[0] = currentHash[0] &+ A + currentHash[1] = currentHash[1] &+ B + currentHash[2] = currentHash[2] &+ C + currentHash[3] = currentHash[3] &+ D + } +} + +extension MD5: Updatable { + + public func update(withBytes bytes: T, isLast: Bool = false) throws -> Array where T.Iterator.Element == UInt8 { + self.accumulated += bytes + + if isLast { + let lengthInBits = (self.processedBytesTotalCount + self.accumulated.count) * 8 + let lengthBytes = lengthInBits.bytes(totalBytes: 64 / 8) // A 64-bit representation of b + + // Step 1. Append padding + bitPadding(to: &self.accumulated, blockSize: MD5.blockSize, allowance: 64 / 8) + + // Step 2. Append Length a 64-bit representation of lengthInBits + self.accumulated += lengthBytes.reversed() + } + + var processedBytes = 0 + for chunk in BytesSequence(chunkSize: MD5.blockSize, data: self.accumulated) { + if (isLast || (self.accumulated.count - processedBytes) >= MD5.blockSize) { + self.process(block: chunk, currentHash: &self.accumulatedHash) + processedBytes += chunk.count + } + } + self.accumulated.removeFirst(processedBytes) + self.processedBytesTotalCount += processedBytes + + // output current hash + var result = Array() + result.reserveCapacity(MD5.digestLength) + + for hElement in self.accumulatedHash { + let hLE = hElement.littleEndian + result += [UInt8(hLE & 0xff), UInt8((hLE >> 8) & 0xff), UInt8((hLE >> 16) & 0xff), UInt8((hLE >> 24) & 0xff)] + } + + // reset hash value for instance + if isLast { + self.accumulatedHash = MD5.hashInitialValue + } + + return result + } +} diff --git a/GeneralUtils/GeneralUtils/libs/CryptoSwift/NoPadding.swift b/GeneralUtils/GeneralUtils/libs/CryptoSwift/NoPadding.swift new file mode 100644 index 0000000..08c3f82 --- /dev/null +++ b/GeneralUtils/GeneralUtils/libs/CryptoSwift/NoPadding.swift @@ -0,0 +1,21 @@ +// +// NoPadding.swift +// CryptoSwift +// +// Created by Marcin Krzyzanowski on 02/04/16. +// Copyright © 2016 Marcin Krzyzanowski. All rights reserved. +// + +public struct NoPadding: Padding { + + public init() { + } + + public func add(to data: Array, blockSize: Int) -> Array { + return data + } + + public func remove(from data: Array, blockSize: Int?) -> Array { + return data + } +} diff --git a/GeneralUtils/GeneralUtils/libs/CryptoSwift/PKCS5/PBKDF1.swift b/GeneralUtils/GeneralUtils/libs/CryptoSwift/PKCS5/PBKDF1.swift new file mode 100644 index 0000000..e890860 --- /dev/null +++ b/GeneralUtils/GeneralUtils/libs/CryptoSwift/PKCS5/PBKDF1.swift @@ -0,0 +1,84 @@ +// +// PBKDF1.swift +// CryptoSwift +// +// Created by Marcin Krzyzanowski on 07/06/16. +// Copyright © 2016 Marcin Krzyzanowski. All rights reserved. +// + +public extension PKCS5 { + + /// A key derivation function. + /// + /// PBKDF1 is recommended only for compatibility with existing + /// applications since the keys it produces may not be large enough for + /// some applications. + public struct PBKDF1 { + + public enum Error: Swift.Error { + case invalidInput + case derivedKeyTooLong + } + + public enum Variant { + case md5, sha1 + + var size: Int { + switch (self) { + case .md5: + return MD5.digestLength + case .sha1: + return SHA1.digestLength + } + } + + fileprivate func calculateHash(_ bytes: Array) -> Array? { + switch (self) { + case .sha1: + return Digest.sha1(bytes) + case .md5: + return Digest.md5(bytes) + } + } + } + + private let iterations: Int // c + private let variant: Variant + private let keyLength: Int + private let t1: Array + + /// - parameters: + /// - salt: salt, an eight-bytes + /// - variant: hash variant + /// - iterations: iteration count, a positive integer + /// - keyLength: intended length of derived key + public init(password: Array, salt: Array, variant: Variant = .sha1, iterations: Int = 4096 /* c */ , keyLength: Int? = nil /* dkLen */ ) throws { + precondition(iterations > 0) + precondition(salt.count == 8) + + let keyLength = keyLength ?? variant.size + + if (keyLength > variant.size) { + throw Error.derivedKeyTooLong + } + + guard let t1 = variant.calculateHash(password + salt) else { + throw Error.invalidInput + } + + self.iterations = iterations + self.variant = variant + self.keyLength = keyLength + self.t1 = t1 + } + + /// Apply the underlying hash function Hash for c iterations + public func calculate() -> Array { + var t = t1 + for _ in 2 ... self.iterations { + t = self.variant.calculateHash(t)! + } + return Array(t[0 ..< self.keyLength]) + } + } +} diff --git a/GeneralUtils/GeneralUtils/libs/CryptoSwift/PKCS5/PBKDF2.swift b/GeneralUtils/GeneralUtils/libs/CryptoSwift/PKCS5/PBKDF2.swift new file mode 100644 index 0000000..3a0d817 --- /dev/null +++ b/GeneralUtils/GeneralUtils/libs/CryptoSwift/PKCS5/PBKDF2.swift @@ -0,0 +1,110 @@ +// +// PBKDF2.swift +// CryptoSwift +// +// Created by Marcin Krzyzanowski on 05/04/16. +// Copyright © 2016 Marcin Krzyzanowski. All rights reserved. +// +// https://www.ietf.org/rfc/rfc2898.txt +// + +#if os(Linux) || os(Android) || os(FreeBSD) + import Glibc +#else + import Darwin +#endif + +public extension PKCS5 { + + /// A key derivation function. + /// + /// PBKDF2 - Password-Based Key Derivation Function 2. Key stretching technique. + /// DK = PBKDF2(PRF, Password, Salt, c, dkLen) + public struct PBKDF2 { + + public enum Error: Swift.Error { + case invalidInput + case derivedKeyTooLong + } + + private let salt: Array // S + fileprivate let iterations: Int // c + private let numBlocks: Int // l + private let dkLen: Int + fileprivate let prf: HMAC + + /// - parameters: + /// - salt: salt + /// - variant: hash variant + /// - iterations: iteration count, a positive integer + /// - keyLength: intended length of derived key + public init(password: Array, salt: Array, iterations: Int = 4096 /* c */ , keyLength: Int? = nil /* dkLen */ , variant: HMAC.Variant = .sha256) throws { + precondition(iterations > 0) + + let prf = HMAC(key: password, variant: variant) + + guard iterations > 0 && !password.isEmpty && !salt.isEmpty else { + throw Error.invalidInput + } + + self.dkLen = keyLength ?? variant.digestLength + let keyLengthFinal = Double(self.dkLen) + let hLen = Double(prf.variant.digestLength) + if keyLengthFinal > (pow(2, 32) - 1) * hLen { + throw Error.derivedKeyTooLong + } + + self.salt = salt + self.iterations = iterations + self.prf = prf + + self.numBlocks = Int(ceil(Double(keyLengthFinal) / hLen)) // l = ceil(keyLength / hLen) + } + + public func calculate() throws -> Array { + var ret = Array() + ret.reserveCapacity(self.numBlocks * self.prf.variant.digestLength) + for i in 1 ... self.numBlocks { + // for each block T_i = U_1 ^ U_2 ^ ... ^ U_iter + if let value = try calculateBlock(self.salt, blockNum: i) { + ret.append(contentsOf: value) + } + } + return Array(ret.prefix(self.dkLen)) + } + } +} + +fileprivate extension PKCS5.PBKDF2 { + + func ARR(_ i: Int) -> Array { + var inti = Array(repeating: 0, count: 4) + inti[0] = UInt8((i >> 24) & 0xFF) + inti[1] = UInt8((i >> 16) & 0xFF) + inti[2] = UInt8((i >> 8) & 0xFF) + inti[3] = UInt8(i & 0xFF) + return inti + } + + // F (P, S, c, i) = U_1 \xor U_2 \xor ... \xor U_c + // U_1 = PRF (P, S || INT (i)) + func calculateBlock(_ salt: Array, blockNum: Int) throws -> Array? { + guard let u1 = try? prf.authenticate(salt + ARR(blockNum)) else { // blockNum.bytes() is slower + return nil + } + + var u = u1 + var ret = u + if self.iterations > 1 { + // U_2 = PRF (P, U_1) , + // U_c = PRF (P, U_{c-1}) . + for _ in 2 ... self.iterations { + u = try prf.authenticate(u) + for x in 0 ..< ret.count { + ret[x] = ret[x] ^ u[x] + } + } + } + return ret + } +} diff --git a/GeneralUtils/GeneralUtils/libs/CryptoSwift/PKCS5/PKCS5.swift b/GeneralUtils/GeneralUtils/libs/CryptoSwift/PKCS5/PKCS5.swift new file mode 100644 index 0000000..c8e8b43 --- /dev/null +++ b/GeneralUtils/GeneralUtils/libs/CryptoSwift/PKCS5/PKCS5.swift @@ -0,0 +1,14 @@ +// +// PKCS.swift +// CryptoSwift +// +// Created by Marcin Krzyzanowski on 12/03/15. +// Copyright (c) 2015 Marcin Krzyzanowski. All rights reserved. +// +// PKCS is a group of public-key cryptography standards devised +// and published by RSA Security Inc, starting in the early 1990s. +// + +public enum PKCS5 { + // PKCS#5 http://tools.ietf.org/html/rfc2898 +} diff --git a/GeneralUtils/GeneralUtils/libs/CryptoSwift/PKCS7.swift b/GeneralUtils/GeneralUtils/libs/CryptoSwift/PKCS7.swift new file mode 100644 index 0000000..1ccac59 --- /dev/null +++ b/GeneralUtils/GeneralUtils/libs/CryptoSwift/PKCS7.swift @@ -0,0 +1,57 @@ +// +// PKCS7.swift +// CryptoSwift +// +// Created by Marcin Krzyzanowski on 28/02/15. +// Copyright (c) 2015 Marcin Krzyzanowski. All rights reserved. +// +// PKCS is a group of public-key cryptography standards devised +// and published by RSA Security Inc, starting in the early 1990s. +// + +public struct PKCS7: Padding { + + public enum Error: Swift.Error { + case invalidPaddingValue + } + + public init() { + } + + public func add(to bytes: Array, blockSize: Int) -> Array { + let padding = UInt8(blockSize - (bytes.count % blockSize)) + var withPadding = bytes + if (padding == 0) { + // If the original data is a multiple of N bytes, then an extra block of bytes with value N is added. + for _ in 0 ..< blockSize { + withPadding += [UInt8(blockSize)] + } + } else { + // The value of each added byte is the number of bytes that are added + for _ in 0 ..< padding { + withPadding += [UInt8(padding)] + } + } + return withPadding + } + + public func remove(from bytes: Array, blockSize: Int?) -> Array { + guard !bytes.isEmpty, let lastByte = bytes.last else { + return bytes + } + + assert(!bytes.isEmpty, "Need bytes to remove padding") + + let padding = Int(lastByte) // last byte + let finalLength = bytes.count - padding + + if finalLength < 0 { + return bytes + } + + if padding >= 1 { + return Array(bytes[0 ..< finalLength]) + } + return bytes + } +} diff --git a/GeneralUtils/GeneralUtils/libs/CryptoSwift/Padding.swift b/GeneralUtils/GeneralUtils/libs/CryptoSwift/Padding.swift new file mode 100644 index 0000000..659c5cb --- /dev/null +++ b/GeneralUtils/GeneralUtils/libs/CryptoSwift/Padding.swift @@ -0,0 +1,12 @@ +// +// Padding.swift +// CryptoSwift +// +// Created by Marcin Krzyzanowski on 27/02/15. +// Copyright (c) 2015 Marcin Krzyzanowski. All rights reserved. +// + +public protocol Padding { + func add(to: Array, blockSize: Int) -> Array + func remove(from: Array, blockSize: Int?) -> Array +} diff --git a/GeneralUtils/GeneralUtils/libs/CryptoSwift/Poly1305.swift b/GeneralUtils/GeneralUtils/libs/CryptoSwift/Poly1305.swift new file mode 100644 index 0000000..c5324a0 --- /dev/null +++ b/GeneralUtils/GeneralUtils/libs/CryptoSwift/Poly1305.swift @@ -0,0 +1,159 @@ +// +// Poly1305.swift +// CryptoSwift +// +// Created by Marcin Krzyzanowski on 30/08/14. +// Copyright (c) 2014 Marcin Krzyzanowski. All rights reserved. +// +// http://tools.ietf.org/html/draft-agl-tls-chacha20poly1305-04#section-4 +// nacl/crypto_onetimeauth/poly1305/ref/auth.c +// +/// Poly1305 takes a 32-byte, one-time key and a message and produces a 16-byte tag that authenticates the +/// message such that an attacker has a negligible chance of producing a valid tag for an inauthentic message. + +public final class Poly1305: Authenticator { + + public enum Error: Swift.Error { + case authenticateError + } + + public static let blockSize: Int = 16 + + private let key: SecureBytes + + /// - parameter key: 32-byte key + public init(key: Array) { + self.key = SecureBytes(bytes: key) + } + + private func squeeze(h: inout Array) { + assert(h.count == 17) + var u: UInt32 = 0 + for j in 0..<16 { + u = u &+ h[j] + h[j] = u & 255 + u = u >> 8 + } + + u = u &+ h[16] + h[16] = u & 3 + u = 5 * (u >> 2) + + for j in 0..<16 { + u = u &+ h[j] + h[j] = u & 255 + u = u >> 8 + } + + u = u &+ h[16] + h[16] = u + } + + private func add(h: inout Array, c: Array) { + assert(h.count == 17 && c.count == 17) + + var u: UInt32 = 0 + for j in 0..<17 { + u = u &+ (h[j] &+ c[j]) + h[j] = u & 255 + u = u >> 8 + } + } + + private func mulmod(h: inout Array, r: Array) { + var hr = Array(repeating: 0, count: 17) + var u: UInt32 = 0 + for i in 0..<17 { + u = 0 + for j in 0...i { + u = u &+ (h[j] * r[i &- j]) + } + for j in (i + 1)..<17 { + u = u &+ (320 * h[j] * r[i &+ 17 &- j]) + } + hr[i] = u + } + h = hr + self.squeeze(h: &h) + } + + private func freeze(h: inout Array) { + let horig = h + add(h: &h, c: [5, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 252]) + let negative = UInt32(bitPattern: -Int32(h[16] >> 7)) + for j in 0..<17 { + h[j] ^= negative & (horig[j] ^ h[j]) + } + } + + /// the key is partitioned into two parts, called "r" and "s" + fileprivate func onetimeauth(message input: Array, key k: Array) -> Array { + // clamp + var r = Array(repeating: 0, count: 17) + var h = Array(repeating: 0, count: 17) + var c = Array(repeating: 0, count: 17) + + r[0] = UInt32(k[0]) + r[1] = UInt32(k[1]) + r[2] = UInt32(k[2]) + r[3] = UInt32(k[3] & 15) + r[4] = UInt32(k[4] & 252) + r[5] = UInt32(k[5]) + r[6] = UInt32(k[6]) + r[7] = UInt32(k[7] & 15) + r[8] = UInt32(k[8] & 252) + r[9] = UInt32(k[9]) + r[10] = UInt32(k[10]) + r[11] = UInt32(k[11] & 15) + r[12] = UInt32(k[12] & 252) + r[13] = UInt32(k[13]) + r[14] = UInt32(k[14]) + r[15] = UInt32(k[15] & 15) + r[16] = 0 + + + var inlen = input.count + var inpos = 0 + while inlen > 0 { + for j in 0..) throws -> Array { + return onetimeauth(message: bytes, key: Array(self.key)) + } +} diff --git a/GeneralUtils/GeneralUtils/libs/CryptoSwift/Rabbit.swift b/GeneralUtils/GeneralUtils/libs/CryptoSwift/Rabbit.swift new file mode 100644 index 0000000..4e17419 --- /dev/null +++ b/GeneralUtils/GeneralUtils/libs/CryptoSwift/Rabbit.swift @@ -0,0 +1,207 @@ +// +// Rabbit.swift +// CryptoSwift +// +// Created by Dima Kalachov on 12/11/15. +// Copyright © 2015 Marcin Krzyzanowski. All rights reserved. +// + +private typealias Key = SecureBytes + +public final class Rabbit: BlockCipher { + + public enum Error: Swift.Error { + case invalidKeyOrInitializationVector + } + + /// Size of IV in bytes + public static let ivSize = 64 / 8 + + /// Size of key in bytes + public static let keySize = 128 / 8 + + /// Size of block in bytes + public static let blockSize = 128 / 8 + + /// Key + private let key: Key + + /// IV (optional) + private let iv: Array? + + /// State variables + private var x = Array(repeating: 0, count: 8) + + /// Counter variables + private var c = Array(repeating: 0, count: 8) + + /// Counter carry + private var p7: UInt32 = 0 + + /// 'a' constants + private var a: Array = [ + 0x4D34D34D, + 0xD34D34D3, + 0x34D34D34, + 0x4D34D34D, + 0xD34D34D3, + 0x34D34D34, + 0x4D34D34D, + 0xD34D34D3, + ] + + // MARK: - Initializers + public convenience init(key: Array) throws { + try self.init(key: key, iv: nil) + } + + public init(key: Array, iv: Array?) throws { + self.key = Key(bytes: key) + self.iv = iv + + guard key.count == Rabbit.keySize && (iv == nil || iv!.count == Rabbit.ivSize) else { + throw Error.invalidKeyOrInitializationVector + } + } + + // MARK: - + fileprivate func setup() { + p7 = 0 + + // Key divided into 8 subkeys + var k = Array(repeating: 0, count: 8) + for j in 0 ..< 8 { + k[j] = UInt32(key[Rabbit.blockSize - (2 * j + 1)]) | (UInt32(key[Rabbit.blockSize - (2 * j + 2)]) << 8) + } + + // Initialize state and counter variables from subkeys + for j in 0 ..< 8 { + if j % 2 == 0 { + x[j] = (k[(j + 1) % 8] << 16) | k[j] + c[j] = (k[(j + 4) % 8] << 16) | k[(j + 5) % 8] + } else { + x[j] = (k[(j + 5) % 8] << 16) | k[(j + 4) % 8] + c[j] = (k[j] << 16) | k[(j + 1) % 8] + } + } + + // Iterate system four times + nextState() + nextState() + nextState() + nextState() + + // Reinitialize counter variables + for j in 0 ..< 8 { + c[j] = c[j] ^ x[(j + 4) % 8] + } + + if let iv = iv { + setupIV(iv) + } + } + + private func setupIV(_ iv: Array) { + // 63...56 55...48 47...40 39...32 31...24 23...16 15...8 7...0 IV bits + // 0 1 2 3 4 5 6 7 IV bytes in array + let iv0 = UInt32(bytes: [iv[4], iv[5], iv[6], iv[7]]) + let iv1 = UInt32(bytes: [iv[0], iv[1], iv[4], iv[5]]) + let iv2 = UInt32(bytes: [iv[0], iv[1], iv[2], iv[3]]) + let iv3 = UInt32(bytes: [iv[2], iv[3], iv[6], iv[7]]) + + // Modify the counter state as function of the IV + c[0] = c[0] ^ iv0 + c[1] = c[1] ^ iv1 + c[2] = c[2] ^ iv2 + c[3] = c[3] ^ iv3 + c[4] = c[4] ^ iv0 + c[5] = c[5] ^ iv1 + c[6] = c[6] ^ iv2 + c[7] = c[7] ^ iv3 + + // Iterate system four times + nextState() + nextState() + nextState() + nextState() + } + + private func nextState() { + // Before an iteration the counters are incremented + var carry = p7 + for j in 0 ..< 8 { + let prev = c[j] + c[j] = prev &+ a[j] &+ carry + carry = prev > c[j] ? 1 : 0 // detect overflow + } + p7 = carry // save last carry bit + + // Iteration of the system + var newX = Array(repeating: 0, count: 8) + newX[0] = g(0) &+ rotateLeft(g(7), by: 16) &+ rotateLeft(g(6), by: 16) + newX[1] = g(1) &+ rotateLeft(g(0), by: 8) &+ g(7) + newX[2] = g(2) &+ rotateLeft(g(1), by: 16) &+ rotateLeft(g(0), by: 16) + newX[3] = g(3) &+ rotateLeft(g(2), by: 8) &+ g(1) + newX[4] = g(4) &+ rotateLeft(g(3), by: 16) &+ rotateLeft(g(2), by: 16) + newX[5] = g(5) &+ rotateLeft(g(4), by: 8) &+ g(3) + newX[6] = g(6) &+ rotateLeft(g(5), by: 16) &+ rotateLeft(g(4), by: 16) + newX[7] = g(7) &+ rotateLeft(g(6), by: 8) &+ g(5) + x = newX + } + + private func g(_ j: Int) -> UInt32 { + let sum = x[j] &+ c[j] + let square = UInt64(sum) * UInt64(sum) + return UInt32(truncatingBitPattern: square ^ (square >> 32)) + } + + fileprivate func nextOutput() -> Array { + nextState() + + var output16 = [UInt16](repeating: 0, count: Rabbit.blockSize / 2) + output16[7] = UInt16(truncatingBitPattern: x[0]) ^ UInt16(truncatingBitPattern: x[5] >> 16) + output16[6] = UInt16(truncatingBitPattern: x[0] >> 16) ^ UInt16(truncatingBitPattern: x[3]) + output16[5] = UInt16(truncatingBitPattern: x[2]) ^ UInt16(truncatingBitPattern: x[7] >> 16) + output16[4] = UInt16(truncatingBitPattern: x[2] >> 16) ^ UInt16(truncatingBitPattern: x[5]) + output16[3] = UInt16(truncatingBitPattern: x[4]) ^ UInt16(truncatingBitPattern: x[1] >> 16) + output16[2] = UInt16(truncatingBitPattern: x[4] >> 16) ^ UInt16(truncatingBitPattern: x[7]) + output16[1] = UInt16(truncatingBitPattern: x[6]) ^ UInt16(truncatingBitPattern: x[3] >> 16) + output16[0] = UInt16(truncatingBitPattern: x[6] >> 16) ^ UInt16(truncatingBitPattern: x[1]) + + var output8 = Array(repeating: 0, count: Rabbit.blockSize) + for j in 0 ..< output16.count { + output8[j * 2] = UInt8(truncatingBitPattern: output16[j] >> 8) + output8[j * 2 + 1] = UInt8(truncatingBitPattern: output16[j]) + } + return output8 + } +} + +// MARK: Cipher +extension Rabbit: Cipher { + + public func encrypt(_ bytes: C) -> Array where C.Iterator.Element == UInt8, C.IndexDistance == Int, C.Index == Int { + setup() + + var result = Array(repeating: 0, count: bytes.count) + var output = nextOutput() + var byteIdx = 0 + var outputIdx = 0 + while byteIdx < bytes.count { + if (outputIdx == Rabbit.blockSize) { + output = nextOutput() + outputIdx = 0 + } + + result[byteIdx] = bytes[byteIdx] ^ output[outputIdx] + + byteIdx += 1 + outputIdx += 1 + } + return result + } + + public func decrypt(_ bytes: C) -> Array where C.Iterator.Element == UInt8, C.IndexDistance == Int, C.Index == Int { + return encrypt(bytes) + } +} diff --git a/GeneralUtils/GeneralUtils/libs/CryptoSwift/RandomAccessCryptor.swift b/GeneralUtils/GeneralUtils/libs/CryptoSwift/RandomAccessCryptor.swift new file mode 100644 index 0000000..d81ff66 --- /dev/null +++ b/GeneralUtils/GeneralUtils/libs/CryptoSwift/RandomAccessCryptor.swift @@ -0,0 +1,17 @@ +// +// RandomAccessCryptor.swift +// CryptoSwift +// +// Created by Marcin Krzyzanowski on 29/07/16. +// Copyright © 2016 Marcin Krzyzanowski. All rights reserved. +// + +/// Random access cryptor +public protocol RandomAccessCryptor: Updatable { + /// Seek to position in file, if block mode allows random access. + /// + /// - parameter to: new value of counter + /// + /// - returns: true if seek succeed + @discardableResult mutating func seek(to: Int) -> Bool +} diff --git a/GeneralUtils/GeneralUtils/libs/CryptoSwift/RandomBytesSequence.swift b/GeneralUtils/GeneralUtils/libs/CryptoSwift/RandomBytesSequence.swift new file mode 100644 index 0000000..856d5bd --- /dev/null +++ b/GeneralUtils/GeneralUtils/libs/CryptoSwift/RandomBytesSequence.swift @@ -0,0 +1,43 @@ +// +// RandomBytesSequence.swift +// CryptoSwift +// +// Created by Marcin Krzyzanowski on 10/10/16. +// Copyright © 2016 Marcin Krzyzanowski. All rights reserved. +// + +#if os(Linux) || os(Android) || os(FreeBSD) + import Glibc +#else + import Darwin +#endif + +struct RandomBytesSequence: Sequence { + let size: Int + + func makeIterator() -> AnyIterator { + var count = 0 + return AnyIterator.init({ () -> UInt8? in + if count >= self.size { + return nil + } + count = count + 1 + + #if os(Linux) || os(Android) || os(FreeBSD) + let fd = open("/dev/urandom", O_RDONLY) + if fd <= 0 { + return nil + } + + var value: UInt8 = 0 + let result = read(fd, &value, MemoryLayout.size) + precondition(result == 1) + + close(fd) + return value + #else + return UInt8(arc4random_uniform(UInt32(UInt8.max) + 1)) + #endif + }) + } +} diff --git a/GeneralUtils/GeneralUtils/libs/CryptoSwift/SHA1.swift b/GeneralUtils/GeneralUtils/libs/CryptoSwift/SHA1.swift new file mode 100644 index 0000000..a1618d8 --- /dev/null +++ b/GeneralUtils/GeneralUtils/libs/CryptoSwift/SHA1.swift @@ -0,0 +1,138 @@ +// +// SHA1.swift +// CryptoSwift +// +// Created by Marcin Krzyzanowski on 16/08/14. +// Copyright (c) 2014 Marcin Krzyzanowski. All rights reserved. +// + +public final class SHA1: DigestType { + static let digestLength: Int = 20 // 160 / 8 + static let blockSize: Int = 64 + fileprivate static let hashInitialValue: ContiguousArray = [0x67452301, 0xEFCDAB89, 0x98BADCFE, 0x10325476, 0xC3D2E1F0] + + fileprivate var accumulated = Array() + fileprivate var processedBytesTotalCount: Int = 0 + fileprivate var accumulatedHash: ContiguousArray = SHA1.hashInitialValue + + public init() { + } + + public func calculate(for bytes: Array) -> Array { + do { + return try self.update(withBytes: bytes, isLast: true) + } catch { + return [] + } + } + + fileprivate func process(block chunk: ArraySlice, currentHash hh: inout ContiguousArray) { + // break chunk into sixteen 32-bit words M[j], 0 ≤ j ≤ 15, big-endian + // Extend the sixteen 32-bit words into eighty 32-bit words: + var M = ContiguousArray(repeating: 0, count: 80) + for x in 0 ..< M.count { + switch x { + case 0 ... 15: + let start = chunk.startIndex.advanced(by: x * 4) // * MemoryLayout.size + M[x] = UInt32(bytes: chunk, fromIndex: start) + break + default: + M[x] = rotateLeft(M[x - 3] ^ M[x - 8] ^ M[x - 14] ^ M[x - 16], by: 1) + break + } + } + + var A = hh[0] + var B = hh[1] + var C = hh[2] + var D = hh[3] + var E = hh[4] + + // Main loop + for j in 0 ... 79 { + var f: UInt32 = 0 + var k: UInt32 = 0 + + switch (j) { + case 0 ... 19: + f = (B & C) | ((~B) & D) + k = 0x5A827999 + break + case 20 ... 39: + f = B ^ C ^ D + k = 0x6ED9EBA1 + break + case 40 ... 59: + f = (B & C) | (B & D) | (C & D) + k = 0x8F1BBCDC + break + case 60 ... 79: + f = B ^ C ^ D + k = 0xCA62C1D6 + break + default: + break + } + + let temp = (rotateLeft(A, by: 5) &+ f &+ E &+ M[j] &+ k) & 0xffffffff + E = D + D = C + C = rotateLeft(B, by: 30) + B = A + A = temp + } + + hh[0] = (hh[0] &+ A) & 0xffffffff + hh[1] = (hh[1] &+ B) & 0xffffffff + hh[2] = (hh[2] &+ C) & 0xffffffff + hh[3] = (hh[3] &+ D) & 0xffffffff + hh[4] = (hh[4] &+ E) & 0xffffffff + } +} + +extension SHA1: Updatable { + + public func update(withBytes bytes: T, isLast: Bool = false) throws -> Array where T.Iterator.Element == UInt8 { + self.accumulated += bytes + + if isLast { + let lengthInBits = (self.processedBytesTotalCount + self.accumulated.count) * 8 + let lengthBytes = lengthInBits.bytes(totalBytes: 64 / 8) // A 64-bit representation of b + + // Step 1. Append padding + bitPadding(to: &self.accumulated, blockSize: SHA1.blockSize, allowance: 64 / 8) + + // Step 2. Append Length a 64-bit representation of lengthInBits + self.accumulated += lengthBytes + } + + var processedBytes = 0 + for chunk in BytesSequence(chunkSize: SHA1.blockSize, data: self.accumulated) { + if (isLast || (self.accumulated.count - processedBytes) >= SHA1.blockSize) { + self.process(block: chunk, currentHash: &self.accumulatedHash) + processedBytes += chunk.count + } + } + self.accumulated.removeFirst(processedBytes) + self.processedBytesTotalCount += processedBytes + + // output current hash + var result = Array(repeating: 0, count: SHA1.digestLength) + var pos = 0 + for idx in 0 ..< self.accumulatedHash.count { + let h = self.accumulatedHash[idx].bigEndian + result[pos] = UInt8(h & 0xff) + result[pos + 1] = UInt8((h >> 8) & 0xff) + result[pos + 2] = UInt8((h >> 16) & 0xff) + result[pos + 3] = UInt8((h >> 24) & 0xff) + pos += 4 + } + + // reset hash value for instance + if isLast { + self.accumulatedHash = SHA1.hashInitialValue + } + + return result + } +} diff --git a/GeneralUtils/GeneralUtils/libs/CryptoSwift/SHA2.swift b/GeneralUtils/GeneralUtils/libs/CryptoSwift/SHA2.swift new file mode 100644 index 0000000..cd60b02 --- /dev/null +++ b/GeneralUtils/GeneralUtils/libs/CryptoSwift/SHA2.swift @@ -0,0 +1,331 @@ +// +// SHA2.swift +// CryptoSwift +// +// Created by Marcin Krzyzanowski on 24/08/14. +// Copyright (c) 2014 Marcin Krzyzanowski. All rights reserved. +// +// TODO: generic for process32/64 (UInt32/UInt64) +// + +public final class SHA2: DigestType { + let variant: Variant + let size: Int + let blockSize: Int + let digestLength: Int + private let k: Array + + fileprivate var accumulated = Array() + fileprivate var processedBytesTotalCount: Int = 0 + fileprivate var accumulatedHash32 = Array() + fileprivate var accumulatedHash64 = Array() + + public enum Variant: RawRepresentable { + case sha224, sha256, sha384, sha512 + + public var digestLength: Int { + return self.rawValue / 8 + } + + public var blockSize: Int { + switch self { + case .sha224, .sha256: + return 64 + case .sha384, .sha512: + return 128 + } + } + + public typealias RawValue = Int + public var rawValue: RawValue { + switch self { + case .sha224: + return 224 + case .sha256: + return 256 + case .sha384: + return 384 + case .sha512: + return 512 + } + } + + public init?(rawValue: RawValue) { + switch (rawValue) { + case 224: + self = .sha224 + break + case 256: + self = .sha256 + break + case 384: + self = .sha384 + break + case 512: + self = .sha512 + break + default: + return nil + } + } + + fileprivate var h: Array { + switch self { + case .sha224: + return [0xc1059ed8, 0x367cd507, 0x3070dd17, 0xf70e5939, 0xffc00b31, 0x68581511, 0x64f98fa7, 0xbefa4fa4] + case .sha256: + return [0x6a09e667, 0xbb67ae85, 0x3c6ef372, 0xa54ff53a, 0x510e527f, 0x9b05688c, 0x1f83d9ab, 0x5be0cd19] + case .sha384: + return [0xcbbb9d5dc1059ed8, 0x629a292a367cd507, 0x9159015a3070dd17, 0x152fecd8f70e5939, 0x67332667ffc00b31, 0x8eb44a8768581511, 0xdb0c2e0d64f98fa7, 0x47b5481dbefa4fa4] + case .sha512: + return [0x6a09e667f3bcc908, 0xbb67ae8584caa73b, 0x3c6ef372fe94f82b, 0xa54ff53a5f1d36f1, 0x510e527fade682d1, 0x9b05688c2b3e6c1f, 0x1f83d9abfb41bd6b, 0x5be0cd19137e2179] + } + } + + fileprivate var finalLength: Int { + switch (self) { + case .sha224: + return 7 + case .sha384: + return 6 + default: + return Int.max + } + } + } + + public init(variant: SHA2.Variant) { + self.variant = variant + switch self.variant { + case .sha224, .sha256: + self.accumulatedHash32 = variant.h.map { UInt32($0) } // FIXME: UInt64 for process64 + self.blockSize = variant.blockSize + self.size = variant.rawValue + self.digestLength = variant.digestLength + self.k = [0x428a2f98, 0x71374491, 0xb5c0fbcf, 0xe9b5dba5, 0x3956c25b, 0x59f111f1, 0x923f82a4, 0xab1c5ed5, + 0xd807aa98, 0x12835b01, 0x243185be, 0x550c7dc3, 0x72be5d74, 0x80deb1fe, 0x9bdc06a7, 0xc19bf174, + 0xe49b69c1, 0xefbe4786, 0x0fc19dc6, 0x240ca1cc, 0x2de92c6f, 0x4a7484aa, 0x5cb0a9dc, 0x76f988da, + 0x983e5152, 0xa831c66d, 0xb00327c8, 0xbf597fc7, 0xc6e00bf3, 0xd5a79147, 0x06ca6351, 0x14292967, + 0x27b70a85, 0x2e1b2138, 0x4d2c6dfc, 0x53380d13, 0x650a7354, 0x766a0abb, 0x81c2c92e, 0x92722c85, + 0xa2bfe8a1, 0xa81a664b, 0xc24b8b70, 0xc76c51a3, 0xd192e819, 0xd6990624, 0xf40e3585, 0x106aa070, + 0x19a4c116, 0x1e376c08, 0x2748774c, 0x34b0bcb5, 0x391c0cb3, 0x4ed8aa4a, 0x5b9cca4f, 0x682e6ff3, + 0x748f82ee, 0x78a5636f, 0x84c87814, 0x8cc70208, 0x90befffa, 0xa4506ceb, 0xbef9a3f7, 0xc67178f2] + case .sha384, .sha512: + self.accumulatedHash64 = variant.h + self.blockSize = variant.blockSize + self.size = variant.rawValue + self.digestLength = variant.digestLength + self.k = [0x428a2f98d728ae22, 0x7137449123ef65cd, 0xb5c0fbcfec4d3b2f, 0xe9b5dba58189dbbc, 0x3956c25bf348b538, + 0x59f111f1b605d019, 0x923f82a4af194f9b, 0xab1c5ed5da6d8118, 0xd807aa98a3030242, 0x12835b0145706fbe, + 0x243185be4ee4b28c, 0x550c7dc3d5ffb4e2, 0x72be5d74f27b896f, 0x80deb1fe3b1696b1, 0x9bdc06a725c71235, + 0xc19bf174cf692694, 0xe49b69c19ef14ad2, 0xefbe4786384f25e3, 0x0fc19dc68b8cd5b5, 0x240ca1cc77ac9c65, + 0x2de92c6f592b0275, 0x4a7484aa6ea6e483, 0x5cb0a9dcbd41fbd4, 0x76f988da831153b5, 0x983e5152ee66dfab, + 0xa831c66d2db43210, 0xb00327c898fb213f, 0xbf597fc7beef0ee4, 0xc6e00bf33da88fc2, 0xd5a79147930aa725, + 0x06ca6351e003826f, 0x142929670a0e6e70, 0x27b70a8546d22ffc, 0x2e1b21385c26c926, 0x4d2c6dfc5ac42aed, + 0x53380d139d95b3df, 0x650a73548baf63de, 0x766a0abb3c77b2a8, 0x81c2c92e47edaee6, 0x92722c851482353b, + 0xa2bfe8a14cf10364, 0xa81a664bbc423001, 0xc24b8b70d0f89791, 0xc76c51a30654be30, 0xd192e819d6ef5218, + 0xd69906245565a910, 0xf40e35855771202a, 0x106aa07032bbd1b8, 0x19a4c116b8d2d0c8, 0x1e376c085141ab53, + 0x2748774cdf8eeb99, 0x34b0bcb5e19b48a8, 0x391c0cb3c5c95a63, 0x4ed8aa4ae3418acb, 0x5b9cca4f7763e373, + 0x682e6ff3d6b2b8a3, 0x748f82ee5defb2fc, 0x78a5636f43172f60, 0x84c87814a1f0ab72, 0x8cc702081a6439ec, + 0x90befffa23631e28, 0xa4506cebde82bde9, 0xbef9a3f7b2c67915, 0xc67178f2e372532b, 0xca273eceea26619c, + 0xd186b8c721c0c207, 0xeada7dd6cde0eb1e, 0xf57d4f7fee6ed178, 0x06f067aa72176fba, 0x0a637dc5a2c898a6, + 0x113f9804bef90dae, 0x1b710b35131c471b, 0x28db77f523047d84, 0x32caab7b40c72493, 0x3c9ebe0a15c9bebc, + 0x431d67c49c100d4c, 0x4cc5d4becb3e42b6, 0x597f299cfc657e2a, 0x5fcb6fab3ad6faec, 0x6c44198c4a475817] + } + } + + public func calculate(for bytes: Array) -> Array { + do { + return try self.update(withBytes: bytes, isLast: true) + } catch { + return [] + } + } + + fileprivate func process64(block chunk: ArraySlice, currentHash hh: inout Array) { + // break chunk into sixteen 64-bit words M[j], 0 ≤ j ≤ 15, big-endian + // Extend the sixteen 64-bit words into eighty 64-bit words: + var M = Array(repeating: 0, count: self.k.count) + for x in 0 ..< M.count { + switch (x) { + case 0 ... 15: + let start = chunk.startIndex.advanced(by: x * 8) // * MemoryLayout.size + M[x] = UInt64(bytes: chunk, fromIndex: start) + break + default: + let s0 = rotateRight(M[x - 15], by: 1) ^ rotateRight(M[x - 15], by: 8) ^ (M[x - 15] >> 7) + let s1 = rotateRight(M[x - 2], by: 19) ^ rotateRight(M[x - 2], by: 61) ^ (M[x - 2] >> 6) + M[x] = M[x - 16] &+ s0 &+ M[x - 7] &+ s1 + break + } + } + + var A = hh[0] + var B = hh[1] + var C = hh[2] + var D = hh[3] + var E = hh[4] + var F = hh[5] + var G = hh[6] + var H = hh[7] + + // Main loop + for j in 0 ..< self.k.count { + let s0 = rotateRight(A, by: 28) ^ rotateRight(A, by: 34) ^ rotateRight(A, by: 39) + let maj = (A & B) ^ (A & C) ^ (B & C) + let t2 = s0 &+ maj + let s1 = rotateRight(E, by: 14) ^ rotateRight(E, by: 18) ^ rotateRight(E, by: 41) + let ch = (E & F) ^ ((~E) & G) + let t1 = H &+ s1 &+ ch &+ self.k[j] &+ UInt64(M[j]) + + H = G + G = F + F = E + E = D &+ t1 + D = C + C = B + B = A + A = t1 &+ t2 + } + + hh[0] = (hh[0] &+ A) + hh[1] = (hh[1] &+ B) + hh[2] = (hh[2] &+ C) + hh[3] = (hh[3] &+ D) + hh[4] = (hh[4] &+ E) + hh[5] = (hh[5] &+ F) + hh[6] = (hh[6] &+ G) + hh[7] = (hh[7] &+ H) + } + + // mutating currentHash in place is way faster than returning new result + fileprivate func process32(block chunk: ArraySlice, currentHash hh: inout Array) { + // break chunk into sixteen 32-bit words M[j], 0 ≤ j ≤ 15, big-endian + // Extend the sixteen 32-bit words into sixty-four 32-bit words: + var M = Array(repeating: 0, count: self.k.count) + for x in 0 ..< M.count { + switch (x) { + case 0 ... 15: + let start = chunk.startIndex.advanced(by: x * 4) // * MemoryLayout.size + M[x] = UInt32(bytes: chunk, fromIndex: start) + break + default: + let s0 = rotateRight(M[x - 15], by: 7) ^ rotateRight(M[x - 15], by: 18) ^ (M[x - 15] >> 3) + let s1 = rotateRight(M[x - 2], by: 17) ^ rotateRight(M[x - 2], by: 19) ^ (M[x - 2] >> 10) + M[x] = M[x - 16] &+ s0 &+ M[x - 7] &+ s1 + break + } + } + + var A = hh[0] + var B = hh[1] + var C = hh[2] + var D = hh[3] + var E = hh[4] + var F = hh[5] + var G = hh[6] + var H = hh[7] + + // Main loop + for j in 0 ..< self.k.count { + let s0 = rotateRight(A, by: 2) ^ rotateRight(A, by: 13) ^ rotateRight(A, by: 22) + let maj = (A & B) ^ (A & C) ^ (B & C) + let t2 = s0 &+ maj + let s1 = rotateRight(E, by: 6) ^ rotateRight(E, by: 11) ^ rotateRight(E, by: 25) + let ch = (E & F) ^ ((~E) & G) + let t1 = H &+ s1 &+ ch &+ UInt32(self.k[j]) &+ M[j] + + H = G + G = F + F = E + E = D &+ t1 + D = C + C = B + B = A + A = t1 &+ t2 + } + + hh[0] = hh[0] &+ A + hh[1] = hh[1] &+ B + hh[2] = hh[2] &+ C + hh[3] = hh[3] &+ D + hh[4] = hh[4] &+ E + hh[5] = hh[5] &+ F + hh[6] = hh[6] &+ G + hh[7] = hh[7] &+ H + } +} + +extension SHA2: Updatable { + + public func update(withBytes bytes: T, isLast: Bool = false) throws -> Array where T.Iterator.Element == UInt8 { + self.accumulated += bytes + + if isLast { + let lengthInBits = (self.processedBytesTotalCount + self.accumulated.count) * 8 + let lengthBytes = lengthInBits.bytes(totalBytes: self.blockSize / 8) // A 64-bit/128-bit representation of b. blockSize fit by accident. + + // Step 1. Append padding + bitPadding(to: &self.accumulated, blockSize: self.blockSize, allowance: self.blockSize / 8) + + // Step 2. Append Length a 64-bit representation of lengthInBits + self.accumulated += lengthBytes + } + + var processedBytes = 0 + for chunk in BytesSequence(chunkSize: self.blockSize, data: self.accumulated) { + if (isLast || (self.accumulated.count - processedBytes) >= self.blockSize) { + switch self.variant { + case .sha224, .sha256: + self.process32(block: chunk, currentHash: &self.accumulatedHash32) + case .sha384, .sha512: + self.process64(block: chunk, currentHash: &self.accumulatedHash64) + } + processedBytes += chunk.count + } + } + self.accumulated.removeFirst(processedBytes) + self.processedBytesTotalCount += processedBytes + + // output current hash + var result = Array(repeating: 0, count: self.variant.digestLength) + switch self.variant { + case .sha224, .sha256: + var pos = 0 + for idx in 0 ..< self.accumulatedHash32.count where idx < self.variant.finalLength { + let h = self.accumulatedHash32[idx].bigEndian + result[pos] = UInt8(h & 0xff) + result[pos + 1] = UInt8((h >> 8) & 0xff) + result[pos + 2] = UInt8((h >> 16) & 0xff) + result[pos + 3] = UInt8((h >> 24) & 0xff) + pos += 4 + } + case .sha384, .sha512: + var pos = 0 + for idx in 0 ..< self.accumulatedHash64.count where idx < self.variant.finalLength { + let h = self.accumulatedHash64[idx].bigEndian + result[pos] = UInt8(h & 0xff) + result[pos + 1] = UInt8((h >> 8) & 0xff) + result[pos + 2] = UInt8((h >> 16) & 0xff) + result[pos + 3] = UInt8((h >> 24) & 0xff) + result[pos + 4] = UInt8((h >> 32) & 0xff) + result[pos + 5] = UInt8((h >> 40) & 0xff) + result[pos + 6] = UInt8((h >> 48) & 0xff) + result[pos + 7] = UInt8((h >> 56) & 0xff) + pos += 8 + } + } + + // reset hash value for instance + if isLast { + switch self.variant { + case .sha224, .sha256: + self.accumulatedHash32 = variant.h.lazy.map { UInt32($0) } // FIXME: UInt64 for process64 + case .sha384, .sha512: + self.accumulatedHash64 = variant.h + } + } + + return result + } +} diff --git a/GeneralUtils/GeneralUtils/libs/CryptoSwift/SHA3.swift b/GeneralUtils/GeneralUtils/libs/CryptoSwift/SHA3.swift new file mode 100644 index 0000000..e6f3a56 --- /dev/null +++ b/GeneralUtils/GeneralUtils/libs/CryptoSwift/SHA3.swift @@ -0,0 +1,281 @@ +// +// SHA3.swift +// CryptoSwift +// +// Created by Marcin Krzyzanowski on 23/09/16. +// Copyright © 2016 Marcin Krzyzanowski. All rights reserved. +// +// http://nvlpubs.nist.gov/nistpubs/FIPS/NIST.FIPS.202.pdf +// http://keccak.noekeon.org/specs_summary.html +// + +#if os(Linux) || os(Android) || os(FreeBSD) + import Glibc +#else + import Darwin +#endif + +public final class SHA3: DigestType { + let round_constants: Array = [0x0000000000000001, 0x0000000000008082, 0x800000000000808A, 0x8000000080008000, + 0x000000000000808B, 0x0000000080000001, 0x8000000080008081, 0x8000000000008009, + 0x000000000000008A, 0x0000000000000088, 0x0000000080008009, 0x000000008000000A, + 0x000000008000808B, 0x800000000000008B, 0x8000000000008089, 0x8000000000008003, + 0x8000000000008002, 0x8000000000000080, 0x000000000000800A, 0x800000008000000A, + 0x8000000080008081, 0x8000000000008080, 0x0000000080000001, 0x8000000080008008] + + public let blockSize: Int + public let digestLength: Int + + fileprivate var accumulated = Array() + fileprivate var processedBytesTotalCount: Int = 0 + fileprivate var accumulatedHash: Array + + public enum Variant: RawRepresentable { + case sha224, sha256, sha384, sha512 + + var digestLength: Int { + return 100 - (self.blockSize / 2) + } + + var blockSize: Int { + return (1600 - self.rawValue * 2) / 8 + } + + public typealias RawValue = Int + public var rawValue: RawValue { + switch self { + case .sha224: + return 224 + case .sha256: + return 256 + case .sha384: + return 384 + case .sha512: + return 512 + } + } + + public init?(rawValue: RawValue) { + switch (rawValue) { + case 224: + self = .sha224 + break + case 256: + self = .sha256 + break + case 384: + self = .sha384 + break + case 512: + self = .sha512 + break + default: + return nil + } + } + } + + public init(variant: SHA3.Variant) { + self.blockSize = variant.blockSize + self.digestLength = variant.digestLength + self.accumulatedHash = Array(repeating: 0, count: self.digestLength) + } + + public func calculate(for bytes: Array) -> Array { + do { + return try self.update(withBytes: bytes, isLast: true) + } catch { + return [] + } + } + + /// 1. For all pairs (x,z) such that 0≤x<5 and 0≤z) { + var c = Array(repeating: 0, count: 5) + var d = Array(repeating: 0, count: 5) + + for i in 0 ..< 5 { + c[i] = a[i] ^ a[i &+ 5] ^ a[i &+ 10] ^ a[i &+ 15] ^ a[i &+ 20] + } + + d[0] = rotateLeft(c[1], by: 1) ^ c[4] + d[1] = rotateLeft(c[2], by: 1) ^ c[0] + d[2] = rotateLeft(c[3], by: 1) ^ c[1] + d[3] = rotateLeft(c[4], by: 1) ^ c[2] + d[4] = rotateLeft(c[0], by: 1) ^ c[3] + + for i in 0 ..< 5 { + a[i] ^= d[i] + a[i &+ 5] ^= d[i] + a[i &+ 10] ^= d[i] + a[i &+ 15] ^= d[i] + a[i &+ 20] ^= d[i] + } + } + + /// A′[x, y, z]=A[(x &+ 3y) mod 5, x, z] + private func π(_ a: inout Array) { + let a1 = a[1] + a[1] = a[6] + a[6] = a[9] + a[9] = a[22] + a[22] = a[14] + a[14] = a[20] + a[20] = a[2] + a[2] = a[12] + a[12] = a[13] + a[13] = a[19] + a[19] = a[23] + a[23] = a[15] + a[15] = a[4] + a[4] = a[24] + a[24] = a[21] + a[21] = a[8] + a[8] = a[16] + a[16] = a[5] + a[5] = a[3] + a[3] = a[18] + a[18] = a[17] + a[17] = a[11] + a[11] = a[7] + a[7] = a[10] + a[10] = a1 + } + + /// For all triples (x, y, z) such that 0≤x<5, 0≤y<5, and 0≤z) { + for i in stride(from: 0, to: 25, by: 5) { + let a0 = a[0 &+ i] + let a1 = a[1 &+ i] + a[0 &+ i] ^= ~a1 & a[2 &+ i] + a[1 &+ i] ^= ~a[2 &+ i] & a[3 &+ i] + a[2 &+ i] ^= ~a[3 &+ i] & a[4 &+ i] + a[3 &+ i] ^= ~a[4 &+ i] & a0 + a[4 &+ i] ^= ~a0 & a1 + } + } + + private func ι(_ a: inout Array, round: Int) { + a[0] ^= round_constants[round] + } + + fileprivate func process(block chunk: C, currentHash hh: inout Array) where C.Iterator.Element == UInt64, C.Index == Int { + // expand + hh[0] ^= chunk[0].littleEndian + hh[1] ^= chunk[1].littleEndian + hh[2] ^= chunk[2].littleEndian + hh[3] ^= chunk[3].littleEndian + hh[4] ^= chunk[4].littleEndian + hh[5] ^= chunk[5].littleEndian + hh[6] ^= chunk[6].littleEndian + hh[7] ^= chunk[7].littleEndian + hh[8] ^= chunk[8].littleEndian + if self.blockSize > 72 { // 72 / 8, sha-512 + hh[9] ^= chunk[9].littleEndian + hh[10] ^= chunk[10].littleEndian + hh[11] ^= chunk[11].littleEndian + hh[12] ^= chunk[12].littleEndian + if self.blockSize > 104 { // 104 / 8, sha-384 + hh[13] ^= chunk[13].littleEndian + hh[14] ^= chunk[14].littleEndian + hh[15] ^= chunk[15].littleEndian + hh[16] ^= chunk[16].littleEndian + if self.blockSize > 136 { // 136 / 8, sha-256 + hh[17] ^= chunk[17].littleEndian + // FULL_SHA3_FAMILY_SUPPORT + if self.blockSize > 144 { // 144 / 8, sha-224 + hh[18] ^= chunk[18].littleEndian + hh[19] ^= chunk[19].littleEndian + hh[20] ^= chunk[20].littleEndian + hh[21] ^= chunk[21].littleEndian + hh[22] ^= chunk[22].littleEndian + hh[23] ^= chunk[23].littleEndian + hh[24] ^= chunk[24].littleEndian + } + } + } + } + + // Keccak-f + for round in 0 ..< 24 { + θ(&hh) + + hh[1] = rotateLeft(hh[1], by: 1) + hh[2] = rotateLeft(hh[2], by: 62) + hh[3] = rotateLeft(hh[3], by: 28) + hh[4] = rotateLeft(hh[4], by: 27) + hh[5] = rotateLeft(hh[5], by: 36) + hh[6] = rotateLeft(hh[6], by: 44) + hh[7] = rotateLeft(hh[7], by: 6) + hh[8] = rotateLeft(hh[8], by: 55) + hh[9] = rotateLeft(hh[9], by: 20) + hh[10] = rotateLeft(hh[10], by: 3) + hh[11] = rotateLeft(hh[11], by: 10) + hh[12] = rotateLeft(hh[12], by: 43) + hh[13] = rotateLeft(hh[13], by: 25) + hh[14] = rotateLeft(hh[14], by: 39) + hh[15] = rotateLeft(hh[15], by: 41) + hh[16] = rotateLeft(hh[16], by: 45) + hh[17] = rotateLeft(hh[17], by: 15) + hh[18] = rotateLeft(hh[18], by: 21) + hh[19] = rotateLeft(hh[19], by: 8) + hh[20] = rotateLeft(hh[20], by: 18) + hh[21] = rotateLeft(hh[21], by: 2) + hh[22] = rotateLeft(hh[22], by: 61) + hh[23] = rotateLeft(hh[23], by: 56) + hh[24] = rotateLeft(hh[24], by: 14) + + π(&hh) + χ(&hh) + ι(&hh, round: round) + } + } +} + +extension SHA3: Updatable { + + public func update(withBytes bytes: T, isLast: Bool = false) throws -> Array where T.Iterator.Element == UInt8 { + self.accumulated += bytes + + if isLast { + // Add padding + let markByteIndex = self.processedBytesTotalCount &+ self.accumulated.count + if self.accumulated.count == 0 || self.accumulated.count % self.blockSize != 0 { + let r = self.blockSize * 8 + let q = (r / 8) - (self.accumulated.count % (r / 8)) + self.accumulated += Array(repeating: 0, count: q) + } + + self.accumulated[markByteIndex] |= 0x06 // 0x1F for SHAKE + self.accumulated[self.accumulated.count - 1] |= 0x80 + } + + var processedBytes = 0 + for chunk in BytesSequence(chunkSize: self.blockSize, data: self.accumulated) { + if (isLast || (self.accumulated.count - processedBytes) >= self.blockSize) { + self.process(block: chunk.toUInt64Array(), currentHash: &self.accumulatedHash) + processedBytes += chunk.count + } + } + self.accumulated.removeFirst(processedBytes) + self.processedBytesTotalCount += processedBytes + + // TODO: verify performance, reduce vs for..in + let result = self.accumulatedHash.reduce(Array()) { (result, value) -> Array in + return result + value.bigEndian.bytes() + } + + // reset hash value for instance + if isLast { + self.accumulatedHash = Array(repeating: 0, count: self.digestLength) + } + + return Array(result[0 ..< self.digestLength]) + } +} diff --git a/GeneralUtils/GeneralUtils/libs/CryptoSwift/SecureBytes.swift b/GeneralUtils/GeneralUtils/libs/CryptoSwift/SecureBytes.swift new file mode 100644 index 0000000..3e21d3d --- /dev/null +++ b/GeneralUtils/GeneralUtils/libs/CryptoSwift/SecureBytes.swift @@ -0,0 +1,68 @@ +// +// SecureBytes.swift +// CryptoSwift +// +// Created by Marcin Krzyzanowski on 15/04/16. +// Copyright © 2016 Marcin Krzyzanowski. All rights reserved. +// + +#if os(Linux) || os(Android) || os(FreeBSD) + import Glibc +#else + import Darwin +#endif + +/// Keeps bytes in memory. Because this is class, bytes are not copied +/// and memory area is locked as long as referenced, then unlocked on deinit +final class SecureBytes { + fileprivate let bytes: Array + let count: Int + + init(bytes: Array) { + self.bytes = bytes + self.count = bytes.count + self.bytes.withUnsafeBufferPointer { (pointer) -> Void in + mlock(pointer.baseAddress, pointer.count) + } + } + + deinit { + self.bytes.withUnsafeBufferPointer { (pointer) -> Void in + munlock(pointer.baseAddress, pointer.count) + } + } +} + +extension SecureBytes: Collection { + typealias Index = Int + + var endIndex: Int { + return self.bytes.endIndex + } + + var startIndex: Int { + return self.bytes.startIndex + } + + subscript(position: Index) -> UInt8 { + return self.bytes[position] + } + + subscript(bounds: Range) -> ArraySlice { + return self.bytes[bounds] + } + + func formIndex(after i: inout Int) { + self.bytes.formIndex(after: &i) + } + + func index(after i: Int) -> Int { + return self.bytes.index(after: i) + } +} + +extension SecureBytes: ExpressibleByArrayLiteral { + public convenience init(arrayLiteral elements: UInt8...) { + self.init(bytes: elements) + } +} diff --git a/GeneralUtils/GeneralUtils/libs/CryptoSwift/String+Extension.swift b/GeneralUtils/GeneralUtils/libs/CryptoSwift/String+Extension.swift new file mode 100644 index 0000000..4bdbbf4 --- /dev/null +++ b/GeneralUtils/GeneralUtils/libs/CryptoSwift/String+Extension.swift @@ -0,0 +1,61 @@ +// +// StringExtension.swift +// CryptoSwift +// +// Created by Marcin Krzyzanowski on 15/08/14. +// Copyright (c) 2014 Marcin Krzyzanowski. All rights reserved. +// + +/** String extension */ +extension String { + + public func md5() -> String { + return self.utf8.lazy.map({ $0 as UInt8 }).md5().toHexString() + } + + public func sha1() -> String { + return self.utf8.lazy.map({ $0 as UInt8 }).sha1().toHexString() + } + + public func sha224() -> String { + return self.utf8.lazy.map({ $0 as UInt8 }).sha224().toHexString() + } + + public func sha256() -> String { + return self.utf8.lazy.map({ $0 as UInt8 }).sha256().toHexString() + } + + public func sha384() -> String { + return self.utf8.lazy.map({ $0 as UInt8 }).sha384().toHexString() + } + + public func sha512() -> String { + return self.utf8.lazy.map({ $0 as UInt8 }).sha512().toHexString() + } + + public func sha3(_ variant: SHA3.Variant) -> String { + return self.utf8.lazy.map({ $0 as UInt8 }).sha3(variant).toHexString() + } + + public func crc32(seed: UInt32? = nil, reflect: Bool = true) -> String { + return self.utf8.lazy.map({ $0 as UInt8 }).crc32(seed: seed, reflect: reflect).bytes().toHexString() + } + + public func crc16(seed: UInt16? = nil) -> String { + return self.utf8.lazy.map({ $0 as UInt8 }).crc16(seed: seed).bytes().toHexString() + } + + /// - parameter cipher: Instance of `Cipher` + /// - returns: hex string of bytes + public func encrypt(cipher: Cipher) throws -> String { + return try self.utf8.lazy.map({ $0 as UInt8 }).encrypt(cipher: cipher).toHexString() + } + + // decrypt() does not make sense for String + + /// - parameter authenticator: Instance of `Authenticator` + /// - returns: hex string of string + public func authenticate(with authenticator: A) throws -> String { + return try self.utf8.lazy.map({ $0 as UInt8 }).authenticate(with: authenticator).toHexString() + } +} diff --git a/GeneralUtils/GeneralUtils/libs/CryptoSwift/UInt16+Extension.swift b/GeneralUtils/GeneralUtils/libs/CryptoSwift/UInt16+Extension.swift new file mode 100644 index 0000000..71f6850 --- /dev/null +++ b/GeneralUtils/GeneralUtils/libs/CryptoSwift/UInt16+Extension.swift @@ -0,0 +1,28 @@ +// +// UInt16+Extension.swift +// CryptoSwift +// +// Created by Marcin Krzyzanowski on 06/08/16. +// Copyright © 2016 Marcin Krzyzanowski. All rights reserved. +// + +/** array of bytes */ +extension UInt16 { + + @_specialize(ArraySlice) + init(bytes: T) where T.Iterator.Element == UInt8, T.Index == Int { + self = UInt16(bytes: bytes, fromIndex: bytes.startIndex) + } + + @_specialize(ArraySlice) + init(bytes: T, fromIndex index: T.Index) where T.Iterator.Element == UInt8, T.Index == Int { + let val0 = UInt16(bytes[index.advanced(by: 0)]) << 8 + let val1 = UInt16(bytes[index.advanced(by: 1)]) + + self = val0 | val1 + } + + func bytes(totalBytes: Int = MemoryLayout.size) -> Array { + return arrayOfBytes(value: self, length: totalBytes) + } +} diff --git a/GeneralUtils/GeneralUtils/libs/CryptoSwift/UInt32+Extension.swift b/GeneralUtils/GeneralUtils/libs/CryptoSwift/UInt32+Extension.swift new file mode 100644 index 0000000..7c87621 --- /dev/null +++ b/GeneralUtils/GeneralUtils/libs/CryptoSwift/UInt32+Extension.swift @@ -0,0 +1,39 @@ +// +// UInt32Extension.swift +// CryptoSwift +// +// Created by Marcin Krzyzanowski on 02/09/14. +// Copyright (c) 2014 Marcin Krzyzanowski. All rights reserved. +// + +#if os(Linux) || os(Android) || os(FreeBSD) + import Glibc +#else + import Darwin +#endif + +protocol _UInt32Type {} +extension UInt32: _UInt32Type {} + +/** array of bytes */ +extension UInt32 { + + @_specialize(ArraySlice) + init(bytes: T) where T.Iterator.Element == UInt8, T.Index == Int { + self = UInt32(bytes: bytes, fromIndex: bytes.startIndex) + } + + @_specialize(ArraySlice) + init(bytes: T, fromIndex index: T.Index) where T.Iterator.Element == UInt8, T.Index == Int { + let val0 = UInt32(bytes[index.advanced(by: 0)]) << 24 + let val1 = UInt32(bytes[index.advanced(by: 1)]) << 16 + let val2 = UInt32(bytes[index.advanced(by: 2)]) << 8 + let val3 = UInt32(bytes[index.advanced(by: 3)]) + + self = val0 | val1 | val2 | val3 + } + + func bytes(totalBytes: Int = MemoryLayout.size) -> Array { + return arrayOfBytes(value: self, length: totalBytes) + } +} diff --git a/GeneralUtils/GeneralUtils/libs/CryptoSwift/UInt64+Extension.swift b/GeneralUtils/GeneralUtils/libs/CryptoSwift/UInt64+Extension.swift new file mode 100644 index 0000000..b13f16d --- /dev/null +++ b/GeneralUtils/GeneralUtils/libs/CryptoSwift/UInt64+Extension.swift @@ -0,0 +1,34 @@ +// +// UInt64Extension.swift +// CryptoSwift +// +// Created by Marcin Krzyzanowski on 02/09/14. +// Copyright (c) 2014 Marcin Krzyzanowski. All rights reserved. +// + +/** array of bytes */ +extension UInt64 { + + @_specialize(ArraySlice) + init(bytes: T) where T.Iterator.Element == UInt8, T.Index == Int { + self = UInt64(bytes: bytes, fromIndex: bytes.startIndex) + } + + @_specialize(ArraySlice) + init(bytes: T, fromIndex index: T.Index) where T.Iterator.Element == UInt8, T.Index == Int { + let val0 = UInt64(bytes[index.advanced(by: 0)]) << 56 + let val1 = UInt64(bytes[index.advanced(by: 1)]) << 48 + let val2 = UInt64(bytes[index.advanced(by: 2)]) << 40 + let val3 = UInt64(bytes[index.advanced(by: 3)]) << 32 + let val4 = UInt64(bytes[index.advanced(by: 4)]) << 24 + let val5 = UInt64(bytes[index.advanced(by: 5)]) << 16 + let val6 = UInt64(bytes[index.advanced(by: 6)]) << 8 + let val7 = UInt64(bytes[index.advanced(by: 7)]) + + self = val0 | val1 | val2 | val3 | val4 | val5 | val6 | val7 + } + + func bytes(totalBytes: Int = MemoryLayout.size) -> Array { + return arrayOfBytes(value: self, length: totalBytes) + } +} diff --git a/GeneralUtils/GeneralUtils/libs/CryptoSwift/UInt8+Extension.swift b/GeneralUtils/GeneralUtils/libs/CryptoSwift/UInt8+Extension.swift new file mode 100644 index 0000000..68df1de --- /dev/null +++ b/GeneralUtils/GeneralUtils/libs/CryptoSwift/UInt8+Extension.swift @@ -0,0 +1,71 @@ +// +// ByteExtension.swift +// CryptoSwift +// +// Created by Marcin Krzyzanowski on 07/08/14. +// Copyright (c) 2014 Marcin Krzyzanowski. All rights reserved. +// + +#if os(Linux) || os(Android) || os(FreeBSD) + import Glibc +#else + import Darwin +#endif + +public protocol _UInt8Type {} +extension UInt8: _UInt8Type {} + +/** casting */ +extension UInt8 { + + /** cast because UInt8() because std initializer crash if value is > byte */ + static func with(value: UInt64) -> UInt8 { + let tmp = value & 0xFF + return UInt8(tmp) + } + + static func with(value: UInt32) -> UInt8 { + let tmp = value & 0xFF + return UInt8(tmp) + } + + static func with(value: UInt16) -> UInt8 { + let tmp = value & 0xFF + return UInt8(tmp) + } +} + +/** Bits */ +extension UInt8 { + + init(bits: [Bit]) { + self.init(integerFrom(bits) as UInt8) + } + + /** array of bits */ + func bits() -> [Bit] { + let totalBitsCount = MemoryLayout.size * 8 + + var bitsArray = [Bit](repeating: Bit.zero, count: totalBitsCount) + + for j in 0 ..< totalBitsCount { + let bitVal: UInt8 = 1 << UInt8(totalBitsCount - 1 - j) + let check = self & bitVal + + if (check != 0) { + bitsArray[j] = Bit.one + } + } + return bitsArray + } + + func bits() -> String { + var s = String() + let arr: [Bit] = self.bits() + for idx in arr.indices { + s += (arr[idx] == Bit.one ? "1" : "0") + if (idx.advanced(by: 1) % 8 == 0) { s += " " } + } + return s + } +} diff --git a/GeneralUtils/GeneralUtils/libs/CryptoSwift/Updatable.swift b/GeneralUtils/GeneralUtils/libs/CryptoSwift/Updatable.swift new file mode 100644 index 0000000..0f39fc5 --- /dev/null +++ b/GeneralUtils/GeneralUtils/libs/CryptoSwift/Updatable.swift @@ -0,0 +1,66 @@ +// +// Updatable.swift +// CryptoSwift +// +// Created by Marcin Krzyzanowski on 06/05/16. +// Copyright © 2016 Marcin Krzyzanowski. All rights reserved. +// + +/// A type that supports incremental updates. For example Digest or Cipher may be updatable +/// and calculate result incerementally. +public protocol Updatable { + /// Update given bytes in chunks. + /// + /// - parameter bytes: Bytes to process + /// - parameter isLast: (Optional) Given chunk is the last one. No more updates after this call. + /// - returns: Processed data or empty array. + mutating func update(withBytes bytes: T, isLast: Bool) throws -> Array where T.Iterator.Element == UInt8 + + /// Update given bytes in chunks. + /// + /// - parameter bytes: Bytes to process + /// - parameter isLast: (Optional) Given chunk is the last one. No more updates after this call. + /// - parameter output: Resulting data + /// - returns: Processed data or empty array. + mutating func update(withBytes bytes: T, isLast: Bool, output: (Array) -> Void) throws where T.Iterator.Element == UInt8 + + /// Finish updates. This may apply padding. + /// - parameter bytes: Bytes to process + /// - returns: Processed data. + mutating func finish(withBytes bytes: T) throws -> Array where T.Iterator.Element == UInt8 + + /// Finish updates. This may apply padding. + /// - parameter bytes: Bytes to process + /// - parameter output: Resulting data + /// - returns: Processed data. + mutating func finish(withBytes bytes: T, output: (Array) -> Void) throws where T.Iterator.Element == UInt8 +} + +extension Updatable { + + mutating public func update(withBytes bytes: T, isLast: Bool = false, output: (Array) -> Void) throws where T.Iterator.Element == UInt8 { + let processed = try self.update(withBytes: bytes, isLast: isLast) + if (!processed.isEmpty) { + output(processed) + } + } + + mutating public func finish(withBytes bytes: T) throws -> Array where T.Iterator.Element == UInt8 { + return try self.update(withBytes: bytes, isLast: true) + } + + mutating public func finish() throws -> Array { + return try self.update(withBytes: [], isLast: true) + } + + mutating public func finish(withBytes bytes: T, output: (Array) -> Void) throws where T.Iterator.Element == UInt8 { + let processed = try self.update(withBytes: bytes, isLast: true) + if (!processed.isEmpty) { + output(processed) + } + } + + mutating public func finish(output: (Array) -> Void) throws { + try self.finish(withBytes: [], output: output) + } +} diff --git a/GeneralUtils/GeneralUtils/libs/CryptoSwift/Utils.swift b/GeneralUtils/GeneralUtils/libs/CryptoSwift/Utils.swift new file mode 100644 index 0000000..baed588 --- /dev/null +++ b/GeneralUtils/GeneralUtils/libs/CryptoSwift/Utils.swift @@ -0,0 +1,85 @@ +// +// Utils.swift +// CryptoSwift +// +// Created by Marcin Krzyzanowski on 26/08/14. +// Copyright (c) 2014 Marcin Krzyzanowski. All rights reserved. +// + +func rotateLeft(_ value: UInt8, by: UInt8) -> UInt8 { + return ((value << by) & 0xFF) | (value >> (8 - by)) +} + +func rotateLeft(_ value: UInt16, by: UInt16) -> UInt16 { + return ((value << by) & 0xFFFF) | (value >> (16 - by)) +} + +func rotateLeft(_ value: UInt32, by: UInt32) -> UInt32 { + return ((value << by) & 0xFFFFFFFF) | (value >> (32 - by)) +} + +func rotateLeft(_ value: UInt64, by: UInt64) -> UInt64 { + return (value << by) | (value >> (64 - by)) +} + +func rotateRight(_ value: UInt16, by: UInt16) -> UInt16 { + return (value >> by) | (value << (16 - by)) +} + +func rotateRight(_ value: UInt32, by: UInt32) -> UInt32 { + return (value >> by) | (value << (32 - by)) +} + +func rotateRight(_ value: UInt64, by: UInt64) -> UInt64 { + return ((value >> by) | (value << (64 - by))) +} + +func reversed(_ uint8: UInt8) -> UInt8 { + var v = uint8 + v = (v & 0xF0) >> 4 | (v & 0x0F) << 4 + v = (v & 0xCC) >> 2 | (v & 0x33) << 2 + v = (v & 0xAA) >> 1 | (v & 0x55) << 1 + return v +} + +func reversed(_ uint32: UInt32) -> UInt32 { + var v = uint32 + v = ((v >> 1) & 0x55555555) | ((v & 0x55555555) << 1) + v = ((v >> 2) & 0x33333333) | ((v & 0x33333333) << 2) + v = ((v >> 4) & 0x0f0f0f0f) | ((v & 0x0f0f0f0f) << 4) + v = ((v >> 8) & 0x00ff00ff) | ((v & 0x00ff00ff) << 8) + v = ((v >> 16) & 0xffff) | ((v & 0xffff) << 16) + return v +} + +func xor(_ a: Array, _ b: Array) -> Array { + var xored = Array(repeating: 0, count: min(a.count, b.count)) + for i in 0 ..< xored.count { + xored[i] = a[i] ^ b[i] + } + return xored +} + +/** + ISO/IEC 9797-1 Padding method 2. + Add a single bit with value 1 to the end of the data. + If necessary add bits with value 0 to the end of the data until the padded data is a multiple of blockSize. + - parameters: + - blockSize: Padding size in bytes. + - allowance: Excluded trailing number of bytes. + */ +@inline(__always) +func bitPadding(to data: inout Array, blockSize: Int, allowance: Int = 0) { + let msgLength = data.count + // Step 1. Append Padding Bits + // append one bit (UInt8 with one bit) to message + data.append(0x80) + + // Step 2. append "0" bit until message length in bits ≡ 448 (mod 512) + let max = blockSize - allowance // 448, 986 + if msgLength % blockSize < max { // 448 + data += Array(repeating: 0, count: max - 1 - (msgLength % blockSize)) + } else { + data += Array(repeating: 0, count: blockSize + max - 1 - (msgLength % blockSize)) + } +} diff --git a/GeneralUtils/GeneralUtils/libs/CryptoSwift/ZeroPadding.swift b/GeneralUtils/GeneralUtils/libs/CryptoSwift/ZeroPadding.swift new file mode 100644 index 0000000..848dff6 --- /dev/null +++ b/GeneralUtils/GeneralUtils/libs/CryptoSwift/ZeroPadding.swift @@ -0,0 +1,32 @@ +// +// ZeroPadding.swift +// CryptoSwift +// +// Created by Marcin Krzyzanowski on 13/06/16. +// Copyright © 2016 Marcin Krzyzanowski. All rights reserved. +// + +/// All the bytes that are required to be padded are padded with zero. +/// Zero padding may not be reversible if the original file ends with one or more zero bytes. +public struct ZeroPadding: Padding { + + public init() { + } + + public func add(to bytes: Array, blockSize: Int) -> Array { + let paddingCount = blockSize - (bytes.count % blockSize) + if paddingCount > 0 { + return bytes + Array(repeating: 0, count: paddingCount) + } + return bytes + } + + public func remove(from bytes: Array, blockSize: Int?) -> Array { + for (idx, value) in bytes.reversed().enumerated() { + if value != 0 { + return Array(bytes[0 ..< bytes.count - idx]) + } + } + return bytes + } +} diff --git a/GeneralUtils/GeneralUtils/libs/Kingfisher/AnimatedImageView.swift b/GeneralUtils/GeneralUtils/libs/Kingfisher/AnimatedImageView.swift new file mode 100755 index 0000000..1bd5d93 --- /dev/null +++ b/GeneralUtils/GeneralUtils/libs/Kingfisher/AnimatedImageView.swift @@ -0,0 +1,351 @@ +// +// AnimatableImageView.swift +// Kingfisher +// +// Created by bl4ckra1sond3tre on 4/22/16. +// +// The AnimatableImageView, AnimatedFrame and Animator is a modified version of +// some classes from kaishin's Gifu project (https://github.com/kaishin/Gifu) +// +// The MIT License (MIT) +// +// Copyright (c) 2014-2016 Reda Lemeden. +// +// Permission is hereby granted, free of charge, to any person obtaining a copy of +// this software and associated documentation files (the "Software"), to deal in +// the Software without restriction, including without limitation the rights to +// use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of +// the Software, and to permit persons to whom the Software is furnished to do so, +// subject to the following conditions: +// +// The above copyright notice and this permission notice shall be included in all +// copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS +// FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR +// COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER +// IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN +// CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. +// +// The name and characters used in the demo of this software are property of their +// respective owners. + +import UIKit +import ImageIO + +/// `AnimatedImageView` is a subclass of `UIImageView` for displaying animated image. +open class AnimatedImageView: UIImageView { + + /// Proxy object for prevending a reference cycle between the CADDisplayLink and AnimatedImageView. + class TargetProxy { + private weak var target: AnimatedImageView? + + init(target: AnimatedImageView) { + self.target = target + } + + @objc func onScreenUpdate() { + target?.updateFrame() + } + } + + // MARK: - Public property + /// Whether automatically play the animation when the view become visible. Default is true. + public var autoPlayAnimatedImage = true + + /// The size of the frame cache. + public var framePreloadCount = 10 + + /// Specifies whether the GIF frames should be pre-scaled to save memory. Default is true. + public var needsPrescaling = true + + /// The animation timer's run loop mode. Default is `NSRunLoopCommonModes`. Set this property to `NSDefaultRunLoopMode` will make the animation pause during UIScrollView scrolling. + public var runLoopMode = RunLoopMode.commonModes { + willSet { + if runLoopMode == newValue { + return + } else { + stopAnimating() + displayLink.remove(from: .main, forMode: runLoopMode) + displayLink.add(to: .main, forMode: newValue) + startAnimating() + } + } + } + + // MARK: - Private property + /// `Animator` instance that holds the frames of a specific image in memory. + private var animator: Animator? + + /// A flag to avoid invalidating the displayLink on deinit if it was never created, because displayLink is so lazy. :D + private var isDisplayLinkInitialized: Bool = false + + /// A display link that keeps calling the `updateFrame` method on every screen refresh. + private lazy var displayLink: CADisplayLink = { + self.isDisplayLinkInitialized = true + let displayLink = CADisplayLink(target: TargetProxy(target: self), selector: #selector(TargetProxy.onScreenUpdate)) + displayLink.add(to: .main, forMode: self.runLoopMode) + displayLink.isPaused = true + return displayLink + }() + + // MARK: - Override + override open var image: Image? { + didSet { + if image != oldValue { + reset() + } + setNeedsDisplay() + layer.setNeedsDisplay() + } + } + + deinit { + if isDisplayLinkInitialized { + displayLink.invalidate() + } + } + + override open var isAnimating: Bool { + if isDisplayLinkInitialized { + return !displayLink.isPaused + } else { + return super.isAnimating + } + } + + /// Starts the animation. + override open func startAnimating() { + if self.isAnimating { + return + } else { + displayLink.isPaused = false + } + } + + /// Stops the animation. + override open func stopAnimating() { + super.stopAnimating() + if isDisplayLinkInitialized { + displayLink.isPaused = true + } + } + + override open func display(_ layer: CALayer) { + if let currentFrame = animator?.currentFrame { + layer.contents = currentFrame.cgImage + } else { + layer.contents = image?.cgImage + } + } + + override open func didMoveToWindow() { + super.didMoveToWindow() + didMove() + } + + override open func didMoveToSuperview() { + super.didMoveToSuperview() + didMove() + } + + // This is for back compatibility that using regular UIImageView to show GIF. + override func shouldPreloadAllGIF() -> Bool { + return false + } + + // MARK: - Private method + /// Reset the animator. + private func reset() { + animator = nil + if let imageSource = image?.kf.imageSource?.imageRef { + animator = Animator(imageSource: imageSource, contentMode: contentMode, size: bounds.size, framePreloadCount: framePreloadCount) + animator?.needsPrescaling = needsPrescaling + animator?.prepareFramesAsynchronously() + } + didMove() + } + + private func didMove() { + if autoPlayAnimatedImage && animator != nil { + if let _ = superview, let _ = window { + startAnimating() + } else { + stopAnimating() + } + } + } + + /// Update the current frame with the displayLink duration. + private func updateFrame() { + if animator?.updateCurrentFrame(duration: displayLink.duration) ?? false { + layer.setNeedsDisplay() + } + } +} + +/// Keeps a reference to an `Image` instance and its duration as a GIF frame. +struct AnimatedFrame { + var image: Image? + let duration: TimeInterval + + static let null: AnimatedFrame = AnimatedFrame(image: .none, duration: 0.0) +} + +// MARK: - Animator +class Animator { + // MARK: Private property + fileprivate let size: CGSize + fileprivate let maxFrameCount: Int + fileprivate let imageSource: CGImageSource + + fileprivate var animatedFrames = [AnimatedFrame]() + fileprivate let maxTimeStep: TimeInterval = 1.0 + fileprivate var frameCount = 0 + fileprivate var currentFrameIndex = 0 + fileprivate var currentPreloadIndex = 0 + fileprivate var timeSinceLastFrameChange: TimeInterval = 0.0 + fileprivate var needsPrescaling = true + + /// Loop count of animatd image. + private var loopCount = 0 + + var currentFrame: UIImage? { + return frame(at: currentFrameIndex) + } + + var contentMode = UIViewContentMode.scaleToFill + + private lazy var preloadQueue: DispatchQueue = { + return DispatchQueue(label: "com.onevcat.Kingfisher.Animator.preloadQueue") + }() + + /** + Init an animator with image source reference. + + - parameter imageSource: The reference of animated image. + - parameter contentMode: Content mode of AnimatedImageView. + - parameter size: Size of AnimatedImageView. + - parameter framePreloadCount: Frame cache size. + + - returns: The animator object. + */ + init(imageSource source: CGImageSource, contentMode mode: UIViewContentMode, size: CGSize, framePreloadCount count: Int) { + self.imageSource = source + self.contentMode = mode + self.size = size + self.maxFrameCount = count + } + + func frame(at index: Int) -> Image? { + return animatedFrames[safe: index]?.image + } + + func prepareFramesAsynchronously() { + preloadQueue.async { [weak self] in + self?.prepareFrames() + } + } + + private func prepareFrames() { + frameCount = CGImageSourceGetCount(imageSource) + + if let properties = CGImageSourceCopyProperties(imageSource, nil), + let gifInfo = (properties as NSDictionary)[kCGImagePropertyGIFDictionary as String] as? NSDictionary, + let loopCount = gifInfo[kCGImagePropertyGIFLoopCount as String] as? Int + { + self.loopCount = loopCount + } + + let frameToProcess = min(frameCount, maxFrameCount) + animatedFrames.reserveCapacity(frameToProcess) + animatedFrames = (0.. AnimatedFrame { + guard let imageRef = CGImageSourceCreateImageAtIndex(imageSource, index, nil) else { + return AnimatedFrame.null + } + + let frameDuration = imageSource.kf.gifProperties(at: index).flatMap { + gifInfo -> Double? in + + let unclampedDelayTime = gifInfo[kCGImagePropertyGIFUnclampedDelayTime as String] as Double? + let delayTime = gifInfo[kCGImagePropertyGIFDelayTime as String] as Double? + let duration = unclampedDelayTime ?? delayTime ?? 0.0 + + /** + http://opensource.apple.com/source/WebCore/WebCore-7600.1.25/platform/graphics/cg/ImageSourceCG.cpp + Many annoying ads specify a 0 duration to make an image flash as quickly as + possible. We follow Safari and Firefox's behavior and use a duration of 100 ms + for any frames that specify a duration of <= 10 ms. + See and for more information. + + See also: http://nullsleep.tumblr.com/post/16524517190/animated-gif-minimum-frame-delay-browser. + */ + return duration > 0.011 ? duration : 0.100 + } + + let image = Image(cgImage: imageRef) + let scaledImage: Image? + + if needsPrescaling { + scaledImage = image.kf.resize(to: size, for: contentMode) + } else { + scaledImage = image + } + + return AnimatedFrame(image: scaledImage, duration: frameDuration ?? 0.0) + } + + /** + Updates the current frame if necessary using the frame timer and the duration of each frame in `animatedFrames`. + */ + func updateCurrentFrame(duration: CFTimeInterval) -> Bool { + timeSinceLastFrameChange += min(maxTimeStep, duration) + guard let frameDuration = animatedFrames[safe: currentFrameIndex]?.duration, frameDuration <= timeSinceLastFrameChange else { + return false + } + + timeSinceLastFrameChange -= frameDuration + let lastFrameIndex = currentFrameIndex + currentFrameIndex += 1 + currentFrameIndex = currentFrameIndex % animatedFrames.count + + if animatedFrames.count < frameCount { + preloadFrameAsynchronously(at: lastFrameIndex) + } + return true + } + + private func preloadFrameAsynchronously(at index: Int) { + preloadQueue.async { [weak self] in + self?.preloadFrame(at: index) + } + } + + private func preloadFrame(at index: Int) { + animatedFrames[index] = prepareFrame(at: currentPreloadIndex) + currentPreloadIndex += 1 + currentPreloadIndex = currentPreloadIndex % frameCount + } +} + +extension CGImageSource: KingfisherCompatible { } +extension Kingfisher where Base: CGImageSource { + func gifProperties(at index: Int) -> [String: Double]? { + let properties = CGImageSourceCopyPropertiesAtIndex(base, index, nil) as Dictionary? + return properties?[kCGImagePropertyGIFDictionary] as? [String: Double] + } +} + +extension Array { + subscript(safe index: Int) -> Element? { + return indices ~= index ? self[index] : nil + } +} + +private func pure(_ value: T) -> [T] { + return [value] +} diff --git a/GeneralUtils/GeneralUtils/libs/Kingfisher/Box.swift b/GeneralUtils/GeneralUtils/libs/Kingfisher/Box.swift new file mode 100644 index 0000000..7076add --- /dev/null +++ b/GeneralUtils/GeneralUtils/libs/Kingfisher/Box.swift @@ -0,0 +1,16 @@ +// +// Box.swift +// Kingfisher +// +// Created by WANG WEI on 2016/09/12. +// Copyright © 2016年 Wei Wang. All rights reserved. +// + +import Foundation + +class Box { + let value: T + init(value: T) { + self.value = value + } +} diff --git a/GeneralUtils/GeneralUtils/libs/Kingfisher/CacheSerializer.swift b/GeneralUtils/GeneralUtils/libs/Kingfisher/CacheSerializer.swift new file mode 100644 index 0000000..df3c5ce --- /dev/null +++ b/GeneralUtils/GeneralUtils/libs/Kingfisher/CacheSerializer.swift @@ -0,0 +1,85 @@ +// +// CacheSerializer.swift +// Kingfisher +// +// Created by Wei Wang on 2016/09/02. +// +// Copyright (c) 2016 Wei Wang +// +// Permission is hereby granted, free of charge, to any person obtaining a copy +// of this software and associated documentation files (the "Software"), to deal +// in the Software without restriction, including without limitation the rights +// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +// copies of the Software, and to permit persons to whom the Software is +// furnished to do so, subject to the following conditions: +// +// The above copyright notice and this permission notice shall be included in +// all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN +// THE SOFTWARE. + +import Foundation + +/// An `CacheSerializer` would be used to convert some data to an image object for +/// retrieving from disk cache and vice versa for storing to disk cache. +public protocol CacheSerializer { + + /// Get the serialized data from a provided image + /// and optional original data for caching to disk. + /// + /// + /// - parameter image: The image needed to be serialized. + /// - parameter original: The original data which is just downloaded. + /// If the image is retrieved from cache instead of + /// downloaded, it will be `nil`. + /// + /// - returns: A data which will be stored to cache, or `nil` when no valid + /// data could be serialized. + func data(with image: Image, original: Data?) -> Data? + + /// Get an image deserialized from provided data. + /// + /// - parameter data: The data from which an image should be deserialized. + /// - parameter options: Options for deserialization. + /// + /// - returns: An image deserialized or `nil` when no valid image + /// could be deserialized. + func image(with data: Data, options: KingfisherOptionsInfo?) -> Image? +} + + +/// `DefaultCacheSerializer` is a basic `CacheSerializer` used in default cache of +/// Kingfisher. It could serialize and deserialize PNG, JEPG and GIF images. For +/// image other than these formats, a normalized `pngRepresentation` will be used. +public struct DefaultCacheSerializer: CacheSerializer { + + public static let `default` = DefaultCacheSerializer() + private init() {} + + public func data(with image: Image, original: Data?) -> Data? { + let imageFormat = original?.kf.imageFormat ?? .unknown + + let data: Data? + switch imageFormat { + case .PNG: data = image.kf.pngRepresentation() + case .JPEG: data = image.kf.jpegRepresentation(compressionQuality: 1.0) + case .GIF: data = image.kf.gifRepresentation() + case .unknown: data = original ?? image.kf.normalized.kf.pngRepresentation() + } + + return data + } + + public func image(with data: Data, options: KingfisherOptionsInfo?) -> Image? { + let scale = (options ?? KingfisherEmptyOptionsInfo).scaleFactor + let preloadAllGIFData = (options ?? KingfisherEmptyOptionsInfo).preloadAllGIFData + + return Kingfisher.image(data: data, scale: scale, preloadAllGIFData: preloadAllGIFData) + } +} diff --git a/GeneralUtils/GeneralUtils/libs/Kingfisher/Filter.swift b/GeneralUtils/GeneralUtils/libs/Kingfisher/Filter.swift new file mode 100644 index 0000000..3b3e524 --- /dev/null +++ b/GeneralUtils/GeneralUtils/libs/Kingfisher/Filter.swift @@ -0,0 +1,145 @@ +// +// Filter.swift +// Kingfisher +// +// Created by Wei Wang on 2016/08/31. +// +// Copyright (c) 2016 Wei Wang +// +// Permission is hereby granted, free of charge, to any person obtaining a copy +// of this software and associated documentation files (the "Software"), to deal +// in the Software without restriction, including without limitation the rights +// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +// copies of the Software, and to permit persons to whom the Software is +// furnished to do so, subject to the following conditions: +// +// The above copyright notice and this permission notice shall be included in +// all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN +// THE SOFTWARE. + + + +import CoreImage +import Accelerate + +// Reuse the same CI Context for all CI drawing. +private let ciContext = CIContext(options: nil) + +/// Transformer method which will be used in to provide a `Filter`. +public typealias Transformer = (CIImage) -> CIImage? + +/// Supply a filter to create an `ImageProcessor`. +public protocol CIImageProcessor: ImageProcessor { + var filter: Filter { get } +} + +extension CIImageProcessor { + public func process(item: ImageProcessItem, options: KingfisherOptionsInfo) -> Image? { + switch item { + case .image(let image): + return image.kf.apply(filter) + case .data(_): + return (DefaultImageProcessor.default >> self).process(item: item, options: options) + } + } +} + +/// Wrapper for a `Transformer` of CIImage filters. +public struct Filter { + + let transform: Transformer + + public init(tranform: @escaping Transformer) { + self.transform = tranform + } + + /// Tint filter which will apply a tint color to images. + public static var tint: (Color) -> Filter = { + color in + Filter { input in + let colorFilter = CIFilter(name: "CIConstantColorGenerator")! + colorFilter.setValue(CIColor(color: color), forKey: kCIInputColorKey) + + let colorImage = colorFilter.outputImage + let filter = CIFilter(name: "CISourceOverCompositing")! + filter.setValue(colorImage, forKey: kCIInputImageKey) + filter.setValue(input, forKey: kCIInputBackgroundImageKey) + return filter.outputImage?.cropping(to: input.extent) + } + } + + public typealias ColorElement = (CGFloat, CGFloat, CGFloat, CGFloat) + + /// Color control filter which will apply color control change to images. + public static var colorControl: (ColorElement) -> Filter = { + brightness, contrast, saturation, inputEV in + Filter { input in + let paramsColor = [kCIInputBrightnessKey: brightness, + kCIInputContrastKey: contrast, + kCIInputSaturationKey: saturation] + + let blackAndWhite = input.applyingFilter("CIColorControls", withInputParameters: paramsColor) + let paramsExposure = [kCIInputEVKey: inputEV] + return blackAndWhite.applyingFilter("CIExposureAdjust", withInputParameters: paramsExposure) + } + + } +} + +extension Kingfisher where Base: Image { + /// Apply a `Filter` containing `CIImage` transformer to `self`. + /// + /// - parameter filter: The filter used to transform `self`. + /// + /// - returns: A transformed image by input `Filter`. + /// + /// - Note: Only CG-based images are supported. If any error happens during transforming, `self` will be returned. + public func apply(_ filter: Filter) -> Image { + + guard let cgImage = cgImage else { + assertionFailure("[Kingfisher] Tint image only works for CG-based image.") + return base + } + + let inputImage = CIImage(cgImage: cgImage) + guard let outputImage = filter.transform(inputImage) else { + return base + } + + guard let result = ciContext.createCGImage(outputImage, from: outputImage.extent) else { + assertionFailure("[Kingfisher] Can not make an tint image within context.") + return base + } + + #if os(macOS) + return fixedForRetinaPixel(cgImage: result, to: size) + #else + return Image(cgImage: result) + #endif + } + +} + +public extension Image { + + /// Apply a `Filter` containing `CIImage` transformer to `self`. + /// + /// - parameter filter: The filter used to transform `self`. + /// + /// - returns: A transformed image by input `Filter`. + /// + /// - Note: Only CG-based images are supported. If any error happens during transforming, `self` will be returned. + @available(*, deprecated, + message: "Extensions directly on Image are deprecated. Use `kf.apply` instead.", + renamed: "kf.apply") + public func kf_apply(_ filter: Filter) -> Image { + return kf.apply(filter) + } +} diff --git a/GeneralUtils/GeneralUtils/libs/Kingfisher/Image.swift b/GeneralUtils/GeneralUtils/libs/Kingfisher/Image.swift new file mode 100755 index 0000000..3b9536d --- /dev/null +++ b/GeneralUtils/GeneralUtils/libs/Kingfisher/Image.swift @@ -0,0 +1,938 @@ +// +// Image.swift +// Kingfisher +// +// Created by Wei Wang on 16/1/6. +// +// Copyright (c) 2016 Wei Wang +// +// Permission is hereby granted, free of charge, to any person obtaining a copy +// of this software and associated documentation files (the "Software"), to deal +// in the Software without restriction, including without limitation the rights +// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +// copies of the Software, and to permit persons to whom the Software is +// furnished to do so, subject to the following conditions: +// +// The above copyright notice and this permission notice shall be included in +// all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN +// THE SOFTWARE. + + +#if os(macOS) +import AppKit +private var imagesKey: Void? +private var durationKey: Void? +#else +import UIKit +import MobileCoreServices +private var imageSourceKey: Void? +private var animatedImageDataKey: Void? +#endif + +import ImageIO +import CoreGraphics + +#if !os(watchOS) +import Accelerate +import CoreImage +#endif + +// MARK: - Image Properties +extension Kingfisher where Base: Image { + #if os(macOS) + var cgImage: CGImage? { + return base.cgImage(forProposedRect: nil, context: nil, hints: nil) + } + + var scale: CGFloat { + return 1.0 + } + + fileprivate(set) var images: [Image]? { + get { + return objc_getAssociatedObject(base, &imagesKey) as? [Image] + } + set { + objc_setAssociatedObject(base, &imagesKey, newValue, .OBJC_ASSOCIATION_RETAIN_NONATOMIC) + } + } + + fileprivate(set) var duration: TimeInterval { + get { + return objc_getAssociatedObject(base, &durationKey) as? TimeInterval ?? 0.0 + } + set { + objc_setAssociatedObject(base, &durationKey, newValue, .OBJC_ASSOCIATION_RETAIN_NONATOMIC) + } + } + + var size: CGSize { + return base.representations.reduce(CGSize.zero, { size, rep in + return CGSize(width: max(size.width, CGFloat(rep.pixelsWide)), height: max(size.height, CGFloat(rep.pixelsHigh))) + }) + } + + #else + var cgImage: CGImage? { + return base.cgImage + } + + var scale: CGFloat { + return base.scale + } + + var images: [Image]? { + return base.images + } + + var duration: TimeInterval { + return base.duration + } + + fileprivate(set) var imageSource: ImageSource? { + get { + return objc_getAssociatedObject(base, &imageSourceKey) as? ImageSource + } + set { + objc_setAssociatedObject(base, &imageSourceKey, newValue, .OBJC_ASSOCIATION_RETAIN_NONATOMIC) + } + } + + fileprivate(set) var animatedImageData: Data? { + get { + return objc_getAssociatedObject(base, &animatedImageDataKey) as? Data + } + set { + objc_setAssociatedObject(base, &animatedImageDataKey, newValue, .OBJC_ASSOCIATION_RETAIN_NONATOMIC) + } + } + + var size: CGSize { + return base.size + } + #endif +} + +// MARK: - Image Conversion +extension Kingfisher where Base: Image { + #if os(macOS) + static func image(cgImage: CGImage, scale: CGFloat, refImage: Image?) -> Image { + return Image(cgImage: cgImage, size: CGSize.zero) + } + + /** + Normalize the image. This method does nothing in OS X. + + - returns: The image itself. + */ + public var normalized: Image { + return base + } + + static func animated(with images: [Image], forDuration forDurationduration: TimeInterval) -> Image? { + return nil + } + #else + static func image(cgImage: CGImage, scale: CGFloat, refImage: Image?) -> Image { + if let refImage = refImage { + return Image(cgImage: cgImage, scale: scale, orientation: refImage.imageOrientation) + } else { + return Image(cgImage: cgImage, scale: scale, orientation: .up) + } + } + + /** + Normalize the image. This method will try to redraw an image with orientation and scale considered. + + - returns: The normalized image with orientation set to up and correct scale. + */ + public var normalized: Image { + // prevent animated image (GIF) lose it's images + guard images == nil else { return base } + // No need to do anything if already up + guard base.imageOrientation != .up else { return base } + + return draw(cgImage: nil, to: size) { + base.draw(in: CGRect(origin: CGPoint.zero, size: size)) + } + } + + static func animated(with images: [Image], forDuration duration: TimeInterval) -> Image? { + return .animatedImage(with: images, duration: duration) + } + #endif +} + +// MARK: - Image Representation +extension Kingfisher where Base: Image { + // MARK: - PNG + func pngRepresentation() -> Data? { + #if os(macOS) + guard let cgimage = cgImage else { + return nil + } + let rep = NSBitmapImageRep(cgImage: cgimage) + return rep.representation(using: .PNG, properties: [:]) + #else + return UIImagePNGRepresentation(base) + #endif + } + + // MARK: - JPEG + func jpegRepresentation(compressionQuality: CGFloat) -> Data? { + #if os(macOS) + guard let cgImage = cgImage else { + return nil + } + let rep = NSBitmapImageRep(cgImage: cgImage) + return rep.representation(using:.JPEG, properties: [NSImageCompressionFactor: compressionQuality]) + #else + return UIImageJPEGRepresentation(base, compressionQuality) + #endif + } + + // MARK: - GIF + func gifRepresentation() -> Data? { + #if os(macOS) + return gifRepresentation(duration: 0.0, repeatCount: 0) + #else + return animatedImageData + #endif + } + + #if os(macOS) + func gifRepresentation(duration: TimeInterval, repeatCount: Int) -> Data? { + guard let images = images else { + return nil + } + + let frameCount = images.count + let gifDuration = duration <= 0.0 ? duration / Double(frameCount) : duration / Double(frameCount) + + let frameProperties = [kCGImagePropertyGIFDictionary as String: [kCGImagePropertyGIFDelayTime as String: gifDuration]] + let imageProperties = [kCGImagePropertyGIFDictionary as String: [kCGImagePropertyGIFLoopCount as String: repeatCount]] + + let data = NSMutableData() + + guard let destination = CGImageDestinationCreateWithData(data, kUTTypeGIF, frameCount, nil) else { + return nil + } + CGImageDestinationSetProperties(destination, imageProperties as CFDictionary) + + for image in images { + CGImageDestinationAddImage(destination, image.kf.cgImage!, frameProperties as CFDictionary) + } + + return CGImageDestinationFinalize(destination) ? data.copy() as? Data : nil + } + #endif +} + +// MARK: - Create images from data +extension Kingfisher where Base: Image { + static func animated(with data: Data, scale: CGFloat = 1.0, duration: TimeInterval = 0.0, preloadAll: Bool) -> Image? { + + func decode(from imageSource: CGImageSource, for options: NSDictionary) -> ([Image], TimeInterval)? { + + //Calculates frame duration for a gif frame out of the kCGImagePropertyGIFDictionary dictionary + func frameDuration(from gifInfo: NSDictionary) -> Double { + let gifDefaultFrameDuration = 0.100 + + let unclampedDelayTime = gifInfo[kCGImagePropertyGIFUnclampedDelayTime as String] as? NSNumber + let delayTime = gifInfo[kCGImagePropertyGIFDelayTime as String] as? NSNumber + let duration = unclampedDelayTime ?? delayTime + + guard let frameDuration = duration else { return gifDefaultFrameDuration } + + return frameDuration.doubleValue > 0.011 ? frameDuration.doubleValue : gifDefaultFrameDuration + } + + let frameCount = CGImageSourceGetCount(imageSource) + var images = [Image]() + var gifDuration = 0.0 + for i in 0 ..< frameCount { + + guard let imageRef = CGImageSourceCreateImageAtIndex(imageSource, i, options) else { + return nil + } + + if frameCount == 1 { + // Single frame + gifDuration = Double.infinity + } else { + // Animated GIF + guard let properties = CGImageSourceCopyPropertiesAtIndex(imageSource, i, nil), + let gifInfo = (properties as NSDictionary)[kCGImagePropertyGIFDictionary as String] as? NSDictionary else + { + return nil + } + gifDuration += frameDuration(from: gifInfo) + } + + images.append(Kingfisher.image(cgImage: imageRef, scale: scale, refImage: nil)) + } + + return (images, gifDuration) + } + + // Start of kf.animatedImageWithGIFData + let options: NSDictionary = [kCGImageSourceShouldCache as String: true, kCGImageSourceTypeIdentifierHint as String: kUTTypeGIF] + guard let imageSource = CGImageSourceCreateWithData(data as CFData, options) else { + return nil + } + + #if os(macOS) + guard let (images, gifDuration) = decode(from: imageSource, for: options) else { + return nil + } + let image = Image(data: data) + image?.kf.images = images + image?.kf.duration = gifDuration + + return image + #else + + if preloadAll { + guard let (images, gifDuration) = decode(from: imageSource, for: options) else { + return nil + } + let image = Kingfisher.animated(with: images, forDuration: duration <= 0.0 ? gifDuration : duration) + image?.kf.animatedImageData = data + return image + } else { + let image = Image(data: data) + image?.kf.animatedImageData = data + image?.kf.imageSource = ImageSource(ref: imageSource) + return image + } + #endif + } + + static func image(data: Data, scale: CGFloat, preloadAllGIFData: Bool) -> Image? { + var image: Image? + + #if os(macOS) + switch data.kf.imageFormat { + case .JPEG: image = Image(data: data) + case .PNG: image = Image(data: data) + case .GIF: image = Kingfisher.animated(with: data, scale: scale, duration: 0.0, preloadAll: preloadAllGIFData) + case .unknown: image = Image(data: data) + } + #else + switch data.kf.imageFormat { + case .JPEG: image = Image(data: data, scale: scale) + case .PNG: image = Image(data: data, scale: scale) + case .GIF: image = Kingfisher.animated(with: data, scale: scale, duration: 0.0, preloadAll: preloadAllGIFData) + case .unknown: image = Image(data: data, scale: scale) + } + #endif + + return image + } +} + +// MARK: - Image Transforming +extension Kingfisher where Base: Image { + // MARK: - Round Corner + /// Create a round corner image based on `self`. + /// + /// - parameter radius: The round corner radius of creating image. + /// - parameter size: The target size of creating image. + /// - parameter scale: The image scale of creating image. + /// + /// - returns: An image with round corner of `self`. + /// + /// - Note: This method only works for CG-based image. + public func image(withRoundRadius radius: CGFloat, fit size: CGSize, scale: CGFloat) -> Image { + + guard let cgImage = cgImage else { + assertionFailure("[Kingfisher] Round corder image only works for CG-based image.") + return base + } + + let rect = CGRect(origin: CGPoint(x: 0, y: 0), size: size) + return draw(cgImage: cgImage, to: size) { + #if os(macOS) + let path = NSBezierPath(roundedRect: rect, xRadius: radius, yRadius: radius) + path.windingRule = .evenOddWindingRule + path.addClip() + base.draw(in: rect) + #else + guard let context = UIGraphicsGetCurrentContext() else { + assertionFailure("[Kingfisher] Failed to create CG context for image.") + return + } + let path = UIBezierPath(roundedRect: rect, byRoundingCorners: .allCorners, cornerRadii: CGSize(width: radius, height: radius)).cgPath + context.addPath(path) + context.clip() + base.draw(in: rect) + #endif + } + } + + #if os(iOS) || os(tvOS) + func resize(to size: CGSize, for contentMode: UIViewContentMode) -> Image { + switch contentMode { + case .scaleAspectFit: + let newSize = self.size.kf.constrained(size) + return resize(to: newSize) + case .scaleAspectFill: + let newSize = self.size.kf.filling(size) + return resize(to: newSize) + default: + return resize(to: size) + } + } + #endif + + // MARK: - Resize + + /// Resize `self` to an image of new size. + /// + /// - parameter size: The target size. + /// + /// - returns: An image with new size. + /// + /// - Note: This method only works for CG-based image. + public func resize(to size: CGSize) -> Image { + + guard let cgImage = cgImage else { + assertionFailure("[Kingfisher] Resize only works for CG-based image.") + return base + } + + let rect = CGRect(origin: CGPoint(x: 0, y: 0), size: size) + return draw(cgImage: cgImage, to: size) { + #if os(macOS) + base.draw(in: rect, from: NSRect.zero, operation: .copy, fraction: 1.0) + #else + base.draw(in: rect) + #endif + } + } + + // MARK: - Blur + + /// Create an image with blur effect based on `self`. + /// + /// - parameter radius: The blur radius should be used when creating blue. + /// + /// - returns: An image with blur effect applied. + /// + /// - Note: This method only works for CG-based image. + public func blurred(withRadius radius: CGFloat) -> Image { + #if os(watchOS) + return base + #else + guard let cgImage = cgImage else { + assertionFailure("[Kingfisher] Blur only works for CG-based image.") + return base + } + + // http://www.w3.org/TR/SVG/filters.html#feGaussianBlurElement + // let d = floor(s * 3*sqrt(2*pi)/4 + 0.5) + // if d is odd, use three box-blurs of size 'd', centered on the output pixel. + let s = max(radius, 2.0) + // We will do blur on a resized image (*0.5), so the blur radius could be half as well. + var targetRadius = floor((Double(s * 3.0) * sqrt(2 * M_PI) / 4.0 + 0.5)) + + if targetRadius.isEven { + targetRadius += 1 + } + + let iterations: Int + if radius < 0.5 { + iterations = 1 + } else if radius < 1.5 { + iterations = 2 + } else { + iterations = 3 + } + + let w = Int(size.width) + let h = Int(size.height) + let rowBytes = Int(CGFloat(cgImage.bytesPerRow)) + + let inDataPointer = UnsafeMutablePointer.allocate(capacity: rowBytes * Int(h)) + inDataPointer.initialize(to: 0) + defer { + inDataPointer.deinitialize() + inDataPointer.deallocate(capacity: rowBytes * Int(h)) + } + + let bitmapInfo = cgImage.bitmapInfo.fixed + guard let context = CGContext(data: inDataPointer, + width: w, + height: h, + bitsPerComponent: cgImage.bitsPerComponent, + bytesPerRow: rowBytes, + space: cgImage.colorSpace ?? CGColorSpaceCreateDeviceRGB(), + bitmapInfo: bitmapInfo.rawValue) else + { + assertionFailure("[Kingfisher] Failed to create CG context for blurring image.") + return base + } + + context.draw(cgImage, in: CGRect(x: 0, y: 0, width: w, height: h)) + + + var inBuffer = vImage_Buffer(data: inDataPointer, height: vImagePixelCount(h), width: vImagePixelCount(w), rowBytes: rowBytes) + + let outDataPointer = UnsafeMutablePointer.allocate(capacity: rowBytes * Int(h)) + outDataPointer.initialize(to: 0) + defer { + outDataPointer.deinitialize() + outDataPointer.deallocate(capacity: rowBytes * Int(h)) + } + + var outBuffer = vImage_Buffer(data: outDataPointer, height: vImagePixelCount(h), width: vImagePixelCount(w), rowBytes: rowBytes) + + for _ in 0 ..< iterations { + vImageBoxConvolve_ARGB8888(&inBuffer, &outBuffer, nil, 0, 0, UInt32(targetRadius), UInt32(targetRadius), nil, vImage_Flags(kvImageEdgeExtend)) + (inBuffer, outBuffer) = (outBuffer, inBuffer) + } + + guard let outContext = CGContext(data: inDataPointer, + width: w, + height: h, + bitsPerComponent: cgImage.bitsPerComponent, + bytesPerRow: rowBytes, + space: cgImage.colorSpace ?? CGColorSpaceCreateDeviceRGB(), + bitmapInfo: bitmapInfo.rawValue) else + { + assertionFailure("[Kingfisher] Failed to create CG context for blurring image.") + return base + } + + #if os(macOS) + let result = outContext.makeImage().flatMap { fixedForRetinaPixel(cgImage: $0, to: size) } + #else + let result = outContext.makeImage().flatMap { Image(cgImage: $0) } + #endif + guard let blurredImage = result else { + assertionFailure("[Kingfisher] Can not make an blurred image within this context.") + return base + } + + return blurredImage + #endif + } + + // MARK: - Overlay + + /// Create an image from `self` with a color overlay layer. + /// + /// - parameter color: The color should be use to overlay. + /// - parameter fraction: Fraction of input color. From 0.0 to 1.0. 0.0 means solid color, 1.0 means transparent overlay. + /// + /// - returns: An image with a color overlay applied. + /// + /// - Note: This method only works for CG-based image. + public func overlaying(with color: Color, fraction: CGFloat) -> Image { + + guard let cgImage = cgImage else { + assertionFailure("[Kingfisher] Overlaying only works for CG-based image.") + return base + } + + let rect = CGRect(x: 0, y: 0, width: size.width, height: size.height) + return draw(cgImage: cgImage, to: rect.size) { + #if os(macOS) + base.draw(in: rect) + if fraction > 0 { + color.withAlphaComponent(1 - fraction).set() + NSRectFillUsingOperation(rect, .sourceAtop) + } + #else + color.set() + UIRectFill(rect) + base.draw(in: rect, blendMode: .destinationIn, alpha: 1.0) + + if fraction > 0 { + base.draw(in: rect, blendMode: .sourceAtop, alpha: fraction) + } + #endif + } + } + + // MARK: - Tint + + /// Create an image from `self` with a color tint. + /// + /// - parameter color: The color should be used to tint `self` + /// + /// - returns: An image with a color tint applied. + public func tinted(with color: Color) -> Image { + #if os(watchOS) + return base + #else + return apply(.tint(color)) + #endif + } + + // MARK: - Color Control + + /// Create an image from `self` with color control. + /// + /// - parameter brightness: Brightness changing to image. + /// - parameter contrast: Contrast changing to image. + /// - parameter saturation: Saturation changing to image. + /// - parameter inputEV: InputEV changing to image. + /// + /// - returns: An image with color control applied. + public func adjusted(brightness: CGFloat, contrast: CGFloat, saturation: CGFloat, inputEV: CGFloat) -> Image { + #if os(watchOS) + return base + #else + return apply(.colorControl(brightness, contrast, saturation, inputEV)) + #endif + } +} + +// MARK: - Decode +extension Kingfisher where Base: Image { + var decoded: Image? { + return decoded(scale: scale) + } + + func decoded(scale: CGFloat) -> Image { + // prevent animated image (GIF) lose it's images + #if os(iOS) + if imageSource != nil { return base } + #else + if images != nil { return base } + #endif + + guard let imageRef = self.cgImage else { + assertionFailure("[Kingfisher] Decoding only works for CG-based image.") + return base + } + let colorSpace = CGColorSpaceCreateDeviceRGB() + let bitmapInfo = imageRef.bitmapInfo.fixed + + guard let context = CGContext(data: nil, width: imageRef.width, height: imageRef.height, bitsPerComponent: 8, bytesPerRow: 0, space: colorSpace, bitmapInfo: bitmapInfo.rawValue) else { + assertionFailure("[Kingfisher] Decoding fails to create a valid context.") + return base + } + + let rect = CGRect(x: 0, y: 0, width: imageRef.width, height: imageRef.height) + context.draw(imageRef, in: rect) + let decompressedImageRef = context.makeImage() + return Kingfisher.image(cgImage: decompressedImageRef!, scale: scale, refImage: base) + } +} + +/// Reference the source image reference +class ImageSource { + var imageRef: CGImageSource? + init(ref: CGImageSource) { + self.imageRef = ref + } +} + +// MARK: - Image format +private struct ImageHeaderData { + static var PNG: [UInt8] = [0x89, 0x50, 0x4E, 0x47, 0x0D, 0x0A, 0x1A, 0x0A] + static var JPEG_SOI: [UInt8] = [0xFF, 0xD8] + static var JPEG_IF: [UInt8] = [0xFF] + static var GIF: [UInt8] = [0x47, 0x49, 0x46] +} + +enum ImageFormat { + case unknown, PNG, JPEG, GIF +} + + +// MARK: - Misc Helpers +public struct DataProxy { + fileprivate let base: Data + init(proxy: Data) { + base = proxy + } +} + +extension Data: KingfisherCompatible { + public typealias CompatibleType = DataProxy + public var kf: DataProxy { + return DataProxy(proxy: self) + } +} + +extension DataProxy { + var imageFormat: ImageFormat { + var buffer = [UInt8](repeating: 0, count: 8) + (base as NSData).getBytes(&buffer, length: 8) + if buffer == ImageHeaderData.PNG { + return .PNG + } else if buffer[0] == ImageHeaderData.JPEG_SOI[0] && + buffer[1] == ImageHeaderData.JPEG_SOI[1] && + buffer[2] == ImageHeaderData.JPEG_IF[0] + { + return .JPEG + } else if buffer[0] == ImageHeaderData.GIF[0] && + buffer[1] == ImageHeaderData.GIF[1] && + buffer[2] == ImageHeaderData.GIF[2] + { + return .GIF + } + + return .unknown + } +} + +public struct CGSizeProxy { + fileprivate let base: CGSize + init(proxy: CGSize) { + base = proxy + } +} + +extension CGSize: KingfisherCompatible { + public typealias CompatibleType = CGSizeProxy + public var kf: CGSizeProxy { + return CGSizeProxy(proxy: self) + } +} + +extension CGSizeProxy { + func constrained(_ size: CGSize) -> CGSize { + let aspectWidth = round(aspectRatio * size.height) + let aspectHeight = round(size.width / aspectRatio) + + return aspectWidth > size.width ? CGSize(width: size.width, height: aspectHeight) : CGSize(width: aspectWidth, height: size.height) + } + + func filling(_ size: CGSize) -> CGSize { + let aspectWidth = round(aspectRatio * size.height) + let aspectHeight = round(size.width / aspectRatio) + + return aspectWidth < size.width ? CGSize(width: size.width, height: aspectHeight) : CGSize(width: aspectWidth, height: size.height) + } + + private var aspectRatio: CGFloat { + return base.height == 0.0 ? 1.0 : base.width / base.height + } +} + +extension CGBitmapInfo { + var fixed: CGBitmapInfo { + var fixed = self + let alpha = (rawValue & CGBitmapInfo.alphaInfoMask.rawValue) + if alpha == CGImageAlphaInfo.none.rawValue { + fixed.remove(.alphaInfoMask) + fixed = CGBitmapInfo(rawValue: fixed.rawValue | CGImageAlphaInfo.noneSkipFirst.rawValue) + } else if !(alpha == CGImageAlphaInfo.noneSkipFirst.rawValue) || !(alpha == CGImageAlphaInfo.noneSkipLast.rawValue) { + fixed.remove(.alphaInfoMask) + fixed = CGBitmapInfo(rawValue: fixed.rawValue | CGImageAlphaInfo.premultipliedFirst.rawValue) + } + return fixed + } +} + + +extension Kingfisher where Base: Image { + + func draw(cgImage: CGImage?, to size: CGSize, draw: ()->()) -> Image { + #if os(macOS) + guard let rep = NSBitmapImageRep( + bitmapDataPlanes: nil, + pixelsWide: Int(size.width), + pixelsHigh: Int(size.height), + bitsPerSample: cgImage?.bitsPerComponent ?? 8, + samplesPerPixel: 4, + hasAlpha: true, + isPlanar: false, + colorSpaceName: NSCalibratedRGBColorSpace, + bytesPerRow: 0, + bitsPerPixel: 0) else + { + assertionFailure("[Kingfisher] Image representation cannot be created.") + return base + } + rep.size = size + + NSGraphicsContext.saveGraphicsState() + + let context = NSGraphicsContext(bitmapImageRep: rep) + NSGraphicsContext.setCurrent(context) + draw() + NSGraphicsContext.restoreGraphicsState() + + let outputImage = Image(size: size) + outputImage.addRepresentation(rep) + return outputImage + #else + + UIGraphicsBeginImageContextWithOptions(size, false, scale) + defer { UIGraphicsEndImageContext() } + draw() + return UIGraphicsGetImageFromCurrentImageContext() ?? base + + #endif + } + + #if os(macOS) + func fixedForRetinaPixel(cgImage: CGImage, to size: CGSize) -> Image { + + let image = Image(cgImage: cgImage, size: base.size) + let rect = CGRect(origin: CGPoint(x: 0, y: 0), size: size) + + return draw(cgImage: cgImage, to: self.size) { + image.draw(in: rect, from: NSRect.zero, operation: .copy, fraction: 1.0) + } + } + #endif +} + + +extension CGContext { + static func createARGBContext(from imageRef: CGImage) -> CGContext? { + + let w = imageRef.width + let h = imageRef.height + let bytesPerRow = w * 4 + let colorSpace = CGColorSpaceCreateDeviceRGB() + + let data = malloc(bytesPerRow * h) + defer { + free(data) + } + + let bitmapInfo = imageRef.bitmapInfo.fixed + + // Create the bitmap context. We want pre-multiplied ARGB, 8-bits + // per component. Regardless of what the source image format is + // (CMYK, Grayscale, and so on) it will be converted over to the format + // specified here. + return CGContext(data: data, + width: w, + height: h, + bitsPerComponent: imageRef.bitsPerComponent, + bytesPerRow: bytesPerRow, + space: colorSpace, + bitmapInfo: bitmapInfo.rawValue) + } +} + +extension Double { + var isEven: Bool { + return truncatingRemainder(dividingBy: 2.0) == 0 + } +} + +// MARK: - Deprecated. Only for back compatibility. +extension Image { + /** + Normalize the image. This method does nothing in OS X. + + - returns: The image itself. + */ + @available(*, deprecated, + message: "Extensions directly on Image are deprecated. Use `kf.normalized` instead.", + renamed: "kf.normalized") + public func kf_normalized() -> Image { + return kf.normalized + } + + // MARK: - Round Corner + + /// Create a round corner image based on `self`. + /// + /// - parameter radius: The round corner radius of creating image. + /// - parameter size: The target size of creating image. + /// - parameter scale: The image scale of creating image. + /// + /// - returns: An image with round corner of `self`. + /// + /// - Note: This method only works for CG-based image. + @available(*, deprecated, + message: "Extensions directly on Image are deprecated. Use `kf.image(withRoundRadius:fit:scale:)` instead.", + renamed: "kf.image") + public func kf_image(withRoundRadius radius: CGFloat, fit size: CGSize, scale: CGFloat) -> Image { + return kf.image(withRoundRadius: radius, fit: size, scale: scale) + } + + // MARK: - Resize + /// Resize `self` to an image of new size. + /// + /// - parameter size: The target size. + /// + /// - returns: An image with new size. + /// + /// - Note: This method only works for CG-based image. + @available(*, deprecated, + message: "Extensions directly on Image are deprecated. Use `kf.resize(to:)` instead.", + renamed: "kf.resize") + public func kf_resize(to size: CGSize) -> Image { + return kf.resize(to: size) + } + + // MARK: - Blur + /// Create an image with blur effect based on `self`. + /// + /// - parameter radius: The blur radius should be used when creating blue. + /// + /// - returns: An image with blur effect applied. + /// + /// - Note: This method only works for CG-based image. + @available(*, deprecated, + message: "Extensions directly on Image are deprecated. Use `kf.blurred(withRadius:)` instead.", + renamed: "kf.blurred") + public func kf_blurred(withRadius radius: CGFloat) -> Image { + return kf.blurred(withRadius: radius) + } + + // MARK: - Overlay + /// Create an image from `self` with a color overlay layer. + /// + /// - parameter color: The color should be use to overlay. + /// - parameter fraction: Fraction of input color. From 0.0 to 1.0. 0.0 means solid color, 1.0 means transparent overlay. + /// + /// - returns: An image with a color overlay applied. + /// + /// - Note: This method only works for CG-based image. + @available(*, deprecated, + message: "Extensions directly on Image are deprecated. Use `kf.overlaying(with:fraction:)` instead.", + renamed: "kf.overlaying") + public func kf_overlaying(with color: Color, fraction: CGFloat) -> Image { + return kf.overlaying(with: color, fraction: fraction) + } + + // MARK: - Tint + + /// Create an image from `self` with a color tint. + /// + /// - parameter color: The color should be used to tint `self` + /// + /// - returns: An image with a color tint applied. + @available(*, deprecated, + message: "Extensions directly on Image are deprecated. Use `kf.tinted(with:)` instead.", + renamed: "kf.tinted") + public func kf_tinted(with color: Color) -> Image { + return kf.tinted(with: color) + } + + // MARK: - Color Control + + /// Create an image from `self` with color control. + /// + /// - parameter brightness: Brightness changing to image. + /// - parameter contrast: Contrast changing to image. + /// - parameter saturation: Saturation changing to image. + /// - parameter inputEV: InputEV changing to image. + /// + /// - returns: An image with color control applied. + @available(*, deprecated, + message: "Extensions directly on Image are deprecated. Use `kf.adjusted` instead.", + renamed: "kf.adjusted") + public func kf_adjusted(brightness: CGFloat, contrast: CGFloat, saturation: CGFloat, inputEV: CGFloat) -> Image { + return kf.adjusted(brightness: brightness, contrast: contrast, saturation: saturation, inputEV: inputEV) + } +} diff --git a/GeneralUtils/GeneralUtils/libs/Kingfisher/ImageCache.swift b/GeneralUtils/GeneralUtils/libs/Kingfisher/ImageCache.swift new file mode 100755 index 0000000..5877150 --- /dev/null +++ b/GeneralUtils/GeneralUtils/libs/Kingfisher/ImageCache.swift @@ -0,0 +1,692 @@ +// +// ImageCache.swift +// Kingfisher +// +// Created by Wei Wang on 15/4/6. +// +// Copyright (c) 2016 Wei Wang +// +// Permission is hereby granted, free of charge, to any person obtaining a copy +// of this software and associated documentation files (the "Software"), to deal +// in the Software without restriction, including without limitation the rights +// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +// copies of the Software, and to permit persons to whom the Software is +// furnished to do so, subject to the following conditions: +// +// The above copyright notice and this permission notice shall be included in +// all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN +// THE SOFTWARE. + +#if os(macOS) +import AppKit +#else +import UIKit +#endif + +public extension Notification.Name { + /** + This notification will be sent when the disk cache got cleaned either there are cached files expired or the total size exceeding the max allowed size. The manually invoking of `clearDiskCache` method will not trigger this notification. + + The `object` of this notification is the `ImageCache` object which sends the notification. + + A list of removed hashes (files) could be retrieved by accessing the array under `KingfisherDiskCacheCleanedHashKey` key in `userInfo` of the notification object you received. By checking the array, you could know the hash codes of files are removed. + + The main purpose of this notification is supplying a chance to maintain some necessary information on the cached files. See [this wiki](https://github.com/onevcat/Kingfisher/wiki/How-to-implement-ETag-based-304-(Not-Modified)-handling-in-Kingfisher) for a use case on it. + */ + public static var KingfisherDidCleanDiskCache = Notification.Name.init("com.onevcat.Kingfisher.KingfisherDidCleanDiskCache") +} + +/** +Key for array of cleaned hashes in `userInfo` of `KingfisherDidCleanDiskCacheNotification`. +*/ +public let KingfisherDiskCacheCleanedHashKey = "com.onevcat.Kingfisher.cleanedHash" + +/// It represents a task of retrieving image. You can call `cancel` on it to stop the process. +public typealias RetrieveImageDiskTask = DispatchWorkItem + +/** +Cache type of a cached image. + +- None: The image is not cached yet when retrieving it. +- Memory: The image is cached in memory. +- Disk: The image is cached in disk. +*/ +public enum CacheType { + case none, memory, disk +} + +/// `ImageCache` represents both the memory and disk cache system of Kingfisher. +/// While a default image cache object will be used if you prefer the extension methods of Kingfisher, +/// you can create your own cache object and configure it as your need. You could use an `ImageCache` +/// object to manipulate memory and disk cache for Kingfisher. +open class ImageCache { + + //Memory + fileprivate let memoryCache = NSCache() + + /// The largest cache cost of memory cache. The total cost is pixel count of + /// all cached images in memory. + /// Default is unlimited. Memory cache will be purged automatically when a + /// memory warning notification is received. + open var maxMemoryCost: UInt = 0 { + didSet { + self.memoryCache.totalCostLimit = Int(maxMemoryCost) + } + } + + //Disk + fileprivate let ioQueue: DispatchQueue + fileprivate var fileManager: FileManager! + + ///The disk cache location. + open let diskCachePath: String + + /// The default file extension appended to cached files. + open var pathExtension: String? + + /// The longest time duration in second of the cache being stored in disk. + /// Default is 1 week (60 * 60 * 24 * 7 seconds). + open var maxCachePeriodInSecond: TimeInterval = 60 * 60 * 24 * 7 //Cache exists for 1 week + + /// The largest disk size can be taken for the cache. It is the total + /// allocated size of cached files in bytes. + /// Default is no limit. + open var maxDiskCacheSize: UInt = 0 + + fileprivate let processQueue: DispatchQueue + + /// The default cache. + public static let `default` = ImageCache(name: "default") + + /// Closure that defines the disk cache path from a given path and cacheName. + public typealias DiskCachePathClosure = (String?, String) -> String + + /// The default DiskCachePathClosure + public final class func defaultDiskCachePathClosure(path: String?, cacheName: String) -> String { + let dstPath = path ?? NSSearchPathForDirectoriesInDomains(.cachesDirectory, .userDomainMask, true).first! + return (dstPath as NSString).appendingPathComponent(cacheName) + } + + /** + Init method. Passing a name for the cache. It represents a cache folder in the memory and disk. + + - parameter name: Name of the cache. It will be used as the memory cache name and the disk cache folder name + appending to the cache path. This value should not be an empty string. + - parameter path: Optional - Location of cache path on disk. If `nil` is passed in (the default value), + the `.cachesDirectory` in of your app will be used. + - parameter diskCachePathClosure: Closure that takes in an optional initial path string and generates + the final disk cache path. You could use it to fully customize your cache path. + + - returns: The cache object. + */ + public init(name: String, + path: String? = nil, + diskCachePathClosure: DiskCachePathClosure = ImageCache.defaultDiskCachePathClosure) + { + + if name.isEmpty { + fatalError("[Kingfisher] You should specify a name for the cache. A cache with empty name is not permitted.") + } + + let cacheName = "com.onevcat.Kingfisher.ImageCache.\(name)" + memoryCache.name = cacheName + + diskCachePath = diskCachePathClosure(path, cacheName) + + let ioQueueName = "com.onevcat.Kingfisher.ImageCache.ioQueue.\(name)" + ioQueue = DispatchQueue(label: ioQueueName) + + let processQueueName = "com.onevcat.Kingfisher.ImageCache.processQueue.\(name)" + processQueue = DispatchQueue(label: processQueueName, attributes: .concurrent) + + ioQueue.sync { fileManager = FileManager() } + +#if !os(macOS) && !os(watchOS) + NotificationCenter.default.addObserver( + self, selector: #selector(clearMemoryCache), name: .UIApplicationDidReceiveMemoryWarning, object: nil) + NotificationCenter.default.addObserver( + self, selector: #selector(cleanExpiredDiskCache), name: .UIApplicationWillTerminate, object: nil) + NotificationCenter.default.addObserver( + self, selector: #selector(backgroundCleanExpiredDiskCache), name: .UIApplicationDidEnterBackground, object: nil) +#endif + } + + deinit { + NotificationCenter.default.removeObserver(self) + } + + + // MARK: - Store & Remove + + /** + Store an image to cache. It will be saved to both memory and disk. It is an async operation. + + - parameter image: The image to be stored. + - parameter original: The original data of the image. + Kingfisher will use it to check the format of the image and optimize cache size on disk. + If `nil` is supplied, the image data will be saved as a normalized PNG file. + It is strongly suggested to supply it whenever possible, to get a better performance and disk usage. + - parameter key: Key for the image. + - parameter identifier: The identifier of processor used. If you are using a processor for the image, pass the identifier of + processor to it. + This identifier will be used to generate a corresponding key for the combination of `key` and processor. + - parameter toDisk: Whether this image should be cached to disk or not. If false, the image will be only cached in memory. + - parameter completionHandler: Called when store operation completes. + */ + open func store(_ image: Image, + original: Data? = nil, + forKey key: String, + processorIdentifier identifier: String = "", + cacheSerializer serializer: CacheSerializer = DefaultCacheSerializer.default, + toDisk: Bool = true, + completionHandler: (() -> Void)? = nil) + { + + let computedKey = key.computedKey(with: identifier) + memoryCache.setObject(image, forKey: computedKey as NSString, cost: image.kf.imageCost) + + func callHandlerInMainQueue() { + if let handler = completionHandler { + DispatchQueue.main.async { + handler() + } + } + } + + if toDisk { + ioQueue.async { + + if let data = serializer.data(with: image, original: original) { + if !self.fileManager.fileExists(atPath: self.diskCachePath) { + do { + try self.fileManager.createDirectory(atPath: self.diskCachePath, withIntermediateDirectories: true, attributes: nil) + } catch _ {} + } + + self.fileManager.createFile(atPath: self.cachePath(forComputedKey: computedKey), contents: data, attributes: nil) + } + callHandlerInMainQueue() + } + } else { + callHandlerInMainQueue() + } + } + + /** + Remove the image for key for the cache. It will be opted out from both memory and disk. + It is an async operation. + + - parameter key: Key for the image. + - parameter identifier: The identifier of processor used. If you are using a processor for the image, pass the identifier of processor to it. + This identifier will be used to generate a corresponding key for the combination of `key` and processor. + - parameter fromDisk: Whether this image should be removed from disk or not. If false, the image will be only removed from memory. + - parameter completionHandler: Called when removal operation completes. + */ + open func removeImage(forKey key: String, + processorIdentifier identifier: String = "", + fromDisk: Bool = true, + completionHandler: (() -> Void)? = nil) + { + let computedKey = key.computedKey(with: identifier) + memoryCache.removeObject(forKey: computedKey as NSString) + + func callHandlerInMainQueue() { + if let handler = completionHandler { + DispatchQueue.main.async { + handler() + } + } + } + + if fromDisk { + ioQueue.async{ + do { + try self.fileManager.removeItem(atPath: self.cachePath(forComputedKey: computedKey)) + } catch _ {} + callHandlerInMainQueue() + } + } else { + callHandlerInMainQueue() + } + } + + // MARK: - Get data from cache + + /** + Get an image for a key from memory or disk. + + - parameter key: Key for the image. + - parameter options: Options of retrieving image. If you need to retrieve an image which was + stored with a specified `ImageProcessor`, pass the processor in the option too. + - parameter completionHandler: Called when getting operation completes with image result and cached type of + this image. If there is no such key cached, the image will be `nil`. + + - returns: The retrieving task. + */ + @discardableResult + open func retrieveImage(forKey key: String, + options: KingfisherOptionsInfo?, + completionHandler: ((Image?, CacheType) -> ())?) -> RetrieveImageDiskTask? + { + // No completion handler. Not start working and early return. + guard let completionHandler = completionHandler else { + return nil + } + + var block: RetrieveImageDiskTask? + let options = options ?? KingfisherEmptyOptionsInfo + + if let image = self.retrieveImageInMemoryCache(forKey: key, options: options) { + options.callbackDispatchQueue.safeAsync { + completionHandler(image, .memory) + } + } else { + var sSelf: ImageCache! = self + block = DispatchWorkItem(block: { + // Begin to load image from disk + if let image = sSelf.retrieveImageInDiskCache(forKey: key, options: options) { + if options.backgroundDecode { + sSelf.processQueue.async { + let result = image.kf.decoded(scale: options.scaleFactor) + + sSelf.store(result, + forKey: key, + processorIdentifier: options.processor.identifier, + cacheSerializer: options.cacheSerializer, + toDisk: false, + completionHandler: nil) + + options.callbackDispatchQueue.safeAsync { + completionHandler(result, .memory) + sSelf = nil + } + } + } else { + sSelf.store(image, + forKey: key, + processorIdentifier: options.processor.identifier, + cacheSerializer: options.cacheSerializer, + toDisk: false, + completionHandler: nil + ) + options.callbackDispatchQueue.safeAsync { + completionHandler(image, .disk) + sSelf = nil + } + } + } else { + // No image found from either memory or disk + options.callbackDispatchQueue.safeAsync { + completionHandler(nil, .none) + sSelf = nil + } + } + }) + + sSelf.ioQueue.async(execute: block!) + } + + return block + } + + /** + Get an image for a key from memory. + + - parameter key: Key for the image. + - parameter options: Options of retrieving image. If you need to retrieve an image which was + stored with a specified `ImageProcessor`, pass the processor in the option too. + - returns: The image object if it is cached, or `nil` if there is no such key in the cache. + */ + open func retrieveImageInMemoryCache(forKey key: String, options: KingfisherOptionsInfo? = nil) -> Image? { + + let options = options ?? KingfisherEmptyOptionsInfo + let computedKey = key.computedKey(with: options.processor.identifier) + + return memoryCache.object(forKey: computedKey as NSString) as? Image + } + + /** + Get an image for a key from disk. + + - parameter key: Key for the image. + - parameter options: Options of retrieving image. If you need to retrieve an image which was + stored with a specified `ImageProcessor`, pass the processor in the option too. + + - returns: The image object if it is cached, or `nil` if there is no such key in the cache. + */ + open func retrieveImageInDiskCache(forKey key: String, options: KingfisherOptionsInfo? = nil) -> Image? { + + let options = options ?? KingfisherEmptyOptionsInfo + let computedKey = key.computedKey(with: options.processor.identifier) + + return diskImage(forComputedKey: computedKey, serializer: options.cacheSerializer, options: options) + } + + + // MARK: - Clear & Clean + + /** + Clear memory cache. + */ + @objc public func clearMemoryCache() { + memoryCache.removeAllObjects() + } + + /** + Clear disk cache. This is an async operation. + + - parameter completionHander: Called after the operation completes. + */ + open func clearDiskCache(completion handler: (()->())? = nil) { + ioQueue.async { + do { + try self.fileManager.removeItem(atPath: self.diskCachePath) + try self.fileManager.createDirectory(atPath: self.diskCachePath, withIntermediateDirectories: true, attributes: nil) + } catch _ { } + + if let handler = handler { + DispatchQueue.main.async { + handler() + } + } + } + } + + /** + Clean expired disk cache. This is an async operation. + */ + @objc fileprivate func cleanExpiredDiskCache() { + cleanExpiredDiskCache(completion: nil) + } + + /** + Clean expired disk cache. This is an async operation. + + - parameter completionHandler: Called after the operation completes. + */ + open func cleanExpiredDiskCache(completion handler: (()->())? = nil) { + + // Do things in cocurrent io queue + ioQueue.async { + + var (URLsToDelete, diskCacheSize, cachedFiles) = self.travelCachedFiles(onlyForCacheSize: false) + + for fileURL in URLsToDelete { + do { + try self.fileManager.removeItem(at: fileURL) + } catch _ { } + } + + if self.maxDiskCacheSize > 0 && diskCacheSize > self.maxDiskCacheSize { + let targetSize = self.maxDiskCacheSize / 2 + + // Sort files by last modify date. We want to clean from the oldest files. + let sortedFiles = cachedFiles.keysSortedByValue { + resourceValue1, resourceValue2 -> Bool in + + if let date1 = resourceValue1.contentAccessDate, + let date2 = resourceValue2.contentAccessDate + { + return date1.compare(date2) == .orderedAscending + } + + // Not valid date information. This should not happen. Just in case. + return true + } + + for fileURL in sortedFiles { + + do { + try self.fileManager.removeItem(at: fileURL) + } catch { } + + URLsToDelete.append(fileURL) + + if let fileSize = cachedFiles[fileURL]?.totalFileAllocatedSize { + diskCacheSize -= UInt(fileSize) + } + + if diskCacheSize < targetSize { + break + } + } + } + + DispatchQueue.main.async { + + if URLsToDelete.count != 0 { + let cleanedHashes = URLsToDelete.map { $0.lastPathComponent } + NotificationCenter.default.post(name: .KingfisherDidCleanDiskCache, object: self, userInfo: [KingfisherDiskCacheCleanedHashKey: cleanedHashes]) + } + + handler?() + } + } + } + + fileprivate func travelCachedFiles(onlyForCacheSize: Bool) -> (urlsToDelete: [URL], diskCacheSize: UInt, cachedFiles: [URL: URLResourceValues]) { + + let diskCacheURL = URL(fileURLWithPath: diskCachePath) + let resourceKeys: Set = [.isDirectoryKey, .contentAccessDateKey, .totalFileAllocatedSizeKey] + let expiredDate = Date(timeIntervalSinceNow: -maxCachePeriodInSecond) + + var cachedFiles = [URL: URLResourceValues]() + var urlsToDelete = [URL]() + var diskCacheSize: UInt = 0 + + if let fileEnumerator = self.fileManager.enumerator(at: diskCacheURL, includingPropertiesForKeys: Array(resourceKeys), options: FileManager.DirectoryEnumerationOptions.skipsHiddenFiles, errorHandler: nil), + let urls = fileEnumerator.allObjects as? [URL] + { + for fileUrl in urls { + + do { + let resourceValues = try fileUrl.resourceValues(forKeys: resourceKeys) + // If it is a Directory. Continue to next file URL. + if resourceValues.isDirectory == true { + continue + } + + if !onlyForCacheSize { + // If this file is expired, add it to URLsToDelete + if let lastAccessData = resourceValues.contentAccessDate { + if (lastAccessData as NSDate).laterDate(expiredDate) == expiredDate { + urlsToDelete.append(fileUrl) + continue + } + } + } + + if let fileSize = resourceValues.totalFileAllocatedSize { + diskCacheSize += UInt(fileSize) + if !onlyForCacheSize { + cachedFiles[fileUrl] = resourceValues + } + } + } catch _ { } + } + } + + return (urlsToDelete, diskCacheSize, cachedFiles) + } + +#if !os(macOS) && !os(watchOS) + /** + Clean expired disk cache when app in background. This is an async operation. + In most cases, you should not call this method explicitly. + It will be called automatically when `UIApplicationDidEnterBackgroundNotification` received. + */ + @objc public func backgroundCleanExpiredDiskCache() { + // if 'sharedApplication()' is unavailable, then return + guard let sharedApplication = Kingfisher.shared else { return } + + func endBackgroundTask(_ task: inout UIBackgroundTaskIdentifier) { + sharedApplication.endBackgroundTask(task) + task = UIBackgroundTaskInvalid + } + + var backgroundTask: UIBackgroundTaskIdentifier! + backgroundTask = sharedApplication.beginBackgroundTask { + endBackgroundTask(&backgroundTask!) + } + + cleanExpiredDiskCache { + endBackgroundTask(&backgroundTask!) + } + } +#endif + + + // MARK: - Check cache status + + /** + * Cache result for checking whether an image is cached for a key. + */ + public struct CacheCheckResult { + public let cached: Bool + public let cacheType: CacheType? + } + + /** + Check whether an image is cached for a key. + + - parameter key: Key for the image. + + - returns: The check result. + */ + open func isImageCached(forKey key: String, processorIdentifier identifier: String = "") -> CacheCheckResult { + + let computedKey = key.computedKey(with: identifier) + + if memoryCache.object(forKey: computedKey as NSString) != nil { + return CacheCheckResult(cached: true, cacheType: .memory) + } + + let filePath = cachePath(forComputedKey: computedKey) + + var diskCached = false + ioQueue.sync { + diskCached = fileManager.fileExists(atPath: filePath) + } + + if diskCached { + return CacheCheckResult(cached: true, cacheType: .disk) + } + + return CacheCheckResult(cached: false, cacheType: nil) + } + + /** + Get the hash for the key. This could be used for matching files. + + - parameter key: The key which is used for caching. + - parameter identifier: The identifier of processor used. If you are using a processor for the image, pass the identifier of processor to it. + + - returns: Corresponding hash. + */ + open func hash(forKey key: String, processorIdentifier identifier: String = "") -> String { + let computedKey = key.computedKey(with: identifier) + return cacheFileName(forComputedKey: computedKey) + } + + /** + Calculate the disk size taken by cache. + It is the total allocated size of the cached files in bytes. + + - parameter completionHandler: Called with the calculated size when finishes. + */ + open func calculateDiskCacheSize(completion handler: @escaping ((_ size: UInt) -> ())) { + ioQueue.async { + let (_, diskCacheSize, _) = self.travelCachedFiles(onlyForCacheSize: true) + DispatchQueue.main.async { + handler(diskCacheSize) + } + } + } + + /** + Get the cache path for the key. + It is useful for projects with UIWebView or anyone that needs access to the local file path. + + i.e. Replace the `` tag in your HTML. + + - Note: This method does not guarantee there is an image already cached in the path. It just returns the path + that the image should be. + You could use `isImageCached(forKey:)` method to check whether the image is cached under that key. + */ + open func cachePath(forKey key: String, processorIdentifier identifier: String = "") -> String { + let computedKey = key.computedKey(with: identifier) + return cachePath(forComputedKey: computedKey) + } + + open func cachePath(forComputedKey key: String) -> String { + let fileName = cacheFileName(forComputedKey: key) + return (diskCachePath as NSString).appendingPathComponent(fileName) + } +} + +// MARK: - Internal Helper +extension ImageCache { + + func diskImage(forComputedKey key: String, serializer: CacheSerializer, options: KingfisherOptionsInfo) -> Image? { + if let data = diskImageData(forComputedKey: key) { + return serializer.image(with: data, options: options) + } else { + return nil + } + } + + func diskImageData(forComputedKey key: String) -> Data? { + let filePath = cachePath(forComputedKey: key) + return (try? Data(contentsOf: URL(fileURLWithPath: filePath))) + } + + func cacheFileName(forComputedKey key: String) -> String { + if let ext = self.pathExtension { + return (key.kf.md5 as NSString).appendingPathExtension(ext)! + } + return key.kf.md5 + } +} + +extension Kingfisher where Base: Image { + var imageCost: Int { + return images == nil ? + Int(size.height * size.width * scale * scale) : + Int(size.height * size.width * scale * scale) * images!.count + } +} + +extension Dictionary { + func keysSortedByValue(_ isOrderedBefore: (Value, Value) -> Bool) -> [Key] { + return Array(self).sorted{ isOrderedBefore($0.1, $1.1) }.map{ $0.0 } + } +} + +#if !os(macOS) && !os(watchOS) +// MARK: - For App Extensions +extension UIApplication: KingfisherCompatible { } +extension Kingfisher where Base: UIApplication { + public static var shared: UIApplication? { + let selector = NSSelectorFromString("sharedApplication") + guard Base.responds(to: selector) else { return nil } + return Base.perform(selector).takeUnretainedValue() as? UIApplication + } +} +#endif + +extension String { + func computedKey(with identifier: String) -> String { + if identifier.isEmpty { + return self + } else { + return appending("@\(identifier)") + } + } +} diff --git a/GeneralUtils/GeneralUtils/libs/Kingfisher/ImageDownloader.swift b/GeneralUtils/GeneralUtils/libs/Kingfisher/ImageDownloader.swift new file mode 100755 index 0000000..c44ae39 --- /dev/null +++ b/GeneralUtils/GeneralUtils/libs/Kingfisher/ImageDownloader.swift @@ -0,0 +1,531 @@ +// +// ImageDownloader.swift +// Kingfisher +// +// Created by Wei Wang on 15/4/6. +// +// Copyright (c) 2016 Wei Wang +// +// Permission is hereby granted, free of charge, to any person obtaining a copy +// of this software and associated documentation files (the "Software"), to deal +// in the Software without restriction, including without limitation the rights +// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +// copies of the Software, and to permit persons to whom the Software is +// furnished to do so, subject to the following conditions: +// +// The above copyright notice and this permission notice shall be included in +// all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN +// THE SOFTWARE. + +#if os(macOS) +import AppKit +#else +import UIKit +#endif + +/// Progress update block of downloader. +public typealias ImageDownloaderProgressBlock = DownloadProgressBlock + +/// Completion block of downloader. +public typealias ImageDownloaderCompletionHandler = ((_ image: Image?, _ error: NSError?, _ url: URL?, _ originalData: Data?) -> ()) + +/// Download task. +public struct RetrieveImageDownloadTask { + let internalTask: URLSessionDataTask + + /// Downloader by which this task is intialized. + public private(set) weak var ownerDownloader: ImageDownloader? + + /** + Cancel this download task. It will trigger the completion handler with an NSURLErrorCancelled error. + */ + public func cancel() { + ownerDownloader?.cancelDownloadingTask(self) + } + + /// The original request URL of this download task. + public var url: URL? { + return internalTask.originalRequest?.url + } + + /// The relative priority of this download task. + /// It represents the `priority` property of the internal `NSURLSessionTask` of this download task. + /// The value for it is between 0.0~1.0. Default priority is value of 0.5. + /// See documentation on `priority` of `NSURLSessionTask` for more about it. + public var priority: Float { + get { + return internalTask.priority + } + set { + internalTask.priority = newValue + } + } +} + +///The code of errors which `ImageDownloader` might encountered. +public enum KingfisherError: Int { + + /// badData: The downloaded data is not an image or the data is corrupted. + case badData = 10000 + + /// notModified: The remote server responsed a 304 code. No image data downloaded. + case notModified = 10001 + + /// The HTTP status code in response is not valid. If an invalid + /// code error received, you could check the value under `KingfisherErrorStatusCodeKey` + /// in `userInfo` to see the code. + case invalidStatusCode = 10002 + + /// notCached: The image rquested is not in cache but .onlyFromCache is activated. + case notCached = 10003 + + /// The URL is invalid. + case invalidURL = 20000 + + /// The downloading task is cancelled before started. + case downloadCancelledBeforeStarting = 30000 +} + +/// Key will be used in the `userInfo` of `.invalidStatusCode` +public let KingfisherErrorStatusCodeKey = "statusCode" + +/// Protocol of `ImageDownloader`. +public protocol ImageDownloaderDelegate: class { + /** + Called when the `ImageDownloader` object successfully downloaded an image from specified URL. + + - parameter downloader: The `ImageDownloader` object finishes the downloading. + - parameter image: Downloaded image. + - parameter url: URL of the original request URL. + - parameter response: The response object of the downloading process. + */ + func imageDownloader(_ downloader: ImageDownloader, didDownload image: Image, for url: URL, with response: URLResponse?) + + + /** + Check if a received HTTP status code is valid or not. + By default, a status code between 200 to 400 (excluded) is considered as valid. + If an invalid code is received, the downloader will raise an .invalidStatusCode error. + It has a `userInfo` which includes this statusCode and localizedString error message. + + - parameter code: The received HTTP status code. + - parameter downloader: The `ImageDownloader` object asking for validate status code. + + - returns: Whether this HTTP status code is valid or not. + + - Note: If the default 200 to 400 valid code does not suit your need, + you can implement this method to change that behavior. + */ + func isValidStatusCode(_ code: Int, for downloader: ImageDownloader) -> Bool +} + +extension ImageDownloaderDelegate { + public func imageDownloader(_ downloader: ImageDownloader, didDownload image: Image, for url: URL, with response: URLResponse?) {} + + public func isValidStatusCode(_ code: Int, for downloader: ImageDownloader) -> Bool { + return (200..<400).contains(code) + } +} + +/// Protocol indicates that an authentication challenge could be handled. +public protocol AuthenticationChallengeResponsable: class { + /** + Called when an session level authentication challenge is received. + This method provide a chance to handle and response to the authentication challenge before downloading could start. + + - parameter downloader: The downloader which receives this challenge. + - parameter challenge: An object that contains the request for authentication. + - parameter completionHandler: A handler that your delegate method must call. + + - Note: This method is a forward from `URLSession(:didReceiveChallenge:completionHandler:)`. Please refer to the document of it in `NSURLSessionDelegate`. + */ + func downloader(_ downloader: ImageDownloader, didReceive challenge: URLAuthenticationChallenge, completionHandler: @escaping (URLSession.AuthChallengeDisposition, URLCredential?) -> Void) +} + +extension AuthenticationChallengeResponsable { + + func downloader(_ downloader: ImageDownloader, didReceive challenge: URLAuthenticationChallenge, completionHandler: @escaping (URLSession.AuthChallengeDisposition, URLCredential?) -> Void) { + + if challenge.protectionSpace.authenticationMethod == NSURLAuthenticationMethodServerTrust { + if let trustedHosts = downloader.trustedHosts, trustedHosts.contains(challenge.protectionSpace.host) { + let credential = URLCredential(trust: challenge.protectionSpace.serverTrust!) + completionHandler(.useCredential, credential) + return + } + } + + completionHandler(.performDefaultHandling, nil) + } +} + +/// `ImageDownloader` represents a downloading manager for requesting the image with a URL from server. +open class ImageDownloader { + + class ImageFetchLoad { + var contents = [(callback: CallbackPair, options: KingfisherOptionsInfo)]() + var responseData = NSMutableData() + + var downloadTaskCount = 0 + var downloadTask: RetrieveImageDownloadTask? + } + + // MARK: - Public property + /// The duration before the download is timeout. Default is 15 seconds. + open var downloadTimeout: TimeInterval = 15.0 + + /// A set of trusted hosts when receiving server trust challenges. A challenge with host name contained in this set will be ignored. + /// You can use this set to specify the self-signed site. It only will be used if you don't specify the `authenticationChallengeResponder`. + /// If `authenticationChallengeResponder` is set, this property will be ignored and the implemention of `authenticationChallengeResponder` will be used instead. + open var trustedHosts: Set? + + /// Use this to set supply a configuration for the downloader. By default, NSURLSessionConfiguration.ephemeralSessionConfiguration() will be used. + /// You could change the configuration before a downloaing task starts. A configuration without persistent storage for caches is requsted for downloader working correctly. + open var sessionConfiguration = URLSessionConfiguration.ephemeral { + didSet { + session = URLSession(configuration: sessionConfiguration, delegate: sessionHandler, delegateQueue: OperationQueue.main) + } + } + + /// Whether the download requests should use pipeling or not. Default is false. + open var requestsUsePipeling = false + + fileprivate let sessionHandler: ImageDownloaderSessionHandler + fileprivate var session: URLSession? + + /// Delegate of this `ImageDownloader` object. See `ImageDownloaderDelegate` protocol for more. + open weak var delegate: ImageDownloaderDelegate? + + /// A responder for authentication challenge. + /// Downloader will forward the received authentication challenge for the downloading session to this responder. + open weak var authenticationChallengeResponder: AuthenticationChallengeResponsable? + + // MARK: - Internal property + let barrierQueue: DispatchQueue + let processQueue: DispatchQueue + + typealias CallbackPair = (progressBlock: ImageDownloaderProgressBlock?, completionHandler: ImageDownloaderCompletionHandler?) + + var fetchLoads = [URL: ImageFetchLoad]() + + // MARK: - Public method + /// The default downloader. + public static let `default` = ImageDownloader(name: "default") + + /** + Init a downloader with name. + + - parameter name: The name for the downloader. It should not be empty. + + - returns: The downloader object. + */ + public init(name: String) { + if name.isEmpty { + fatalError("[Kingfisher] You should specify a name for the downloader. A downloader with empty name is not permitted.") + } + + barrierQueue = DispatchQueue(label: "com.onevcat.Kingfisher.ImageDownloader.Barrier.\(name)", attributes: .concurrent) + processQueue = DispatchQueue(label: "com.onevcat.Kingfisher.ImageDownloader.Process.\(name)", attributes: .concurrent) + + sessionHandler = ImageDownloaderSessionHandler() + + // Provide a default implement for challenge responder. + authenticationChallengeResponder = sessionHandler + session = URLSession(configuration: sessionConfiguration, delegate: sessionHandler, delegateQueue: .main) + } + + func fetchLoad(for url: URL) -> ImageFetchLoad? { + var fetchLoad: ImageFetchLoad? + barrierQueue.sync { fetchLoad = fetchLoads[url] } + return fetchLoad + } + + /** + Download an image with a URL and option. + + - parameter url: Target URL. + - parameter options: The options could control download behavior. See `KingfisherOptionsInfo`. + - parameter progressBlock: Called when the download progress updated. + - parameter completionHandler: Called when the download progress finishes. + + - returns: A downloading task. You could call `cancel` on it to stop the downloading process. + */ + @discardableResult + open func downloadImage(with url: URL, + options: KingfisherOptionsInfo? = nil, + progressBlock: ImageDownloaderProgressBlock? = nil, + completionHandler: ImageDownloaderCompletionHandler? = nil) -> RetrieveImageDownloadTask? + { + return downloadImage(with: url, + retrieveImageTask: nil, + options: options, + progressBlock: progressBlock, + completionHandler: completionHandler) + } +} + +// MARK: - Download method +extension ImageDownloader { + func downloadImage(with url: URL, + retrieveImageTask: RetrieveImageTask?, + options: KingfisherOptionsInfo?, + progressBlock: ImageDownloaderProgressBlock?, + completionHandler: ImageDownloaderCompletionHandler?) -> RetrieveImageDownloadTask? + { + if let retrieveImageTask = retrieveImageTask, retrieveImageTask.cancelledBeforeDownloadStarting { + return nil + } + + let timeout = self.downloadTimeout == 0.0 ? 15.0 : self.downloadTimeout + + // We need to set the URL as the load key. So before setup progress, we need to ask the `requestModifier` for a final URL. + var request = URLRequest(url: url, cachePolicy: .reloadIgnoringLocalCacheData, timeoutInterval: timeout) + request.httpShouldUsePipelining = requestsUsePipeling + + if let modifier = options?.modifier { + guard let r = modifier.modified(for: request) else { + completionHandler?(nil, NSError(domain: KingfisherErrorDomain, code: KingfisherError.downloadCancelledBeforeStarting.rawValue, userInfo: nil), nil, nil) + return nil + } + request = r + } + + // There is a possiblility that request modifier changed the url to `nil` or empty. + guard let url = request.url, !url.absoluteString.isEmpty else { + completionHandler?(nil, NSError(domain: KingfisherErrorDomain, code: KingfisherError.invalidURL.rawValue, userInfo: nil), nil, nil) + return nil + } + + var downloadTask: RetrieveImageDownloadTask? + setup(progressBlock: progressBlock, with: completionHandler, for: url, options: options) {(session, fetchLoad) -> Void in + if fetchLoad.downloadTask == nil { + let dataTask = session.dataTask(with: request) + + fetchLoad.downloadTask = RetrieveImageDownloadTask(internalTask: dataTask, ownerDownloader: self) + + dataTask.priority = options?.downloadPriority ?? URLSessionTask.defaultPriority + dataTask.resume() + + // Hold self while the task is executing. + self.sessionHandler.downloadHolder = self + } + + fetchLoad.downloadTaskCount += 1 + downloadTask = fetchLoad.downloadTask + + retrieveImageTask?.downloadTask = downloadTask + } + return downloadTask + } + + // A single key may have multiple callbacks. Only download once. + func setup(progressBlock: ImageDownloaderProgressBlock?, with completionHandler: ImageDownloaderCompletionHandler?, for url: URL, options: KingfisherOptionsInfo?, started: ((URLSession, ImageFetchLoad) -> Void)) { + + barrierQueue.sync(flags: .barrier) { + let loadObjectForURL = fetchLoads[url] ?? ImageFetchLoad() + let callbackPair = (progressBlock: progressBlock, completionHandler: completionHandler) + + loadObjectForURL.contents.append((callbackPair, options ?? KingfisherEmptyOptionsInfo)) + + fetchLoads[url] = loadObjectForURL + + if let session = session { + started(session, loadObjectForURL) + } + } + } + + func cancelDownloadingTask(_ task: RetrieveImageDownloadTask) { + barrierQueue.sync { + if let URL = task.internalTask.originalRequest?.url, let imageFetchLoad = self.fetchLoads[URL] { + imageFetchLoad.downloadTaskCount -= 1 + if imageFetchLoad.downloadTaskCount == 0 { + task.internalTask.cancel() + } + } + } + } + + func clean(for url: URL) { + barrierQueue.sync(flags: .barrier) { + fetchLoads.removeValue(forKey: url) + return + } + } +} + +// MARK: - NSURLSessionDataDelegate + +/// Delegate class for `NSURLSessionTaskDelegate`. +/// The session object will hold its delegate until it gets invalidated. +/// If we use `ImageDownloader` as the session delegate, it will not be released. +/// So we need an additional handler to break the retain cycle. +// See https://github.com/onevcat/Kingfisher/issues/235 +class ImageDownloaderSessionHandler: NSObject, URLSessionDataDelegate, AuthenticationChallengeResponsable { + + // The holder will keep downloader not released while a data task is being executed. + // It will be set when the task started, and reset when the task finished. + var downloadHolder: ImageDownloader? + + func urlSession(_ session: URLSession, dataTask: URLSessionDataTask, didReceive response: URLResponse, completionHandler: @escaping (URLSession.ResponseDisposition) -> Void) { + + guard let downloader = downloadHolder else { + completionHandler(.cancel) + return + } + + if let statusCode = (response as? HTTPURLResponse)?.statusCode, + let url = dataTask.originalRequest?.url, + !(downloader.delegate ?? downloader).isValidStatusCode(statusCode, for: downloader) + { + let error = NSError(domain: KingfisherErrorDomain, + code: KingfisherError.invalidStatusCode.rawValue, + userInfo: [KingfisherErrorStatusCodeKey: statusCode, NSLocalizedDescriptionKey: HTTPURLResponse.localizedString(forStatusCode: statusCode)]) + callCompletionHandlerFailure(error: error, url: url) + } + + completionHandler(.allow) + } + + func urlSession(_ session: URLSession, dataTask: URLSessionDataTask, didReceive data: Data) { + + guard let downloader = downloadHolder else { + return + } + + if let url = dataTask.originalRequest?.url, let fetchLoad = downloader.fetchLoad(for: url) { + fetchLoad.responseData.append(data) + + if let expectedLength = dataTask.response?.expectedContentLength { + for content in fetchLoad.contents { + DispatchQueue.main.async { + content.callback.progressBlock?(Int64(fetchLoad.responseData.length), expectedLength) + } + } + } + } + } + + func urlSession(_ session: URLSession, task: URLSessionTask, didCompleteWithError error: Error?) { + + guard let url = task.originalRequest?.url else { + return + } + + guard error == nil else { + callCompletionHandlerFailure(error: error!, url: url) + return + } + + processImage(for: task, url: url) + } + + /** + This method is exposed since the compiler requests. Do not call it. + */ + func urlSession(_ session: URLSession, didReceive challenge: URLAuthenticationChallenge, completionHandler: @escaping (URLSession.AuthChallengeDisposition, URLCredential?) -> Void) { + guard let downloader = downloadHolder else { + return + } + + downloader.authenticationChallengeResponder?.downloader(downloader, didReceive: challenge, completionHandler: completionHandler) + } + + private func cleanFetchLoad(for url: URL) { + guard let downloader = downloadHolder else { + return + } + + downloader.clean(for: url) + + if downloader.fetchLoads.isEmpty { + downloadHolder = nil + } + } + + private func callCompletionHandlerFailure(error: Error, url: URL) { + guard let downloader = downloadHolder, let fetchLoad = downloader.fetchLoad(for: url) else { + return + } + + // We need to clean the fetch load first, before actually calling completion handler. + cleanFetchLoad(for: url) + + for content in fetchLoad.contents { + content.options.callbackDispatchQueue.safeAsync { + content.callback.completionHandler?(nil, error as NSError, url, nil) + } + } + } + + private func processImage(for task: URLSessionTask, url: URL) { + + guard let downloader = downloadHolder else { + return + } + + // We are on main queue when receiving this. + downloader.processQueue.async { + + guard let fetchLoad = downloader.fetchLoad(for: url) else { + return + } + + self.cleanFetchLoad(for: url) + + let data = fetchLoad.responseData as Data + + // Cache the processed images. So we do not need to re-process the image if using the same processor. + // Key is the identifier of processor. + var imageCache: [String: Image] = [:] + for content in fetchLoad.contents { + + let options = content.options + let completionHandler = content.callback.completionHandler + let callbackQueue = options.callbackDispatchQueue + + let processor = options.processor + + var image = imageCache[processor.identifier] + if image == nil { + image = processor.process(item: .data(data), options: options) + + // Add the processed image to cache. + // If `image` is nil, nothing will happen (since the key is not existing before). + imageCache[processor.identifier] = image + } + + if let image = image { + + downloader.delegate?.imageDownloader(downloader, didDownload: image, for: url, with: task.response) + + if options.backgroundDecode { + let decodedImage = image.kf.decoded(scale: options.scaleFactor) + callbackQueue.safeAsync { completionHandler?(decodedImage, nil, url, data) } + } else { + callbackQueue.safeAsync { completionHandler?(image, nil, url, data) } + } + + } else { + if let res = task.response as? HTTPURLResponse , res.statusCode == 304 { + let notModified = NSError(domain: KingfisherErrorDomain, code: KingfisherError.notModified.rawValue, userInfo: nil) + completionHandler?(nil, notModified, url, nil) + continue + } + + let badData = NSError(domain: KingfisherErrorDomain, code: KingfisherError.badData.rawValue, userInfo: nil) + callbackQueue.safeAsync { completionHandler?(nil, badData, url, nil) } + } + } + } + } +} + +// Placeholder. For retrieving extension methods of ImageDownloaderDelegate +extension ImageDownloader: ImageDownloaderDelegate {} diff --git a/GeneralUtils/GeneralUtils/libs/Kingfisher/ImagePrefetcher.swift b/GeneralUtils/GeneralUtils/libs/Kingfisher/ImagePrefetcher.swift new file mode 100755 index 0000000..f699700 --- /dev/null +++ b/GeneralUtils/GeneralUtils/libs/Kingfisher/ImagePrefetcher.swift @@ -0,0 +1,267 @@ +// +// ImagePrefetcher.swift +// Kingfisher +// +// Created by Claire Knight on 24/02/2016 +// +// Copyright (c) 2016 Wei Wang +// +// Permission is hereby granted, free of charge, to any person obtaining a copy +// of this software and associated documentation files (the "Software"), to deal +// in the Software without restriction, including without limitation the rights +// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +// copies of the Software, and to permit persons to whom the Software is +// furnished to do so, subject to the following conditions: +// +// The above copyright notice and this permission notice shall be included in +// all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN +// THE SOFTWARE. + + +#if os(macOS) + import AppKit +#else + import UIKit +#endif + + +/// Progress update block of prefetcher. +/// +/// - `skippedResources`: An array of resources that are already cached before the prefetching starting. +/// - `failedResources`: An array of resources that fail to be downloaded. It could because of being cancelled while downloading, encountered an error when downloading or the download not being started at all. +/// - `completedResources`: An array of resources that are downloaded and cached successfully. +public typealias PrefetcherProgressBlock = ((_ skippedResources: [Resource], _ failedResources: [Resource], _ completedResources: [Resource]) -> ()) + +/// Completion block of prefetcher. +/// +/// - `skippedResources`: An array of resources that are already cached before the prefetching starting. +/// - `failedResources`: An array of resources that fail to be downloaded. It could because of being cancelled while downloading, encountered an error when downloading or the download not being started at all. +/// - `completedResources`: An array of resources that are downloaded and cached successfully. +public typealias PrefetcherCompletionHandler = ((_ skippedResources: [Resource], _ failedResources: [Resource], _ completedResources: [Resource]) -> ()) + +/// `ImagePrefetcher` represents a downloading manager for requesting many images via URLs, then caching them. +/// This is useful when you know a list of image resources and want to download them before showing. +public class ImagePrefetcher { + + /// The maximum concurrent downloads to use when prefetching images. Default is 5. + public var maxConcurrentDownloads = 5 + + private let prefetchResources: [Resource] + private let optionsInfo: KingfisherOptionsInfo + private var progressBlock: PrefetcherProgressBlock? + private var completionHandler: PrefetcherCompletionHandler? + + private var tasks = [URL: RetrieveImageDownloadTask]() + + private var pendingResources: ArraySlice + private var skippedResources = [Resource]() + private var completedResources = [Resource]() + private var failedResources = [Resource]() + + private var stopped = false + + // The created manager used for prefetch. We will use the helper method in manager. + private let manager: KingfisherManager + + private var finished: Bool { + return failedResources.count + skippedResources.count + completedResources.count == prefetchResources.count && self.tasks.isEmpty + } + + /** + Init an image prefetcher with an array of URLs. + + The prefetcher should be initiated with a list of prefetching targets. The URLs list is immutable. + After you get a valid `ImagePrefetcher` object, you could call `start()` on it to begin the prefetching process. + The images already cached will be skipped without downloading again. + + - parameter urls: The URLs which should be prefetched. + - parameter options: A dictionary could control some behaviors. See `KingfisherOptionsInfo` for more. + - parameter progressBlock: Called every time an resource is downloaded, skipped or cancelled. + - parameter completionHandler: Called when the whole prefetching process finished. + + - returns: An `ImagePrefetcher` object. + + - Note: By default, the `ImageDownloader.defaultDownloader` and `ImageCache.defaultCache` will be used as + the downloader and cache target respectively. You can specify another downloader or cache by using a customized `KingfisherOptionsInfo`. + Both the progress and completion block will be invoked in main thread. The `CallbackDispatchQueue` in `optionsInfo` will be ignored in this method. + */ + public convenience init(urls: [URL], + options: KingfisherOptionsInfo? = nil, + progressBlock: PrefetcherProgressBlock? = nil, + completionHandler: PrefetcherCompletionHandler? = nil) + { + let resources: [Resource] = urls.map { $0 } + self.init(resources: resources, options: options, progressBlock: progressBlock, completionHandler: completionHandler) + } + + /** + Init an image prefetcher with an array of resources. + + The prefetcher should be initiated with a list of prefetching targets. The resources list is immutable. + After you get a valid `ImagePrefetcher` object, you could call `start()` on it to begin the prefetching process. + The images already cached will be skipped without downloading again. + + - parameter resources: The resources which should be prefetched. See `Resource` type for more. + - parameter options: A dictionary could control some behaviors. See `KingfisherOptionsInfo` for more. + - parameter progressBlock: Called every time an resource is downloaded, skipped or cancelled. + - parameter completionHandler: Called when the whole prefetching process finished. + + - returns: An `ImagePrefetcher` object. + + - Note: By default, the `ImageDownloader.defaultDownloader` and `ImageCache.defaultCache` will be used as + the downloader and cache target respectively. You can specify another downloader or cache by using a customized `KingfisherOptionsInfo`. + Both the progress and completion block will be invoked in main thread. The `CallbackDispatchQueue` in `optionsInfo` will be ignored in this method. + */ + public init(resources: [Resource], + options: KingfisherOptionsInfo? = nil, + progressBlock: PrefetcherProgressBlock? = nil, + completionHandler: PrefetcherCompletionHandler? = nil) + { + prefetchResources = resources + pendingResources = ArraySlice(resources) + + // We want all callbacks from main queue, so we ignore the call back queue in options + let optionsInfoWithoutQueue = options?.removeAllMatchesIgnoringAssociatedValue(.callbackDispatchQueue(nil)) + self.optionsInfo = optionsInfoWithoutQueue ?? KingfisherEmptyOptionsInfo + + let cache = self.optionsInfo.targetCache + let downloader = self.optionsInfo.downloader + manager = KingfisherManager(downloader: downloader, cache: cache) + + self.progressBlock = progressBlock + self.completionHandler = completionHandler + } + + /** + Start to download the resources and cache them. This can be useful for background downloading + of assets that are required for later use in an app. This code will not try and update any UI + with the results of the process. + */ + public func start() + { + // Since we want to handle the resources cancellation in main thread only. + DispatchQueue.main.safeAsync { + + guard !self.stopped else { + assertionFailure("You can not restart the same prefetcher. Try to create a new prefetcher.") + self.handleComplete() + return + } + + guard self.maxConcurrentDownloads > 0 else { + assertionFailure("There should be concurrent downloads value should be at least 1.") + self.handleComplete() + return + } + + guard self.prefetchResources.count > 0 else { + self.handleComplete() + return + } + + let initialConcurentDownloads = min(self.prefetchResources.count, self.maxConcurrentDownloads) + for _ in 0 ..< initialConcurentDownloads { + if let resource = self.pendingResources.popFirst() { + self.startPrefetching(resource) + } + } + } + } + + + /** + Stop current downloading progress, and cancel any future prefetching activity that might be occuring. + */ + public func stop() { + DispatchQueue.main.safeAsync { + + if self.finished { return } + + self.stopped = true + self.tasks.forEach { (_, task) -> () in + task.cancel() + } + } + } + + func downloadAndCache(_ resource: Resource) { + + let downloadTaskCompletionHandler: CompletionHandler = { (image, error, _, _) -> () in + self.tasks.removeValue(forKey: resource.downloadURL) + if let _ = error { + self.failedResources.append(resource) + } else { + self.completedResources.append(resource) + } + + self.reportProgress() + if self.stopped { + if self.tasks.isEmpty { + self.failedResources.append(contentsOf: self.pendingResources) + self.handleComplete() + } + } else { + self.reportCompletionOrStartNext() + } + } + + let downloadTask = manager.downloadAndCacheImage( + with: resource.downloadURL, + forKey: resource.cacheKey, + retrieveImageTask: RetrieveImageTask(), + progressBlock: nil, + completionHandler: downloadTaskCompletionHandler, + options: optionsInfo) + + if let downloadTask = downloadTask { + tasks[resource.downloadURL] = downloadTask + } + } + + func append(cached resource: Resource) { + skippedResources.append(resource) + + reportProgress() + reportCompletionOrStartNext() + } + + func startPrefetching(_ resource: Resource) + { + if optionsInfo.forceRefresh { + downloadAndCache(resource) + } else { + let alreadyInCache = manager.cache.isImageCached(forKey: resource.cacheKey).cached + if alreadyInCache { + append(cached: resource) + } else { + downloadAndCache(resource) + } + } + } + + func reportProgress() { + progressBlock?(skippedResources, failedResources, completedResources) + } + + func reportCompletionOrStartNext() { + if let resource = pendingResources.popFirst() { + startPrefetching(resource) + } else { + guard tasks.isEmpty else { return } + handleComplete() + } + } + + func handleComplete() { + completionHandler?(skippedResources, failedResources, completedResources) + completionHandler = nil + progressBlock = nil + } +} diff --git a/GeneralUtils/GeneralUtils/libs/Kingfisher/ImageProcessor.swift b/GeneralUtils/GeneralUtils/libs/Kingfisher/ImageProcessor.swift new file mode 100644 index 0000000..aeb8742 --- /dev/null +++ b/GeneralUtils/GeneralUtils/libs/Kingfisher/ImageProcessor.swift @@ -0,0 +1,370 @@ +// +// ImageProcessor.swift +// Kingfisher +// +// Created by Wei Wang on 2016/08/26. +// +// Copyright (c) 2016 Wei Wang +// +// Permission is hereby granted, free of charge, to any person obtaining a copy +// of this software and associated documentation files (the "Software"), to deal +// in the Software without restriction, including without limitation the rights +// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +// copies of the Software, and to permit persons to whom the Software is +// furnished to do so, subject to the following conditions: +// +// The above copyright notice and this permission notice shall be included in +// all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN +// THE SOFTWARE. + +import Foundation +import CoreGraphics + + +/// The item which could be processed by an `ImageProcessor` +/// +/// - image: Input image +/// - data: Input data +public enum ImageProcessItem { + case image(Image) + case data(Data) +} + +/// An `ImageProcessor` would be used to convert some downloaded data to an image. +public protocol ImageProcessor { + /// Identifier of the processor. It will be used to identify the processor when + /// caching and retriving an image. You might want to make sure that processors with + /// same properties/functionality have the same identifiers, so correct processed images + /// could be retrived with proper key. + /// + /// - Note: Do not supply an empty string for a customized processor, which is already taken by + /// the `DefaultImageProcessor`. It is recommended to use a reverse domain name notation + /// string of your own for the identifier. + var identifier: String { get } + + /// Process an input `ImageProcessItem` item to an image for this processor. + /// + /// - parameter item: Input item which will be processed by `self` + /// - parameter options: Options when processing the item. + /// + /// - returns: The processed image. + /// + /// - Note: The return value will be `nil` if processing failed while converting data to image. + /// If input item is already an image and there is any errors in processing, the input + /// image itself will be returned. + /// - Note: Most processor only supports CG-based images. + /// watchOS is not supported for processers containing filter, the input image will be returned directly on watchOS. + func process(item: ImageProcessItem, options: KingfisherOptionsInfo) -> Image? +} + +typealias ProcessorImp = ((ImageProcessItem, KingfisherOptionsInfo) -> Image?) + +public extension ImageProcessor { + + /// Append an `ImageProcessor` to another. The identifier of the new `ImageProcessor` + /// will be "\(self.identifier)|>\(another.identifier)>". + /// + /// - parameter another: An `ImageProcessor` you want to append to `self`. + /// + /// - returns: The new `ImageProcessor`. It will process the image in the order + /// of the two processors concatenated. + public func append(another: ImageProcessor) -> ImageProcessor { + let newIdentifier = identifier.appending("|>\(another.identifier)") + return GeneralProcessor(identifier: newIdentifier) { + item, options in + if let image = self.process(item: item, options: options) { + return another.process(item: .image(image), options: options) + } else { + return nil + } + } + } +} + +fileprivate struct GeneralProcessor: ImageProcessor { + let identifier: String + let p: ProcessorImp + func process(item: ImageProcessItem, options: KingfisherOptionsInfo) -> Image? { + return p(item, options) + } +} + +/// The default processor. It convert the input data to a valid image. +/// Images of .PNG, .JPEG and .GIF format are supported. +/// If an image is given, `DefaultImageProcessor` will do nothing on it and just return that image. +public struct DefaultImageProcessor: ImageProcessor { + + /// A default `DefaultImageProcessor` could be used across. + public static let `default` = DefaultImageProcessor() + + public let identifier = "" + + /// Initialize a `DefaultImageProcessor` + /// + /// - returns: An initialized `DefaultImageProcessor`. + public init() {} + + public func process(item: ImageProcessItem, options: KingfisherOptionsInfo) -> Image? { + switch item { + case .image(let image): + return image + case .data(let data): + return Kingfisher.image(data: data, scale: options.scaleFactor, preloadAllGIFData: options.preloadAllGIFData) + } + } +} + +/// Processor for making round corner images. Only CG-based images are supported in macOS, +/// if a non-CG image passed in, the processor will do nothing. +public struct RoundCornerImageProcessor: ImageProcessor { + public let identifier: String + + /// Corner radius will be applied in processing. + public let cornerRadius: CGFloat + + /// Target size of output image should be. If `nil`, the image will keep its original size after processing. + public let targetSize: CGSize? + + /// Initialize a `RoundCornerImageProcessor` + /// + /// - parameter cornerRadius: Corner radius will be applied in processing. + /// - parameter targetSize: Target size of output image should be. If `nil`, + /// the image will keep its original size after processing. + /// Default is `nil`. + /// + /// - returns: An initialized `RoundCornerImageProcessor`. + public init(cornerRadius: CGFloat, targetSize: CGSize? = nil) { + self.cornerRadius = cornerRadius + self.targetSize = targetSize + if let size = targetSize { + self.identifier = "com.onevcat.Kingfisher.RoundCornerImageProcessor(\(cornerRadius)_\(size))" + } else { + self.identifier = "com.onevcat.Kingfisher.RoundCornerImageProcessor(\(cornerRadius))" + } + } + + public func process(item: ImageProcessItem, options: KingfisherOptionsInfo) -> Image? { + switch item { + case .image(let image): + let size = targetSize ?? image.kf.size + return image.kf.image(withRoundRadius: cornerRadius, fit: size, scale: options.scaleFactor) + case .data(_): + return (DefaultImageProcessor.default >> self).process(item: item, options: options) + } + } +} + +/// Processor for resizing images. Only CG-based images are supported in macOS. +public struct ResizingImageProcessor: ImageProcessor { + public let identifier: String + + /// Target size of output image should be. + public let targetSize: CGSize + + /// Initialize a `ResizingImageProcessor` + /// + /// - parameter targetSize: Target size of output image should be. + /// + /// - returns: An initialized `ResizingImageProcessor`. + public init(targetSize: CGSize) { + self.targetSize = targetSize + self.identifier = "com.onevcat.Kingfisher.ResizingImageProcessor(\(targetSize))" + } + + public func process(item: ImageProcessItem, options: KingfisherOptionsInfo) -> Image? { + switch item { + case .image(let image): + return image.kf.resize(to: targetSize) + case .data(_): + return (DefaultImageProcessor.default >> self).process(item: item, options: options) + } + } +} + +/// Processor for adding blur effect to images. `Accelerate.framework` is used underhood for +/// a better performance. A simulated Gaussian blur with specified blur radius will be applied. +public struct BlurImageProcessor: ImageProcessor { + public let identifier: String + + /// Blur radius for the simulated Gaussian blur. + public let blurRadius: CGFloat + + /// Initialize a `BlurImageProcessor` + /// + /// - parameter blurRadius: Blur radius for the simulated Gaussian blur. + /// + /// - returns: An initialized `BlurImageProcessor`. + public init(blurRadius: CGFloat) { + self.blurRadius = blurRadius + self.identifier = "com.onevcat.Kingfisher.BlurImageProcessor(\(blurRadius))" + } + + public func process(item: ImageProcessItem, options: KingfisherOptionsInfo) -> Image? { + switch item { + case .image(let image): + let radius = blurRadius * options.scaleFactor + return image.kf.blurred(withRadius: radius) + case .data(_): + return (DefaultImageProcessor.default >> self).process(item: item, options: options) + } + } +} + +/// Processor for adding an overlay to images. Only CG-based images are supported in macOS. +public struct OverlayImageProcessor: ImageProcessor { + + public var identifier: String + + /// Overlay color will be used to overlay the input image. + public let overlay: Color + + /// Fraction will be used when overlay the color to image. + public let fraction: CGFloat + + /// Initialize an `OverlayImageProcessor` + /// + /// - parameter overlay: Overlay color will be used to overlay the input image. + /// - parameter fraction: Fraction will be used when overlay the color to image. + /// From 0.0 to 1.0. 0.0 means solid color, 1.0 means transparent overlay. + /// + /// - returns: An initialized `OverlayImageProcessor`. + public init(overlay: Color, fraction: CGFloat = 0.5) { + self.overlay = overlay + self.fraction = fraction + self.identifier = "com.onevcat.Kingfisher.OverlayImageProcessor(\(overlay.hex)_\(fraction))" + } + + public func process(item: ImageProcessItem, options: KingfisherOptionsInfo) -> Image? { + switch item { + case .image(let image): + return image.kf.overlaying(with: overlay, fraction: fraction) + case .data(_): + return (DefaultImageProcessor.default >> self).process(item: item, options: options) + } + } +} + +/// Processor for tint images with color. Only CG-based images are supported. +public struct TintImageProcessor: ImageProcessor { + + public let identifier: String + + /// Tint color will be used to tint the input image. + public let tint: Color + + /// Initialize a `TintImageProcessor` + /// + /// - parameter tint: Tint color will be used to tint the input image. + /// + /// - returns: An initialized `TintImageProcessor`. + public init(tint: Color) { + self.tint = tint + self.identifier = "com.onevcat.Kingfisher.TintImageProcessor(\(tint.hex))" + } + + public func process(item: ImageProcessItem, options: KingfisherOptionsInfo) -> Image? { + switch item { + case .image(let image): + return image.kf.tinted(with: tint) + case .data(_): + return (DefaultImageProcessor.default >> self).process(item: item, options: options) + } + } +} + +/// Processor for applying some color control to images. Only CG-based images are supported. +/// watchOS is not supported. +public struct ColorControlsProcessor: ImageProcessor { + + public let identifier: String + + /// Brightness changing to image. + public let brightness: CGFloat + + /// Contrast changing to image. + public let contrast: CGFloat + + /// Saturation changing to image. + public let saturation: CGFloat + + /// InputEV changing to image. + public let inputEV: CGFloat + + /// Initialize a `ColorControlsProcessor` + /// + /// - parameter brightness: Brightness changing to image. + /// - parameter contrast: Contrast changing to image. + /// - parameter saturation: Saturation changing to image. + /// - parameter inputEV: InputEV changing to image. + /// + /// - returns: An initialized `ColorControlsProcessor` + public init(brightness: CGFloat, contrast: CGFloat, saturation: CGFloat, inputEV: CGFloat) { + self.brightness = brightness + self.contrast = contrast + self.saturation = saturation + self.inputEV = inputEV + self.identifier = "com.onevcat.Kingfisher.ColorControlsProcessor(\(brightness)_\(contrast)_\(saturation)_\(inputEV))" + } + + public func process(item: ImageProcessItem, options: KingfisherOptionsInfo) -> Image? { + switch item { + case .image(let image): + return image.kf.adjusted(brightness: brightness, contrast: contrast, saturation: saturation, inputEV: inputEV) + case .data(_): + return (DefaultImageProcessor.default >> self).process(item: item, options: options) + } + } +} + +/// Processor for applying black and white effect to images. Only CG-based images are supported. +/// watchOS is not supported. +public struct BlackWhiteProcessor: ImageProcessor { + public let identifier = "com.onevcat.Kingfisher.BlackWhiteProcessor" + + /// Initialize a `BlackWhiteProcessor` + /// + /// - returns: An initialized `BlackWhiteProcessor` + public init() {} + + public func process(item: ImageProcessItem, options: KingfisherOptionsInfo) -> Image? { + return ColorControlsProcessor(brightness: 0.0, contrast: 1.0, saturation: 0.0, inputEV: 0.7) + .process(item: item, options: options) + } +} + +/// Concatenate two `ImageProcessor`s. `ImageProcessor.appen(another:)` is used internally. +/// +/// - parameter left: First processor. +/// - parameter right: Second processor. +/// +/// - returns: The concatenated processor. +public func >>(left: ImageProcessor, right: ImageProcessor) -> ImageProcessor { + return left.append(another: right) +} + +fileprivate extension Color { + var hex: String { + var r: CGFloat = 0 + var g: CGFloat = 0 + var b: CGFloat = 0 + var a: CGFloat = 0 + + getRed(&r, green: &g, blue: &b, alpha: &a) + + let rInt = Int(r * 255) << 24 + let gInt = Int(g * 255) << 16 + let bInt = Int(b * 255) << 8 + let aInt = Int(a * 255) + + let rgba = rInt | gInt | bInt | aInt + + return String(format:"#%08x", rgba) + } +} diff --git a/GeneralUtils/GeneralUtils/libs/Kingfisher/ImageTransition.swift b/GeneralUtils/GeneralUtils/libs/Kingfisher/ImageTransition.swift new file mode 100755 index 0000000..9fa9077 --- /dev/null +++ b/GeneralUtils/GeneralUtils/libs/Kingfisher/ImageTransition.swift @@ -0,0 +1,128 @@ +// +// ImageTransition.swift +// Kingfisher +// +// Created by Wei Wang on 15/9/18. +// +// Copyright (c) 2016 Wei Wang +// +// Permission is hereby granted, free of charge, to any person obtaining a copy +// of this software and associated documentation files (the "Software"), to deal +// in the Software without restriction, including without limitation the rights +// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +// copies of the Software, and to permit persons to whom the Software is +// furnished to do so, subject to the following conditions: +// +// The above copyright notice and this permission notice shall be included in +// all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN +// THE SOFTWARE. + +#if os(macOS) +// Not implemented for macOS and watchOS yet. + +import AppKit + +/// Image transition is not supported on macOS. +public enum ImageTransition { + case none + var duration: TimeInterval { + return 0 + } +} + +#elseif os(watchOS) +import UIKit +/// Image transition is not supported on watchOS. +public enum ImageTransition { + case none + var duration: TimeInterval { + return 0 + } +} +#else +import UIKit + +/** +Transition effect which will be used when an image downloaded and set by `UIImageView` extension API in Kingfisher. +You can assign an enum value with transition duration as an item in `KingfisherOptionsInfo` +to enable the animation transition. + +Apple's UIViewAnimationOptions is used under the hood. +For custom transition, you should specified your own transition options, animations and +comletion handler as well. +*/ +public enum ImageTransition { + /// No animation transistion. + case none + + /// Fade in the loaded image. + case fade(TimeInterval) + + /// Flip from left transition. + case flipFromLeft(TimeInterval) + + /// Flip from right transition. + case flipFromRight(TimeInterval) + + /// Flip from top transition. + case flipFromTop(TimeInterval) + + /// Flip from bottom transition. + case flipFromBottom(TimeInterval) + + /// Custom transition. + case custom(duration: TimeInterval, + options: UIViewAnimationOptions, + animations: ((UIImageView, UIImage) -> Void)?, + completion: ((Bool) -> Void)?) + + var duration: TimeInterval { + switch self { + case .none: return 0 + case .fade(let duration): return duration + + case .flipFromLeft(let duration): return duration + case .flipFromRight(let duration): return duration + case .flipFromTop(let duration): return duration + case .flipFromBottom(let duration): return duration + + case .custom(let duration, _, _, _): return duration + } + } + + var animationOptions: UIViewAnimationOptions { + switch self { + case .none: return [] + case .fade(_): return .transitionCrossDissolve + + case .flipFromLeft(_): return .transitionFlipFromLeft + case .flipFromRight(_): return .transitionFlipFromRight + case .flipFromTop(_): return .transitionFlipFromTop + case .flipFromBottom(_): return .transitionFlipFromBottom + + case .custom(_, let options, _, _): return options + } + } + + var animations: ((UIImageView, UIImage) -> Void)? { + switch self { + case .custom(_, _, let animations, _): return animations + default: return { $0.image = $1 } + } + } + + var completion: ((Bool) -> Void)? { + switch self { + case .custom(_, _, _, let completion): return completion + default: return nil + } + } +} +#endif diff --git a/GeneralUtils/GeneralUtils/libs/Kingfisher/ImageView+Kingfisher.swift b/GeneralUtils/GeneralUtils/libs/Kingfisher/ImageView+Kingfisher.swift new file mode 100755 index 0000000..e4e3658 --- /dev/null +++ b/GeneralUtils/GeneralUtils/libs/Kingfisher/ImageView+Kingfisher.swift @@ -0,0 +1,288 @@ +// +// ImageView+Kingfisher.swift +// Kingfisher +// +// Created by Wei Wang on 15/4/6. +// +// Copyright (c) 2016 Wei Wang +// +// Permission is hereby granted, free of charge, to any person obtaining a copy +// of this software and associated documentation files (the "Software"), to deal +// in the Software without restriction, including without limitation the rights +// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +// copies of the Software, and to permit persons to whom the Software is +// furnished to do so, subject to the following conditions: +// +// The above copyright notice and this permission notice shall be included in +// all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN +// THE SOFTWARE. + + +#if os(macOS) +import AppKit +#else +import UIKit +#endif + +// MARK: - Extension methods. +/** + * Set image to use from web. + */ +extension Kingfisher where Base: ImageView { + /** + Set an image with a resource, a placeholder image, options, progress handler and completion handler. + + - parameter resource: Resource object contains information such as `cacheKey` and `downloadURL`. + - parameter placeholder: A placeholder image when retrieving the image at URL. + - parameter options: A dictionary could control some behaviors. See `KingfisherOptionsInfo` for more. + - parameter progressBlock: Called when the image downloading progress gets updated. + - parameter completionHandler: Called when the image retrieved and set. + + - returns: A task represents the retrieving process. + + - note: Both the `progressBlock` and `completionHandler` will be invoked in main thread. + The `CallbackDispatchQueue` specified in `optionsInfo` will not be used in callbacks of this method. + */ + @discardableResult + public func setImage(with resource: Resource?, + placeholder: Image? = nil, + options: KingfisherOptionsInfo? = nil, + progressBlock: DownloadProgressBlock? = nil, + completionHandler: CompletionHandler? = nil) -> RetrieveImageTask + { + guard let resource = resource else { + base.image = placeholder + completionHandler?(nil, nil, .none, nil) + return .empty + } + + var options = options ?? KingfisherEmptyOptionsInfo + + if !options.keepCurrentImageWhileLoading { + base.image = placeholder + } + + let maybeIndicator = indicator + maybeIndicator?.startAnimatingView() + + setWebURL(resource.downloadURL) + + if base.shouldPreloadAllGIF() { + options.append(.preloadAllGIFData) + } + + let task = KingfisherManager.shared.retrieveImage( + with: resource, + options: options, + progressBlock: { receivedSize, totalSize in + if let progressBlock = progressBlock { + progressBlock(receivedSize, totalSize) + } + }, + completionHandler: {[weak base] image, error, cacheType, imageURL in + DispatchQueue.main.safeAsync { + guard let strongBase = base, imageURL == self.webURL else { + return + } + self.setImageTask(nil) + guard let image = image else { + maybeIndicator?.stopAnimatingView() + completionHandler?(nil, error, cacheType, imageURL) + return + } + + guard let transitionItem = options.firstMatchIgnoringAssociatedValue(.transition(.none)), + case .transition(let transition) = transitionItem, ( options.forceTransition || cacheType == .none) else + { + maybeIndicator?.stopAnimatingView() + strongBase.image = image + completionHandler?(image, error, cacheType, imageURL) + return + } + + #if !os(macOS) + UIView.transition(with: strongBase, duration: 0.0, options: [], + animations: { maybeIndicator?.stopAnimatingView() }, + completion: { _ in + UIView.transition(with: strongBase, duration: transition.duration, + options: [transition.animationOptions, .allowUserInteraction], + animations: { + // Set image property in the animation. + transition.animations?(strongBase, image) + }, + completion: { finished in + transition.completion?(finished) + completionHandler?(image, error, cacheType, imageURL) + }) + }) + #endif + } + }) + + setImageTask(task) + + return task + } + + /** + Cancel the image download task bounded to the image view if it is running. + Nothing will happen if the downloading has already finished. + */ + public func cancelDownloadTask() { + imageTask?.downloadTask?.cancel() + } +} + +// MARK: - Associated Object +private var lastURLKey: Void? +private var indicatorKey: Void? +private var indicatorTypeKey: Void? +private var imageTaskKey: Void? + +extension Kingfisher where Base: ImageView { + /// Get the image URL binded to this image view. + public var webURL: URL? { + return objc_getAssociatedObject(base, &lastURLKey) as? URL + } + + fileprivate func setWebURL(_ url: URL) { + objc_setAssociatedObject(base, &lastURLKey, url, .OBJC_ASSOCIATION_RETAIN_NONATOMIC) + } + + /// Holds which indicator type is going to be used. + /// Default is .none, means no indicator will be shown. + public var indicatorType: IndicatorType { + get { + let indicator = (objc_getAssociatedObject(base, &indicatorTypeKey) as? Box)?.value + return indicator ?? .none + } + + set { + switch newValue { + case .none: + indicator = nil + case .activity: + indicator = ActivityIndicator() + case .image(let data): + indicator = ImageIndicator(imageData: data) + case .custom(let anIndicator): + indicator = anIndicator + } + + objc_setAssociatedObject(base, &indicatorTypeKey, Box(value: newValue), .OBJC_ASSOCIATION_RETAIN_NONATOMIC) + } + } + + /// Holds any type that conforms to the protocol `Indicator`. + /// The protocol `Indicator` has a `view` property that will be shown when loading an image. + /// It will be `nil` if `indicatorType` is `.none`. + public fileprivate(set) var indicator: Indicator? { + get { + return (objc_getAssociatedObject(base, &indicatorKey) as? Box)?.value + } + + set { + // Remove previous + if let previousIndicator = indicator { + previousIndicator.view.removeFromSuperview() + } + + // Add new + if var newIndicator = newValue { + newIndicator.view.frame = base.frame + newIndicator.viewCenter = CGPoint(x: base.bounds.midX, y: base.bounds.midY) + newIndicator.view.isHidden = true + base.addSubview(newIndicator.view) + } + + // Save in associated object + objc_setAssociatedObject(base, &indicatorKey, Box(value: newValue), .OBJC_ASSOCIATION_RETAIN_NONATOMIC) + } + } + + fileprivate var imageTask: RetrieveImageTask? { + return objc_getAssociatedObject(base, &imageTaskKey) as? RetrieveImageTask + } + + fileprivate func setImageTask(_ task: RetrieveImageTask?) { + objc_setAssociatedObject(base, &imageTaskKey, task, .OBJC_ASSOCIATION_RETAIN_NONATOMIC) + } +} + + +// MARK: - Deprecated. Only for back compatibility. +/** +* Set image to use from web. Deprecated. Use `kf` namespacing instead. +*/ +extension ImageView { + /** + Set an image with a resource, a placeholder image, options, progress handler and completion handler. + + - parameter resource: Resource object contains information such as `cacheKey` and `downloadURL`. + - parameter placeholder: A placeholder image when retrieving the image at URL. + - parameter options: A dictionary could control some behaviors. See `KingfisherOptionsInfo` for more. + - parameter progressBlock: Called when the image downloading progress gets updated. + - parameter completionHandler: Called when the image retrieved and set. + + - returns: A task represents the retrieving process. + + - note: Both the `progressBlock` and `completionHandler` will be invoked in main thread. + The `CallbackDispatchQueue` specified in `optionsInfo` will not be used in callbacks of this method. + */ + @available(*, deprecated, message: "Extensions directly on image views are deprecated. Use `imageView.kf.setImage` instead.", renamed: "kf.setImage") + @discardableResult + public func kf_setImage(with resource: Resource?, + placeholder: Image? = nil, + options: KingfisherOptionsInfo? = nil, + progressBlock: DownloadProgressBlock? = nil, + completionHandler: CompletionHandler? = nil) -> RetrieveImageTask + { + return kf.setImage(with: resource, placeholder: placeholder, options: options, progressBlock: progressBlock, completionHandler: completionHandler) + } + + /** + Cancel the image download task bounded to the image view if it is running. + Nothing will happen if the downloading has already finished. + */ + @available(*, deprecated, message: "Extensions directly on image views are deprecated. Use `imageView.kf.cancelDownloadTask` instead.", renamed: "kf.cancelDownloadTask") + public func kf_cancelDownloadTask() { kf.cancelDownloadTask() } + + /// Get the image URL binded to this image view. + @available(*, deprecated, message: "Extensions directly on image views are deprecated. Use `imageView.kf.webURL` instead.", renamed: "kf.webURL") + public var kf_webURL: URL? { return kf.webURL } + + /// Holds which indicator type is going to be used. + /// Default is .none, means no indicator will be shown. + @available(*, deprecated, message: "Extensions directly on image views are deprecated. Use `imageView.kf.indicatorType` instead.", renamed: "kf.indicatorType") + public var kf_indicatorType: IndicatorType { + get { return kf.indicatorType } + set { kf.indicatorType = newValue } + } + + @available(*, deprecated, message: "Extensions directly on image views are deprecated. Use `imageView.kf.indicator` instead.", renamed: "kf.indicator") + /// Holds any type that conforms to the protocol `Indicator`. + /// The protocol `Indicator` has a `view` property that will be shown when loading an image. + /// It will be `nil` if `kf_indicatorType` is `.none`. + public private(set) var kf_indicator: Indicator? { + get { return kf.indicator } + set { kf.indicator = newValue } + } + + @available(*, deprecated, message: "Extensions directly on image views are deprecated.", renamed: "kf.imageTask") + fileprivate var kf_imageTask: RetrieveImageTask? { return kf.imageTask } + @available(*, deprecated, message: "Extensions directly on image views are deprecated.", renamed: "kf.setImageTask") + fileprivate func kf_setImageTask(_ task: RetrieveImageTask?) { kf.setImageTask(task) } + @available(*, deprecated, message: "Extensions directly on image views are deprecated.", renamed: "kf.setWebURL") + fileprivate func kf_setWebURL(_ url: URL) { kf.setWebURL(url) } +} + +extension ImageView { + func shouldPreloadAllGIF() -> Bool { return true } +} diff --git a/GeneralUtils/GeneralUtils/libs/Kingfisher/Indicator.swift b/GeneralUtils/GeneralUtils/libs/Kingfisher/Indicator.swift new file mode 100644 index 0000000..89908b1 --- /dev/null +++ b/GeneralUtils/GeneralUtils/libs/Kingfisher/Indicator.swift @@ -0,0 +1,191 @@ +// +// Indicator.swift +// Kingfisher +// +// Created by João D. Moreira on 30/08/16. +// +// Copyright (c) 2016 Wei Wang +// +// Permission is hereby granted, free of charge, to any person obtaining a copy +// of this software and associated documentation files (the "Software"), to deal +// in the Software without restriction, including without limitation the rights +// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +// copies of the Software, and to permit persons to whom the Software is +// furnished to do so, subject to the following conditions: +// +// The above copyright notice and this permission notice shall be included in +// all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN +// THE SOFTWARE. + +#if os(macOS) + import AppKit +#else + import UIKit +#endif + +#if os(macOS) + public typealias IndicatorView = NSView +#else + public typealias IndicatorView = UIView +#endif + +public enum IndicatorType { + /// No indicator. + case none + /// Use system activity indicator. + case activity + /// Use an image as indicator. GIF is supported. + case image(imageData: Data) + /// Use a custom indicator, which conforms to the `Indicator` protocol. + case custom(indicator: Indicator) +} + +// MARK: - Indicator Protocol +public protocol Indicator { + func startAnimatingView() + func stopAnimatingView() + + var viewCenter: CGPoint { get set } + var view: IndicatorView { get } +} + +extension Indicator { + #if os(macOS) + public var viewCenter: CGPoint { + get { + let frame = view.frame + return CGPoint(x: frame.origin.x + frame.size.width / 2.0, y: frame.origin.y + frame.size.height / 2.0 ) + } + set { + let frame = view.frame + let newFrame = CGRect(x: newValue.x - frame.size.width / 2.0, + y: newValue.y - frame.size.height / 2.0, + width: frame.size.width, + height: frame.size.height) + view.frame = newFrame + } + } + #else + public var viewCenter: CGPoint { + get { + return view.center + } + set { + view.center = newValue + } + } + #endif +} + +// MARK: - ActivityIndicator +// Displays a NSProgressIndicator / UIActivityIndicatorView +struct ActivityIndicator: Indicator { + + #if os(macOS) + private let activityIndicatorView: NSProgressIndicator + #else + private let activityIndicatorView: UIActivityIndicatorView + #endif + + var view: IndicatorView { + return activityIndicatorView + } + + func startAnimatingView() { + #if os(macOS) + activityIndicatorView.startAnimation(nil) + #else + activityIndicatorView.startAnimating() + #endif + activityIndicatorView.isHidden = false + } + + func stopAnimatingView() { + #if os(macOS) + activityIndicatorView.stopAnimation(nil) + #else + activityIndicatorView.stopAnimating() + #endif + activityIndicatorView.isHidden = true + } + + init() { + #if os(macOS) + activityIndicatorView = NSProgressIndicator(frame: CGRect(x: 0, y: 0, width: 16, height: 16)) + activityIndicatorView.controlSize = .small + activityIndicatorView.style = .spinningStyle + #else + #if os(tvOS) + let indicatorStyle = UIActivityIndicatorViewStyle.white + #else + let indicatorStyle = UIActivityIndicatorViewStyle.gray + #endif + activityIndicatorView = UIActivityIndicatorView(activityIndicatorStyle:indicatorStyle) + activityIndicatorView.autoresizingMask = [.flexibleLeftMargin, .flexibleRightMargin, .flexibleBottomMargin, .flexibleTopMargin] + #endif + } +} + +// MARK: - ImageIndicator +// Displays an ImageView. Supports gif +struct ImageIndicator: Indicator { + private let animatedImageIndicatorView: ImageView + + var view: IndicatorView { + return animatedImageIndicatorView + } + + init?(imageData data: Data, processor: ImageProcessor = DefaultImageProcessor.default, options: KingfisherOptionsInfo = KingfisherEmptyOptionsInfo) { + + var options = options + // Use normal image view to show gif, so we need to preload all gif data. + if !options.preloadAllGIFData { + options.append(.preloadAllGIFData) + } + + guard let image = processor.process(item: .data(data), options: options) else { + return nil + } + + animatedImageIndicatorView = ImageView() + animatedImageIndicatorView.image = image + + #if os(macOS) + // Need for gif to animate on macOS + self.animatedImageIndicatorView.imageScaling = .scaleNone + self.animatedImageIndicatorView.canDrawSubviewsIntoLayer = true + #else + animatedImageIndicatorView.contentMode = .center + + animatedImageIndicatorView.autoresizingMask = [.flexibleLeftMargin, + .flexibleRightMargin, + .flexibleBottomMargin, + .flexibleTopMargin] + #endif + } + + func startAnimatingView() { + #if os(macOS) + animatedImageIndicatorView.animates = true + #else + animatedImageIndicatorView.startAnimating() + #endif + animatedImageIndicatorView.isHidden = false + } + + func stopAnimatingView() { + #if os(macOS) + animatedImageIndicatorView.animates = false + #else + animatedImageIndicatorView.stopAnimating() + #endif + animatedImageIndicatorView.isHidden = true + } +} diff --git a/GeneralUtils/GeneralUtils/libs/Kingfisher/Kingfisher.h b/GeneralUtils/GeneralUtils/libs/Kingfisher/Kingfisher.h new file mode 100644 index 0000000..05350ce --- /dev/null +++ b/GeneralUtils/GeneralUtils/libs/Kingfisher/Kingfisher.h @@ -0,0 +1,37 @@ +// +// Kingfisher.h +// Kingfisher +// +// Created by Wei Wang on 15/4/6. +// +// Copyright (c) 2016 Wei Wang +// +// Permission is hereby granted, free of charge, to any person obtaining a copy +// of this software and associated documentation files (the "Software"), to deal +// in the Software without restriction, including without limitation the rights +// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +// copies of the Software, and to permit persons to whom the Software is +// furnished to do so, subject to the following conditions: +// +// The above copyright notice and this permission notice shall be included in +// all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN +// THE SOFTWARE. + +#import + +//! Project version number for Kingfisher. +FOUNDATION_EXPORT double KingfisherVersionNumber; + +//! Project version string for Kingfisher. +FOUNDATION_EXPORT const unsigned char KingfisherVersionString[]; + +// In this header, you should import all the public headers of your framework using statements like #import + + diff --git a/GeneralUtils/GeneralUtils/libs/Kingfisher/Kingfisher.swift b/GeneralUtils/GeneralUtils/libs/Kingfisher/Kingfisher.swift new file mode 100644 index 0000000..b1bb397 --- /dev/null +++ b/GeneralUtils/GeneralUtils/libs/Kingfisher/Kingfisher.swift @@ -0,0 +1,71 @@ +// +// Kingfisher.swift +// Kingfisher +// +// Created by Wei Wang on 16/9/14. +// +// Copyright (c) 2016 Wei Wang +// +// Permission is hereby granted, free of charge, to any person obtaining a copy +// of this software and associated documentation files (the "Software"), to deal +// in the Software without restriction, including without limitation the rights +// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +// copies of the Software, and to permit persons to whom the Software is +// furnished to do so, subject to the following conditions: +// +// The above copyright notice and this permission notice shall be included in +// all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN +// THE SOFTWARE. + +import Foundation +import ImageIO + +#if os(macOS) + import AppKit + public typealias Image = NSImage + public typealias Color = NSColor + public typealias ImageView = NSImageView + typealias Button = NSButton +#else + import UIKit + public typealias Image = UIImage + public typealias Color = UIColor + #if !os(watchOS) + public typealias ImageView = UIImageView + typealias Button = UIButton + #endif +#endif + +public final class Kingfisher { + public let base: Base + public init(_ base: Base) { + self.base = base + } +} + +/** + A type that has Kingfisher extensions. + */ +public protocol KingfisherCompatible { + associatedtype CompatibleType + var kf: CompatibleType { get } +} + +public extension KingfisherCompatible { + public var kf: Kingfisher { + get { return Kingfisher(self) } + } +} + +extension Image: KingfisherCompatible { } +#if !os(watchOS) +extension ImageView: KingfisherCompatible { } +extension Button: KingfisherCompatible { } +#endif diff --git a/GeneralUtils/GeneralUtils/libs/Kingfisher/KingfisherManager.swift b/GeneralUtils/GeneralUtils/libs/Kingfisher/KingfisherManager.swift new file mode 100755 index 0000000..c3348f8 --- /dev/null +++ b/GeneralUtils/GeneralUtils/libs/Kingfisher/KingfisherManager.swift @@ -0,0 +1,213 @@ +// +// KingfisherManager.swift +// Kingfisher +// +// Created by Wei Wang on 15/4/6. +// +// Copyright (c) 2016 Wei Wang +// +// Permission is hereby granted, free of charge, to any person obtaining a copy +// of this software and associated documentation files (the "Software"), to deal +// in the Software without restriction, including without limitation the rights +// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +// copies of the Software, and to permit persons to whom the Software is +// furnished to do so, subject to the following conditions: +// +// The above copyright notice and this permission notice shall be included in +// all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN +// THE SOFTWARE. + +#if os(macOS) +import AppKit +#else +import UIKit +#endif + +public typealias DownloadProgressBlock = ((_ receivedSize: Int64, _ totalSize: Int64) -> ()) +public typealias CompletionHandler = ((_ image: Image?, _ error: NSError?, _ cacheType: CacheType, _ imageURL: URL?) -> ()) + +/// RetrieveImageTask represents a task of image retrieving process. +/// It contains an async task of getting image from disk and from network. +public class RetrieveImageTask { + + public static let empty = RetrieveImageTask() + + // If task is canceled before the download task started (which means the `downloadTask` is nil), + // the download task should not begin. + var cancelledBeforeDownloadStarting: Bool = false + + /// The disk retrieve task in this image task. Kingfisher will try to look up in cache first. This task represent the cache search task. + public var diskRetrieveTask: RetrieveImageDiskTask? + + /// The network retrieve task in this image task. + public var downloadTask: RetrieveImageDownloadTask? + + /** + Cancel current task. If this task does not begin or already done, do nothing. + */ + public func cancel() { + // From Xcode 7 beta 6, the `dispatch_block_cancel` will crash at runtime. + // It fixed in Xcode 7.1. + // See https://github.com/onevcat/Kingfisher/issues/99 for more. + if let diskRetrieveTask = diskRetrieveTask { + diskRetrieveTask.cancel() + } + + if let downloadTask = downloadTask { + downloadTask.cancel() + } else { + cancelledBeforeDownloadStarting = true + } + } +} + +/// Error domain of Kingfisher +public let KingfisherErrorDomain = "com.onevcat.Kingfisher.Error" + +/// Main manager class of Kingfisher. It connects Kingfisher downloader and cache. +/// You can use this class to retrieve an image via a specified URL from web or cache. +public class KingfisherManager { + + /// Shared manager used by the extensions across Kingfisher. + public static let shared = KingfisherManager() + + /// Cache used by this manager + public var cache: ImageCache + + /// Downloader used by this manager + public var downloader: ImageDownloader + + convenience init() { + self.init(downloader: .default, cache: .default) + } + + init(downloader: ImageDownloader, cache: ImageCache) { + self.downloader = downloader + self.cache = cache + } + + /** + Get an image with resource. + If KingfisherOptions.None is used as `options`, Kingfisher will seek the image in memory and disk first. + If not found, it will download the image at `resource.downloadURL` and cache it with `resource.cacheKey`. + These default behaviors could be adjusted by passing different options. See `KingfisherOptions` for more. + + - parameter resource: Resource object contains information such as `cacheKey` and `downloadURL`. + - parameter options: A dictionary could control some behaviors. See `KingfisherOptionsInfo` for more. + - parameter progressBlock: Called every time downloaded data changed. This could be used as a progress UI. + - parameter completionHandler: Called when the whole retrieving process finished. + + - returns: A `RetrieveImageTask` task object. You can use this object to cancel the task. + */ + @discardableResult + public func retrieveImage(with resource: Resource, + options: KingfisherOptionsInfo?, + progressBlock: DownloadProgressBlock?, + completionHandler: CompletionHandler?) -> RetrieveImageTask + { + let task = RetrieveImageTask() + + if let options = options, options.forceRefresh { + _ = downloadAndCacheImage( + with: resource.downloadURL, + forKey: resource.cacheKey, + retrieveImageTask: task, + progressBlock: progressBlock, + completionHandler: completionHandler, + options: options) + } else { + tryToRetrieveImageFromCache( + forKey: resource.cacheKey, + with: resource.downloadURL, + retrieveImageTask: task, + progressBlock: progressBlock, + completionHandler: completionHandler, + options: options) + } + + return task + } + + @discardableResult + func downloadAndCacheImage(with url: URL, + forKey key: String, + retrieveImageTask: RetrieveImageTask, + progressBlock: DownloadProgressBlock?, + completionHandler: CompletionHandler?, + options: KingfisherOptionsInfo?) -> RetrieveImageDownloadTask? + { + let options = options ?? KingfisherEmptyOptionsInfo + let downloader = options.downloader + return downloader.downloadImage(with: url, retrieveImageTask: retrieveImageTask, options: options, + progressBlock: { receivedSize, totalSize in + progressBlock?(receivedSize, totalSize) + }, + completionHandler: { image, error, imageURL, originalData in + + let targetCache = options.targetCache + if let error = error, error.code == KingfisherError.notModified.rawValue { + // Not modified. Try to find the image from cache. + // (The image should be in cache. It should be guaranteed by the framework users.) + targetCache.retrieveImage(forKey: key, options: options, completionHandler: { (cacheImage, cacheType) -> () in + completionHandler?(cacheImage, nil, cacheType, url) + }) + return + } + + if let image = image, let originalData = originalData { + targetCache.store(image, + original: originalData, + forKey: key, + processorIdentifier:options.processor.identifier, + cacheSerializer: options.cacheSerializer, + toDisk: !options.cacheMemoryOnly, + completionHandler: nil) + } + + completionHandler?(image, error, .none, url) + + }) + } + + func tryToRetrieveImageFromCache(forKey key: String, + with url: URL, + retrieveImageTask: RetrieveImageTask, + progressBlock: DownloadProgressBlock?, + completionHandler: CompletionHandler?, + options: KingfisherOptionsInfo?) + { + let diskTaskCompletionHandler: CompletionHandler = { (image, error, cacheType, imageURL) -> () in + // Break retain cycle created inside diskTask closure below + retrieveImageTask.diskRetrieveTask = nil + completionHandler?(image, error, cacheType, imageURL) + } + + let targetCache = options?.targetCache ?? cache + let diskTask = targetCache.retrieveImage(forKey: key, options: options, + completionHandler: { image, cacheType in + if image != nil { + diskTaskCompletionHandler(image, nil, cacheType, url) + } else if let options = options, options.onlyFromCache { + let error = NSError(domain: KingfisherErrorDomain, code: KingfisherError.notCached.rawValue, userInfo: nil) + diskTaskCompletionHandler(nil, error, .none, url) + } else { + self.downloadAndCacheImage( + with: url, + forKey: key, + retrieveImageTask: retrieveImageTask, + progressBlock: progressBlock, + completionHandler: diskTaskCompletionHandler, + options: options) + } + } + ) + retrieveImageTask.diskRetrieveTask = diskTask + } +} diff --git a/GeneralUtils/GeneralUtils/libs/Kingfisher/KingfisherOptionsInfo.swift b/GeneralUtils/GeneralUtils/libs/Kingfisher/KingfisherOptionsInfo.swift new file mode 100755 index 0000000..2ed7b62 --- /dev/null +++ b/GeneralUtils/GeneralUtils/libs/Kingfisher/KingfisherOptionsInfo.swift @@ -0,0 +1,285 @@ +// +// KingfisherOptionsInfo.swift +// Kingfisher +// +// Created by Wei Wang on 15/4/23. +// +// Copyright (c) 2016 Wei Wang +// +// Permission is hereby granted, free of charge, to any person obtaining a copy +// of this software and associated documentation files (the "Software"), to deal +// in the Software without restriction, including without limitation the rights +// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +// copies of the Software, and to permit persons to whom the Software is +// furnished to do so, subject to the following conditions: +// +// The above copyright notice and this permission notice shall be included in +// all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN +// THE SOFTWARE. + +#if os(macOS) +import AppKit +#else +import UIKit +#endif + + +/** +* KingfisherOptionsInfo is a typealias for [KingfisherOptionsInfoItem]. You can use the enum of option item with value to control some behaviors of Kingfisher. +*/ +public typealias KingfisherOptionsInfo = [KingfisherOptionsInfoItem] +let KingfisherEmptyOptionsInfo = [KingfisherOptionsInfoItem]() + +/** +Items could be added into KingfisherOptionsInfo. +*/ +public enum KingfisherOptionsInfoItem { + /// The associated value of this member should be an ImageCache object. Kingfisher will use the specified + /// cache object when handling related operations, including trying to retrieve the cached images and store + /// the downloaded image to it. + case targetCache(ImageCache) + + /// The associated value of this member should be an ImageDownloader object. Kingfisher will use this + /// downloader to download the images. + case downloader(ImageDownloader) + + /// Member for animation transition when using UIImageView. Kingfisher will use the `ImageTransition` of + /// this enum to animate the image in if it is downloaded from web. The transition will not happen when the + /// image is retrieved from either memory or disk cache by default. If you need to do the transition even when + /// the image being retrieved from cache, set `ForceTransition` as well. + case transition(ImageTransition) + + /// Associated `Float` value will be set as the priority of image download task. The value for it should be + /// between 0.0~1.0. If this option not set, the default value (`NSURLSessionTaskPriorityDefault`) will be used. + case downloadPriority(Float) + + /// If set, `Kingfisher` will ignore the cache and try to fire a download task for the resource. + case forceRefresh + + /// If set, setting the image to an image view will happen with transition even when retrieved from cache. + /// See `Transition` option for more. + case forceTransition + + /// If set, `Kingfisher` will only cache the value in memory but not in disk. + case cacheMemoryOnly + + /// If set, `Kingfisher` will only try to retrieve the image from cache not from network. + case onlyFromCache + + /// Decode the image in background thread before using. + case backgroundDecode + + /// The associated value of this member will be used as the target queue of dispatch callbacks when + /// retrieving images from cache. If not set, `Kingfisher` will use main quese for callbacks. + case callbackDispatchQueue(DispatchQueue?) + + /// The associated value of this member will be used as the scale factor when converting retrieved data to an image. + /// It is the image scale, instead of your screen scale. You may need to specify the correct scale when you dealing + /// with 2x or 3x retina images. + case scaleFactor(CGFloat) + + /// Whether all the GIF data should be preloaded. Default it false, which means following frames will be + /// loaded on need. If true, all the GIF data will be loaded and decoded into memory. This option is mainly + /// used for back compatibility internally. You should not set it directly. `AnimatedImageView` will not preload + /// all data, while a normal image view (`UIImageView` or `NSImageView`) will load all data. Choose to use + /// corresponding image view type instead of setting this option. + case preloadAllGIFData + + /// The `ImageDownloadRequestModifier` contained will be used to change the request before it being sent. + /// This is the last chance you can modify the request. You can modify the request for some customizing purpose, + /// such as adding auth token to the header, do basic HTTP auth or something like url mapping. The original request + /// will be sent without any modification by default. + case requestModifier(ImageDownloadRequestModifier) + + /// Processor for processing when the downloading finishes, a processor will convert the downloaded data to an image + /// and/or apply some filter on it. If a cache is connected to the downloader (it happenes when you are using + /// KingfisherManager or the image extension methods), the converted image will also be sent to cache as well as the + /// image view. `DefaultImageProcessor.default` will be used by default. + case processor(ImageProcessor) + + /// Supply an `CacheSerializer` to convert some data to an image object for + /// retrieving from disk cache or vice versa for storing to disk cache. + /// `DefaultCacheSerializer.default` will be used by default. + case cacheSerializer(CacheSerializer) + + /// Keep the existing image while setting another image to an image view. + /// By setting this option, the placeholder image parameter of imageview extension method + /// will be ignored and the current image will be kept while loading or downloading the new image. + case keepCurrentImageWhileLoading +} + +precedencegroup ItemComparisonPrecedence { + associativity: none + higherThan: LogicalConjunctionPrecedence +} + +infix operator <== : ItemComparisonPrecedence + +// This operator returns true if two `KingfisherOptionsInfoItem` enum is the same, without considering the associated values. +func <== (lhs: KingfisherOptionsInfoItem, rhs: KingfisherOptionsInfoItem) -> Bool { + switch (lhs, rhs) { + case (.targetCache(_), .targetCache(_)): return true + case (.downloader(_), .downloader(_)): return true + case (.transition(_), .transition(_)): return true + case (.downloadPriority(_), .downloadPriority(_)): return true + case (.forceRefresh, .forceRefresh): return true + case (.forceTransition, .forceTransition): return true + case (.cacheMemoryOnly, .cacheMemoryOnly): return true + case (.onlyFromCache, .onlyFromCache): return true + case (.backgroundDecode, .backgroundDecode): return true + case (.callbackDispatchQueue(_), .callbackDispatchQueue(_)): return true + case (.scaleFactor(_), .scaleFactor(_)): return true + case (.preloadAllGIFData, .preloadAllGIFData): return true + case (.requestModifier(_), .requestModifier(_)): return true + case (.processor(_), .processor(_)): return true + case (.cacheSerializer(_), .cacheSerializer(_)): return true + case (.keepCurrentImageWhileLoading, .keepCurrentImageWhileLoading): return true + default: return false + } +} + +extension Collection where Iterator.Element == KingfisherOptionsInfoItem { + func firstMatchIgnoringAssociatedValue(_ target: Iterator.Element) -> Iterator.Element? { + return index { $0 <== target }.flatMap { self[$0] } + } + + func removeAllMatchesIgnoringAssociatedValue(_ target: Iterator.Element) -> [Iterator.Element] { + return self.filter { !($0 <== target) } + } +} + +public extension Collection where Iterator.Element == KingfisherOptionsInfoItem { + /// The target `ImageCache` which is used. + public var targetCache: ImageCache { + if let item = firstMatchIgnoringAssociatedValue(.targetCache(.default)), + case .targetCache(let cache) = item + { + return cache + } + return ImageCache.default + } + + /// The `ImageDownloader` which is specified. + public var downloader: ImageDownloader { + if let item = firstMatchIgnoringAssociatedValue(.downloader(.default)), + case .downloader(let downloader) = item + { + return downloader + } + return ImageDownloader.default + } + + /// Member for animation transition when using UIImageView. + public var transition: ImageTransition { + if let item = firstMatchIgnoringAssociatedValue(.transition(.none)), + case .transition(let transition) = item + { + return transition + } + return ImageTransition.none + } + + /// A `Float` value set as the priority of image download task. The value for it should be + /// between 0.0~1.0. + public var downloadPriority: Float { + if let item = firstMatchIgnoringAssociatedValue(.downloadPriority(0)), + case .downloadPriority(let priority) = item + { + return priority + } + return URLSessionTask.defaultPriority + } + + /// Whether an image will be always downloaded again or not. + public var forceRefresh: Bool { + return contains{ $0 <== .forceRefresh } + } + + /// Whether the transition should always happen or not. + public var forceTransition: Bool { + return contains{ $0 <== .forceTransition } + } + + /// Whether cache the image only in memory or not. + public var cacheMemoryOnly: Bool { + return contains{ $0 <== .cacheMemoryOnly } + } + + /// Whether only load the images from cache or not. + public var onlyFromCache: Bool { + return contains{ $0 <== .onlyFromCache } + } + + /// Whether the image should be decoded in background or not. + public var backgroundDecode: Bool { + return contains{ $0 <== .backgroundDecode } + } + + /// Whether the image data should be all loaded at once if it is a GIF. + public var preloadAllGIFData: Bool { + return contains { $0 <== .preloadAllGIFData } + } + + /// The queue of callbacks should happen from Kingfisher. + public var callbackDispatchQueue: DispatchQueue { + if let item = firstMatchIgnoringAssociatedValue(.callbackDispatchQueue(nil)), + case .callbackDispatchQueue(let queue) = item + { + return queue ?? DispatchQueue.main + } + return DispatchQueue.main + } + + /// The scale factor which should be used for the image. + public var scaleFactor: CGFloat { + if let item = firstMatchIgnoringAssociatedValue(.scaleFactor(0)), + case .scaleFactor(let scale) = item + { + return scale + } + return 1.0 + } + + /// The `ImageDownloadRequestModifier` will be used before sending a download request. + public var modifier: ImageDownloadRequestModifier { + if let item = firstMatchIgnoringAssociatedValue(.requestModifier(NoModifier.default)), + case .requestModifier(let modifier) = item + { + return modifier + } + return NoModifier.default + } + + /// `ImageProcessor` for processing when the downloading finishes. + public var processor: ImageProcessor { + if let item = firstMatchIgnoringAssociatedValue(.processor(DefaultImageProcessor.default)), + case .processor(let processor) = item + { + return processor + } + return DefaultImageProcessor.default + } + + /// `CacheSerializer` to convert image to data for storing in cache. + public var cacheSerializer: CacheSerializer { + if let item = firstMatchIgnoringAssociatedValue(.cacheSerializer(DefaultCacheSerializer.default)), + case .cacheSerializer(let cacheSerializer) = item + { + return cacheSerializer + } + return DefaultCacheSerializer.default + } + + /// Keep the existing image while setting another image to an image view. + /// Or the placeholder will be used while downloading. + public var keepCurrentImageWhileLoading: Bool { + return contains { $0 <== .keepCurrentImageWhileLoading } + } +} diff --git a/GeneralUtils/GeneralUtils/libs/Kingfisher/RequestModifier.swift b/GeneralUtils/GeneralUtils/libs/Kingfisher/RequestModifier.swift new file mode 100644 index 0000000..afde19a --- /dev/null +++ b/GeneralUtils/GeneralUtils/libs/Kingfisher/RequestModifier.swift @@ -0,0 +1,53 @@ +// +// RequestModifier.swift +// Kingfisher +// +// Created by Wei Wang on 2016/09/05. +// +// Copyright (c) 2016 Wei Wang +// +// Permission is hereby granted, free of charge, to any person obtaining a copy +// of this software and associated documentation files (the "Software"), to deal +// in the Software without restriction, including without limitation the rights +// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +// copies of the Software, and to permit persons to whom the Software is +// furnished to do so, subject to the following conditions: +// +// The above copyright notice and this permission notice shall be included in +// all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN +// THE SOFTWARE. + +import Foundation + +/// Request modifier of image downloader. +public protocol ImageDownloadRequestModifier { + func modified(for request: URLRequest) -> URLRequest? +} + +struct NoModifier: ImageDownloadRequestModifier { + static let `default` = NoModifier() + private init() {} + func modified(for request: URLRequest) -> URLRequest? { + return request + } +} + +public struct AnyModifier: ImageDownloadRequestModifier { + + let block: (URLRequest) -> URLRequest? + + public func modified(for request: URLRequest) -> URLRequest? { + return block(request) + } + + public init(modify: @escaping (URLRequest) -> URLRequest? ) { + block = modify + } +} diff --git a/GeneralUtils/GeneralUtils/libs/Kingfisher/Resource.swift b/GeneralUtils/GeneralUtils/libs/Kingfisher/Resource.swift new file mode 100755 index 0000000..875927f --- /dev/null +++ b/GeneralUtils/GeneralUtils/libs/Kingfisher/Resource.swift @@ -0,0 +1,74 @@ +// +// Resource.swift +// Kingfisher +// +// Created by Wei Wang on 15/4/6. +// +// Copyright (c) 2016 Wei Wang +// +// Permission is hereby granted, free of charge, to any person obtaining a copy +// of this software and associated documentation files (the "Software"), to deal +// in the Software without restriction, including without limitation the rights +// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +// copies of the Software, and to permit persons to whom the Software is +// furnished to do so, subject to the following conditions: +// +// The above copyright notice and this permission notice shall be included in +// all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN +// THE SOFTWARE. + +import Foundation + + +/// `Resource` protocol defines how to download and cache a resource from network. +public protocol Resource { + /// The key used in cache. + var cacheKey: String { get } + + /// The target image URL. + var downloadURL: URL { get } +} + +/** + ImageResource is a simple combination of `downloadURL` and `cacheKey`. + + When passed to image view set methods, Kingfisher will try to download the target + image from the `downloadURL`, and then store it with the `cacheKey` as the key in cache. + */ +public struct ImageResource: Resource { + /// The key used in cache. + public let cacheKey: String + + /// The target image URL. + public let downloadURL: URL + + /** + Create a resource. + + - parameter downloadURL: The target image URL. + - parameter cacheKey: The cache key. If `nil`, Kingfisher will use the `absoluteString` of `downloadURL` as the key. + + - returns: A resource. + */ + public init(downloadURL: URL, cacheKey: String? = nil) { + self.downloadURL = downloadURL + self.cacheKey = cacheKey ?? downloadURL.absoluteString + } +} + +/** + URL conforms to `Resource` in Kingfisher. + The `absoluteString` of this URL is used as `cacheKey`. And the URL itself will be used as `downloadURL`. + If you need customize the url and/or cache key, use `ImageResource` instead. + */ +extension URL: Resource { + public var cacheKey: String { return absoluteString } + public var downloadURL: URL { return self } +} diff --git a/GeneralUtils/GeneralUtils/libs/Kingfisher/String+MD5.swift b/GeneralUtils/GeneralUtils/libs/Kingfisher/String+MD5.swift new file mode 100755 index 0000000..2f71cd3 --- /dev/null +++ b/GeneralUtils/GeneralUtils/libs/Kingfisher/String+MD5.swift @@ -0,0 +1,292 @@ +// +// String+MD5.swift +// Kingfisher +// +// To date, adding CommonCrypto to a Swift framework is problematic. See: +// http://stackoverflow.com/questions/25248598/importing-commoncrypto-in-a-swift-framework +// We're using a subset and modified version of CryptoSwift as an alternative. +// The following is an altered source version that only includes MD5. The original software can be found at: +// https://github.com/krzyzanowskim/CryptoSwift +// This is the original copyright notice: + +/* +Copyright (C) 2014 Marcin Krzyżanowski +This software is provided 'as-is', without any express or implied warranty. +In no event will the authors be held liable for any damages arising from the use of this software. +Permission is granted to anyone to use this software for any purpose,including commercial applications, and to alter it and redistribute it freely, subject to the following restrictions: +- The origin of this software must not be misrepresented; you must not claim that you wrote the original software. If you use this software in a product, an acknowledgment in the product documentation is required. +- Altered source versions must be plainly marked as such, and must not be misrepresented as being the original software. +- This notice may not be removed or altered from any source or binary distribution. +*/ + +import Foundation + +public struct StringProxy { + fileprivate let base: String + init(proxy: String) { + base = proxy + } +} + +extension String: KingfisherCompatible { + public typealias CompatibleType = StringProxy + public var kf: CompatibleType { + return StringProxy(proxy: self) + } +} + +extension StringProxy { + var md5: String { + if let data = base.data(using: .utf8, allowLossyConversion: true) { + + let message = data.withUnsafeBytes { bytes -> [UInt8] in + return Array(UnsafeBufferPointer(start: bytes, count: data.count)) + } + + let MD5Calculator = KSMD5(message) + let MD5Data = MD5Calculator.calculate() + + let MD5String = NSMutableString() + for c in MD5Data { + MD5String.appendFormat("%02x", c) + } + return MD5String as String + + } else { + return base + } + } +} + + +/** array of bytes, little-endian representation */ +func arrayOfBytes(_ value: T, length: Int? = nil) -> [UInt8] { + let totalBytes = length ?? (MemoryLayout.size * 8) + + let valuePointer = UnsafeMutablePointer.allocate(capacity: 1) + valuePointer.pointee = value + + let bytes = valuePointer.withMemoryRebound(to: UInt8.self, capacity: totalBytes) { (bytesPointer) -> [UInt8] in + var bytes = [UInt8](repeating: 0, count: totalBytes) + for j in 0...size, totalBytes) { + bytes[totalBytes - 1 - j] = (bytesPointer + j).pointee + } + return bytes + } + + valuePointer.deinitialize() + valuePointer.deallocate(capacity: 1) + + return bytes +} + +extension Int { + /** Array of bytes with optional padding (little-endian) */ + func bytes(_ totalBytes: Int = MemoryLayout.size) -> [UInt8] { + return arrayOfBytes(self, length: totalBytes) + } + +} + +extension NSMutableData { + + /** Convenient way to append bytes */ + func appendBytes(_ arrayOfBytes: [UInt8]) { + append(arrayOfBytes, length: arrayOfBytes.count) + } + +} + +protocol HashProtocol { + var message: Array { get } + + /** Common part for hash calculation. Prepare header data. */ + func prepare(_ len: Int) -> Array +} + +extension HashProtocol { + + func prepare(_ len: Int) -> Array { + var tmpMessage = message + + // Step 1. Append Padding Bits + tmpMessage.append(0x80) // append one bit (UInt8 with one bit) to message + + // append "0" bit until message length in bits ≡ 448 (mod 512) + var msgLength = tmpMessage.count + var counter = 0 + + while msgLength % len != (len - 8) { + counter += 1 + msgLength += 1 + } + + tmpMessage += Array(repeating: 0, count: counter) + return tmpMessage + } +} + +func toUInt32Array(_ slice: ArraySlice) -> Array { + var result = Array() + result.reserveCapacity(16) + + for idx in stride(from: slice.startIndex, to: slice.endIndex, by: MemoryLayout.size) { + let d0 = UInt32(slice[idx.advanced(by: 3)]) << 24 + let d1 = UInt32(slice[idx.advanced(by: 2)]) << 16 + let d2 = UInt32(slice[idx.advanced(by: 1)]) << 8 + let d3 = UInt32(slice[idx]) + let val: UInt32 = d0 | d1 | d2 | d3 + + result.append(val) + } + return result +} + +struct BytesIterator: IteratorProtocol { + + let chunkSize: Int + let data: [UInt8] + + init(chunkSize: Int, data: [UInt8]) { + self.chunkSize = chunkSize + self.data = data + } + + var offset = 0 + + mutating func next() -> ArraySlice? { + let end = min(chunkSize, data.count - offset) + let result = data[offset.. 0 ? result : nil + } +} + +struct KSBytesSequence: Sequence { + let chunkSize: Int + let data: [UInt8] + + func makeIterator() -> BytesIterator { + return BytesIterator(chunkSize: chunkSize, data: data) + } +} + +func rotateLeft(_ value: UInt32, bits: UInt32) -> UInt32 { + return ((value << bits) & 0xFFFFFFFF) | (value >> (32 - bits)) +} + +class KSMD5: HashProtocol { + + static let size = 16 // 128 / 8 + let message: [UInt8] + + init (_ message: [UInt8]) { + self.message = message + } + + /** specifies the per-round shift amounts */ + private let shifts: [UInt32] = [7, 12, 17, 22, 7, 12, 17, 22, 7, 12, 17, 22, 7, 12, 17, 22, + 5, 9, 14, 20, 5, 9, 14, 20, 5, 9, 14, 20, 5, 9, 14, 20, + 4, 11, 16, 23, 4, 11, 16, 23, 4, 11, 16, 23, 4, 11, 16, 23, + 6, 10, 15, 21, 6, 10, 15, 21, 6, 10, 15, 21, 6, 10, 15, 21] + + /** binary integer part of the sines of integers (Radians) */ + private let sines: [UInt32] = [0xd76aa478, 0xe8c7b756, 0x242070db, 0xc1bdceee, + 0xf57c0faf, 0x4787c62a, 0xa8304613, 0xfd469501, + 0x698098d8, 0x8b44f7af, 0xffff5bb1, 0x895cd7be, + 0x6b901122, 0xfd987193, 0xa679438e, 0x49b40821, + 0xf61e2562, 0xc040b340, 0x265e5a51, 0xe9b6c7aa, + 0xd62f105d, 0x02441453, 0xd8a1e681, 0xe7d3fbc8, + 0x21e1cde6, 0xc33707d6, 0xf4d50d87, 0x455a14ed, + 0xa9e3e905, 0xfcefa3f8, 0x676f02d9, 0x8d2a4c8a, + 0xfffa3942, 0x8771f681, 0x6d9d6122, 0xfde5380c, + 0xa4beea44, 0x4bdecfa9, 0xf6bb4b60, 0xbebfbc70, + 0x289b7ec6, 0xeaa127fa, 0xd4ef3085, 0x4881d05, + 0xd9d4d039, 0xe6db99e5, 0x1fa27cf8, 0xc4ac5665, + 0xf4292244, 0x432aff97, 0xab9423a7, 0xfc93a039, + 0x655b59c3, 0x8f0ccc92, 0xffeff47d, 0x85845dd1, + 0x6fa87e4f, 0xfe2ce6e0, 0xa3014314, 0x4e0811a1, + 0xf7537e82, 0xbd3af235, 0x2ad7d2bb, 0xeb86d391] + + private let hashes: [UInt32] = [0x67452301, 0xefcdab89, 0x98badcfe, 0x10325476] + + func calculate() -> [UInt8] { + var tmpMessage = prepare(64) + tmpMessage.reserveCapacity(tmpMessage.count + 4) + + // hash values + var hh = hashes + + // Step 2. Append Length a 64-bit representation of lengthInBits + let lengthInBits = (message.count * 8) + let lengthBytes = lengthInBits.bytes(64 / 8) + tmpMessage += lengthBytes.reversed() + + // Process the message in successive 512-bit chunks: + let chunkSizeBytes = 512 / 8 // 64 + + for chunk in KSBytesSequence(chunkSize: chunkSizeBytes, data: tmpMessage) { + // break chunk into sixteen 32-bit words M[j], 0 ≤ j ≤ 15 + var M = toUInt32Array(chunk) + assert(M.count == 16, "Invalid array") + + // Initialize hash value for this chunk: + var A: UInt32 = hh[0] + var B: UInt32 = hh[1] + var C: UInt32 = hh[2] + var D: UInt32 = hh[3] + + var dTemp: UInt32 = 0 + + // Main loop + for j in 0 ..< sines.count { + var g = 0 + var F: UInt32 = 0 + + switch j { + case 0...15: + F = (B & C) | ((~B) & D) + g = j + break + case 16...31: + F = (D & B) | (~D & C) + g = (5 * j + 1) % 16 + break + case 32...47: + F = B ^ C ^ D + g = (3 * j + 5) % 16 + break + case 48...63: + F = C ^ (B | (~D)) + g = (7 * j) % 16 + break + default: + break + } + dTemp = D + D = C + C = B + B = B &+ rotateLeft((A &+ F &+ sines[j] &+ M[g]), bits: shifts[j]) + A = dTemp + } + + hh[0] = hh[0] &+ A + hh[1] = hh[1] &+ B + hh[2] = hh[2] &+ C + hh[3] = hh[3] &+ D + } + + var result = [UInt8]() + result.reserveCapacity(hh.count / 4) + + hh.forEach { + let itemLE = $0.littleEndian + let r1 = UInt8(itemLE & 0xff) + let r2 = UInt8((itemLE >> 8) & 0xff) + let r3 = UInt8((itemLE >> 16) & 0xff) + let r4 = UInt8((itemLE >> 24) & 0xff) + result += [r1, r2, r3, r4] + } + return result + } +} diff --git a/GeneralUtils/GeneralUtils/libs/Kingfisher/ThreadHelper.swift b/GeneralUtils/GeneralUtils/libs/Kingfisher/ThreadHelper.swift new file mode 100755 index 0000000..afb3c93 --- /dev/null +++ b/GeneralUtils/GeneralUtils/libs/Kingfisher/ThreadHelper.swift @@ -0,0 +1,40 @@ +// +// ThreadHelper.swift +// Kingfisher +// +// Created by Wei Wang on 15/10/9. +// +// Copyright (c) 2016 Wei Wang +// +// Permission is hereby granted, free of charge, to any person obtaining a copy +// of this software and associated documentation files (the "Software"), to deal +// in the Software without restriction, including without limitation the rights +// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +// copies of the Software, and to permit persons to whom the Software is +// furnished to do so, subject to the following conditions: +// +// The above copyright notice and this permission notice shall be included in +// all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN +// THE SOFTWARE. + +import Foundation + +extension DispatchQueue { + // This method will dispatch the `block` to self. + // If `self` is the main queue, and current thread is main thread, the block + // will be invoked immediately instead of being dispatched. + func safeAsync(_ block: @escaping ()->()) { + if self === DispatchQueue.main && Thread.isMainThread { + block() + } else { + async { block() } + } + } +} diff --git a/GeneralUtils/GeneralUtils/libs/Kingfisher/UIButton+Kingfisher.swift b/GeneralUtils/GeneralUtils/libs/Kingfisher/UIButton+Kingfisher.swift new file mode 100755 index 0000000..e1b1809 --- /dev/null +++ b/GeneralUtils/GeneralUtils/libs/Kingfisher/UIButton+Kingfisher.swift @@ -0,0 +1,407 @@ +// +// UIButton+Kingfisher.swift +// Kingfisher +// +// Created by Wei Wang on 15/4/13. +// +// Copyright (c) 2016 Wei Wang +// +// Permission is hereby granted, free of charge, to any person obtaining a copy +// of this software and associated documentation files (the "Software"), to deal +// in the Software without restriction, including without limitation the rights +// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +// copies of the Software, and to permit persons to whom the Software is +// furnished to do so, subject to the following conditions: +// +// The above copyright notice and this permission notice shall be included in +// all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN +// THE SOFTWARE. + +import UIKit + +// MARK: - Set Images +/** + * Set image to use in button from web for a specified state. + */ +extension Kingfisher where Base: UIButton { + /** + Set an image to use for a specified state with a resource, a placeholder image, options, progress handler and + completion handler. + + - parameter resource: Resource object contains information such as `cacheKey` and `downloadURL`. + - parameter state: The state that uses the specified image. + - parameter placeholder: A placeholder image when retrieving the image at URL. + - parameter options: A dictionary could control some behaviors. See `KingfisherOptionsInfo` for more. + - parameter progressBlock: Called when the image downloading progress gets updated. + - parameter completionHandler: Called when the image retrieved and set. + + - returns: A task represents the retrieving process. + + - note: Both the `progressBlock` and `completionHandler` will be invoked in main thread. + The `CallbackDispatchQueue` specified in `optionsInfo` will not be used in callbacks of this method. + */ + @discardableResult + public func setImage(with resource: Resource?, + for state: UIControlState, + placeholder: UIImage? = nil, + options: KingfisherOptionsInfo? = nil, + progressBlock: DownloadProgressBlock? = nil, + completionHandler: CompletionHandler? = nil) -> RetrieveImageTask + { + guard let resource = resource else { + base.setImage(placeholder, for: state) + completionHandler?(nil, nil, .none, nil) + return .empty + } + + let options = options ?? KingfisherEmptyOptionsInfo + if !options.keepCurrentImageWhileLoading { + base.setImage(placeholder, for: state) + } + + setWebURL(resource.downloadURL, for: state) + let task = KingfisherManager.shared.retrieveImage( + with: resource, + options: options, + progressBlock: { receivedSize, totalSize in + if let progressBlock = progressBlock { + progressBlock(receivedSize, totalSize) + } + }, + completionHandler: {[weak base] image, error, cacheType, imageURL in + DispatchQueue.main.safeAsync { + guard let strongBase = base, imageURL == self.webURL(for: state) else { + return + } + self.setImageTask(nil) + + if image != nil { + strongBase.setImage(image, for: state) + } + + completionHandler?(image, error, cacheType, imageURL) + } + }) + + setImageTask(task) + return task + } + + /** + Cancel the image download task bounded to the image view if it is running. + Nothing will happen if the downloading has already finished. + */ + public func cancelImageDownloadTask() { + imageTask?.downloadTask?.cancel() + } + + /** + Set the background image to use for a specified state with a resource, + a placeholder image, options progress handler and completion handler. + + - parameter resource: Resource object contains information such as `cacheKey` and `downloadURL`. + - parameter state: The state that uses the specified image. + - parameter placeholder: A placeholder image when retrieving the image at URL. + - parameter options: A dictionary could control some behaviors. See `KingfisherOptionsInfo` for more. + - parameter progressBlock: Called when the image downloading progress gets updated. + - parameter completionHandler: Called when the image retrieved and set. + + - returns: A task represents the retrieving process. + + - note: Both the `progressBlock` and `completionHandler` will be invoked in main thread. + The `CallbackDispatchQueue` specified in `optionsInfo` will not be used in callbacks of this method. + */ + @discardableResult + public func setBackgroundImage(with resource: Resource?, + for state: UIControlState, + placeholder: UIImage? = nil, + options: KingfisherOptionsInfo? = nil, + progressBlock: DownloadProgressBlock? = nil, + completionHandler: CompletionHandler? = nil) -> RetrieveImageTask + { + guard let resource = resource else { + base.setBackgroundImage(placeholder, for: state) + completionHandler?(nil, nil, .none, nil) + return .empty + } + + let options = options ?? KingfisherEmptyOptionsInfo + if !options.keepCurrentImageWhileLoading { + base.setBackgroundImage(placeholder, for: state) + } + + setBackgroundWebURL(resource.downloadURL, for: state) + let task = KingfisherManager.shared.retrieveImage( + with: resource, + options: options, + progressBlock: { receivedSize, totalSize in + if let progressBlock = progressBlock { + progressBlock(receivedSize, totalSize) + } + }, + completionHandler: { [weak base] image, error, cacheType, imageURL in + DispatchQueue.main.safeAsync { + guard let strongBase = base, imageURL == self.backgroundWebURL(for: state) else { + return + } + self.setBackgroundImageTask(nil) + if image != nil { + strongBase.setBackgroundImage(image, for: state) + } + completionHandler?(image, error, cacheType, imageURL) + } + }) + + setBackgroundImageTask(task) + return task + } + + /** + Cancel the background image download task bounded to the image view if it is running. + Nothing will happen if the downloading has already finished. + */ + public func cancelBackgroundImageDownloadTask() { + backgroundImageTask?.downloadTask?.cancel() + } + +} + +// MARK: - Associated Object +private var lastURLKey: Void? +private var imageTaskKey: Void? + +extension Kingfisher where Base: UIButton { + /** + Get the image URL binded to this button for a specified state. + + - parameter state: The state that uses the specified image. + + - returns: Current URL for image. + */ + public func webURL(for state: UIControlState) -> URL? { + return webURLs[NSNumber(value:state.rawValue)] as? URL + } + + fileprivate func setWebURL(_ url: URL, for state: UIControlState) { + webURLs[NSNumber(value:state.rawValue)] = url + } + + fileprivate var webURLs: NSMutableDictionary { + var dictionary = objc_getAssociatedObject(base, &lastURLKey) as? NSMutableDictionary + if dictionary == nil { + dictionary = NSMutableDictionary() + setWebURLs(dictionary!) + } + return dictionary! + } + + fileprivate func setWebURLs(_ URLs: NSMutableDictionary) { + objc_setAssociatedObject(base, &lastURLKey, URLs, .OBJC_ASSOCIATION_RETAIN_NONATOMIC) + } + + fileprivate var imageTask: RetrieveImageTask? { + return objc_getAssociatedObject(base, &imageTaskKey) as? RetrieveImageTask + } + + fileprivate func setImageTask(_ task: RetrieveImageTask?) { + objc_setAssociatedObject(base, &imageTaskKey, task, .OBJC_ASSOCIATION_RETAIN_NONATOMIC) + } +} + + +private var lastBackgroundURLKey: Void? +private var backgroundImageTaskKey: Void? + + +extension Kingfisher where Base: UIButton { + /** + Get the background image URL binded to this button for a specified state. + + - parameter state: The state that uses the specified background image. + + - returns: Current URL for background image. + */ + public func backgroundWebURL(for state: UIControlState) -> URL? { + return backgroundWebURLs[NSNumber(value:state.rawValue)] as? URL + } + + fileprivate func setBackgroundWebURL(_ url: URL, for state: UIControlState) { + backgroundWebURLs[NSNumber(value:state.rawValue)] = url + } + + fileprivate var backgroundWebURLs: NSMutableDictionary { + var dictionary = objc_getAssociatedObject(base, &lastBackgroundURLKey) as? NSMutableDictionary + if dictionary == nil { + dictionary = NSMutableDictionary() + setBackgroundWebURLs(dictionary!) + } + return dictionary! + } + + fileprivate func setBackgroundWebURLs(_ URLs: NSMutableDictionary) { + objc_setAssociatedObject(base, &lastBackgroundURLKey, URLs, .OBJC_ASSOCIATION_RETAIN_NONATOMIC) + } + + fileprivate var backgroundImageTask: RetrieveImageTask? { + return objc_getAssociatedObject(base, &backgroundImageTaskKey) as? RetrieveImageTask + } + + fileprivate func setBackgroundImageTask(_ task: RetrieveImageTask?) { + objc_setAssociatedObject(base, &backgroundImageTaskKey, task, .OBJC_ASSOCIATION_RETAIN_NONATOMIC) + } +} + +// MARK: - Deprecated. Only for back compatibility. +/** +* Set image to use from web for a specified state. Deprecated. Use `kf` namespacing instead. +*/ +extension UIButton { + /** + Set an image to use for a specified state with a resource, a placeholder image, options, progress handler and + completion handler. + + - parameter resource: Resource object contains information such as `cacheKey` and `downloadURL`. + - parameter state: The state that uses the specified image. + - parameter placeholder: A placeholder image when retrieving the image at URL. + - parameter options: A dictionary could control some behaviors. See `KingfisherOptionsInfo` for more. + - parameter progressBlock: Called when the image downloading progress gets updated. + - parameter completionHandler: Called when the image retrieved and set. + + - returns: A task represents the retrieving process. + + - note: Both the `progressBlock` and `completionHandler` will be invoked in main thread. + The `CallbackDispatchQueue` specified in `optionsInfo` will not be used in callbacks of this method. + */ + @discardableResult + @available(*, deprecated, + message: "Extensions directly on UIButton are deprecated. Use `button.kf.setImage` instead.", + renamed: "kf.setImage") + public func kf_setImage(with resource: Resource?, + for state: UIControlState, + placeholder: UIImage? = nil, + options: KingfisherOptionsInfo? = nil, + progressBlock: DownloadProgressBlock? = nil, + completionHandler: CompletionHandler? = nil) -> RetrieveImageTask + { + return kf.setImage(with: resource, for: state, placeholder: placeholder, options: options, + progressBlock: progressBlock, completionHandler: completionHandler) + } + + /** + Cancel the image download task bounded to the image view if it is running. + Nothing will happen if the downloading has already finished. + */ + @available(*, deprecated, + message: "Extensions directly on UIButton are deprecated. Use `button.kf.cancelImageDownloadTask` instead.", + renamed: "kf.cancelImageDownloadTask") + public func kf_cancelImageDownloadTask() { kf.cancelImageDownloadTask() } + + /** + Set the background image to use for a specified state with a resource, + a placeholder image, options progress handler and completion handler. + + - parameter resource: Resource object contains information such as `cacheKey` and `downloadURL`. + - parameter state: The state that uses the specified image. + - parameter placeholder: A placeholder image when retrieving the image at URL. + - parameter options: A dictionary could control some behaviors. See `KingfisherOptionsInfo` for more. + - parameter progressBlock: Called when the image downloading progress gets updated. + - parameter completionHandler: Called when the image retrieved and set. + + - returns: A task represents the retrieving process. + + - note: Both the `progressBlock` and `completionHandler` will be invoked in main thread. + The `CallbackDispatchQueue` specified in `optionsInfo` will not be used in callbacks of this method. + */ + @discardableResult + @available(*, deprecated, + message: "Extensions directly on UIButton are deprecated. Use `button.kf.setBackgroundImage` instead.", + renamed: "kf.setBackgroundImage") + public func kf_setBackgroundImage(with resource: Resource?, + for state: UIControlState, + placeholder: UIImage? = nil, + options: KingfisherOptionsInfo? = nil, + progressBlock: DownloadProgressBlock? = nil, + completionHandler: CompletionHandler? = nil) -> RetrieveImageTask + { + return kf.setBackgroundImage(with: resource, for: state, placeholder: placeholder, options: options, + progressBlock: progressBlock, completionHandler: completionHandler) + } + + /** + Cancel the background image download task bounded to the image view if it is running. + Nothing will happen if the downloading has already finished. + */ + @available(*, deprecated, + message: "Extensions directly on UIButton are deprecated. Use `button.kf.cancelBackgroundImageDownloadTask` instead.", + renamed: "kf.cancelBackgroundImageDownloadTask") + public func kf_cancelBackgroundImageDownloadTask() { kf.cancelBackgroundImageDownloadTask() } + + /** + Get the image URL binded to this button for a specified state. + + - parameter state: The state that uses the specified image. + + - returns: Current URL for image. + */ + @available(*, deprecated, + message: "Extensions directly on UIButton are deprecated. Use `button.kf.webURL` instead.", + renamed: "kf.webURL") + public func kf_webURL(for state: UIControlState) -> URL? { return kf.webURL(for: state) } + + @available(*, deprecated, message: "Extensions directly on UIButton are deprecated.",renamed: "kf.setWebURL") + fileprivate func kf_setWebURL(_ url: URL, for state: UIControlState) { kf.setWebURL(url, for: state) } + + @available(*, deprecated, message: "Extensions directly on UIButton are deprecated.",renamed: "kf.webURLs") + fileprivate var kf_webURLs: NSMutableDictionary { return kf.webURLs } + + @available(*, deprecated, message: "Extensions directly on UIButton are deprecated.",renamed: "kf.setWebURLs") + fileprivate func kf_setWebURLs(_ URLs: NSMutableDictionary) { kf.setWebURLs(URLs) } + + @available(*, deprecated, message: "Extensions directly on UIButton are deprecated.",renamed: "kf.imageTask") + fileprivate var kf_imageTask: RetrieveImageTask? { return kf.imageTask } + + @available(*, deprecated, message: "Extensions directly on UIButton are deprecated.",renamed: "kf.setImageTask") + fileprivate func kf_setImageTask(_ task: RetrieveImageTask?) { kf.setImageTask(task) } + + /** + Get the background image URL binded to this button for a specified state. + + - parameter state: The state that uses the specified background image. + + - returns: Current URL for background image. + */ + @available(*, deprecated, + message: "Extensions directly on UIButton are deprecated. Use `button.kf.backgroundWebURL` instead.", + renamed: "kf.backgroundWebURL") + public func kf_backgroundWebURL(for state: UIControlState) -> URL? { return kf.backgroundWebURL(for: state) } + + @available(*, deprecated, + message: "Extensions directly on UIButton are deprecated.",renamed: "kf.setBackgroundWebURL") + fileprivate func kf_setBackgroundWebURL(_ url: URL, for state: UIControlState) { + kf.setBackgroundWebURL(url, for: state) + } + + @available(*, deprecated, + message: "Extensions directly on UIButton are deprecated.",renamed: "kf.backgroundWebURLs") + fileprivate var kf_backgroundWebURLs: NSMutableDictionary { return kf.backgroundWebURLs } + + @available(*, deprecated, + message: "Extensions directly on UIButton are deprecated.",renamed: "kf.setBackgroundWebURLs") + fileprivate func kf_setBackgroundWebURLs(_ URLs: NSMutableDictionary) { kf.setBackgroundWebURLs(URLs) } + + @available(*, deprecated, + message: "Extensions directly on UIButton are deprecated.",renamed: "kf.backgroundImageTask") + fileprivate var kf_backgroundImageTask: RetrieveImageTask? { return kf.backgroundImageTask } + + @available(*, deprecated, + message: "Extensions directly on UIButton are deprecated.",renamed: "kf.setBackgroundImageTask") + fileprivate func kf_setBackgroundImageTask(_ task: RetrieveImageTask?) { return kf.setBackgroundImageTask(task) } + +} diff --git a/GeneralUtils/GeneralUtils/libs/ObjectMapper/CustomDateFormatTransform.swift b/GeneralUtils/GeneralUtils/libs/ObjectMapper/CustomDateFormatTransform.swift new file mode 100644 index 0000000..3cd5c59 --- /dev/null +++ b/GeneralUtils/GeneralUtils/libs/ObjectMapper/CustomDateFormatTransform.swift @@ -0,0 +1,40 @@ +// +// CustomDateFormatTransform.swift +// ObjectMapper +// +// Created by Dan McCracken on 3/8/15. +// +// The MIT License (MIT) +// +// Copyright (c) 2014-2016 Hearst +// +// Permission is hereby granted, free of charge, to any person obtaining a copy +// of this software and associated documentation files (the "Software"), to deal +// in the Software without restriction, including without limitation the rights +// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +// copies of the Software, and to permit persons to whom the Software is +// furnished to do so, subject to the following conditions: +// +// The above copyright notice and this permission notice shall be included in +// all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN +// THE SOFTWARE. + +import Foundation + +open class CustomDateFormatTransform: DateFormatterTransform { + + public init(formatString: String) { + let formatter = DateFormatter() + formatter.locale = Locale(identifier: "en_US_POSIX") + formatter.dateFormat = formatString + + super.init(dateFormatter: formatter) + } +} diff --git a/GeneralUtils/GeneralUtils/libs/ObjectMapper/DataTransform.swift b/GeneralUtils/GeneralUtils/libs/ObjectMapper/DataTransform.swift new file mode 100644 index 0000000..d96f3d6 --- /dev/null +++ b/GeneralUtils/GeneralUtils/libs/ObjectMapper/DataTransform.swift @@ -0,0 +1,50 @@ +// +// DataTransform.swift +// ObjectMapper +// +// Created by Yagrushkin, Evgeny on 8/30/16. +// +// The MIT License (MIT) +// +// Copyright (c) 2014-2016 Hearst +// +// Permission is hereby granted, free of charge, to any person obtaining a copy +// of this software and associated documentation files (the "Software"), to deal +// in the Software without restriction, including without limitation the rights +// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +// copies of the Software, and to permit persons to whom the Software is +// furnished to do so, subject to the following conditions: +// +// The above copyright notice and this permission notice shall be included in +// all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN +// THE SOFTWARE. + +import Foundation + +open class DataTransform: TransformType { + public typealias Object = Data + public typealias JSON = String + + public init() {} + + open func transformFromJSON(_ value: Any?) -> Data? { + guard let string = value as? String else{ + return nil + } + return Data(base64Encoded: string) + } + + open func transformToJSON(_ value: Data?) -> String? { + guard let data = value else{ + return nil + } + return data.base64EncodedString() + } +} diff --git a/GeneralUtils/GeneralUtils/libs/ObjectMapper/DateFormatterTransform.swift b/GeneralUtils/GeneralUtils/libs/ObjectMapper/DateFormatterTransform.swift new file mode 100644 index 0000000..fa75f3b --- /dev/null +++ b/GeneralUtils/GeneralUtils/libs/ObjectMapper/DateFormatterTransform.swift @@ -0,0 +1,54 @@ +// +// DateFormatterTransform.swift +// ObjectMapper +// +// Created by Tristan Himmelman on 2015-03-09. +// +// The MIT License (MIT) +// +// Copyright (c) 2014-2016 Hearst +// +// Permission is hereby granted, free of charge, to any person obtaining a copy +// of this software and associated documentation files (the "Software"), to deal +// in the Software without restriction, including without limitation the rights +// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +// copies of the Software, and to permit persons to whom the Software is +// furnished to do so, subject to the following conditions: +// +// The above copyright notice and this permission notice shall be included in +// all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN +// THE SOFTWARE. + +import Foundation + +open class DateFormatterTransform: TransformType { + public typealias Object = Date + public typealias JSON = String + + public let dateFormatter: DateFormatter + + public init(dateFormatter: DateFormatter) { + self.dateFormatter = dateFormatter + } + + open func transformFromJSON(_ value: Any?) -> Date? { + if let dateString = value as? String { + return dateFormatter.date(from: dateString) + } + return nil + } + + open func transformToJSON(_ value: Date?) -> String? { + if let date = value { + return dateFormatter.string(from: date) + } + return nil + } +} diff --git a/GeneralUtils/GeneralUtils/libs/ObjectMapper/DateTransform.swift b/GeneralUtils/GeneralUtils/libs/ObjectMapper/DateTransform.swift new file mode 100644 index 0000000..2c175cb --- /dev/null +++ b/GeneralUtils/GeneralUtils/libs/ObjectMapper/DateTransform.swift @@ -0,0 +1,55 @@ +// +// DateTransform.swift +// ObjectMapper +// +// Created by Tristan Himmelman on 2014-10-13. +// +// The MIT License (MIT) +// +// Copyright (c) 2014-2016 Hearst +// +// Permission is hereby granted, free of charge, to any person obtaining a copy +// of this software and associated documentation files (the "Software"), to deal +// in the Software without restriction, including without limitation the rights +// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +// copies of the Software, and to permit persons to whom the Software is +// furnished to do so, subject to the following conditions: +// +// The above copyright notice and this permission notice shall be included in +// all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN +// THE SOFTWARE. + +import Foundation + +open class DateTransform: TransformType { + public typealias Object = Date + public typealias JSON = Double + + public init() {} + + open func transformFromJSON(_ value: Any?) -> Date? { + if let timeInt = value as? Double { + return Date(timeIntervalSince1970: TimeInterval(timeInt)) + } + + if let timeStr = value as? String { + return Date(timeIntervalSince1970: TimeInterval(atof(timeStr))) + } + + return nil + } + + open func transformToJSON(_ value: Date?) -> Double? { + if let date = value { + return Double(date.timeIntervalSince1970) + } + return nil + } +} diff --git a/GeneralUtils/GeneralUtils/libs/ObjectMapper/DictionaryTransform.swift b/GeneralUtils/GeneralUtils/libs/ObjectMapper/DictionaryTransform.swift new file mode 100644 index 0000000..e7b6ef3 --- /dev/null +++ b/GeneralUtils/GeneralUtils/libs/ObjectMapper/DictionaryTransform.swift @@ -0,0 +1,58 @@ +// +// DictionaryTransform.swift +// ObjectMapper +// +// Created by Milen Halachev on 7/20/16. +// Copyright © 2016 hearst. All rights reserved. +// + +import Foundation + +///Transforms [String: AnyObject] <-> [Key: Value] where Key is RawRepresentable as String, Value is Mappable +public struct DictionaryTransform: TransformType where Key: Hashable, Key: RawRepresentable, Key.RawValue == String, Value: Mappable { + + public init() { + + } + + public func transformFromJSON(_ value: Any?) -> [Key: Value]? { + + guard let json = value as? [String: Any] else { + + return nil + } + + let result = json.reduce([:]) { (result, element) -> [Key: Value] in + + guard + let key = Key(rawValue: element.0), + let valueJSON = element.1 as? [String: Any], + let value = Value(JSON: valueJSON) + else { + + return result + } + + var result = result + result[key] = value + return result + } + + return result + } + + public func transformToJSON(_ value: [Key: Value]?) -> Any? { + + let result = value?.reduce([:]) { (result, element) -> [String: Any] in + + let key = element.0.rawValue + let value = element.1.toJSON() + + var result = result + result[key] = value + return result + } + + return result + } +} diff --git a/GeneralUtils/GeneralUtils/libs/ObjectMapper/EnumOperators.swift b/GeneralUtils/GeneralUtils/libs/ObjectMapper/EnumOperators.swift new file mode 100644 index 0000000..5a1a667 --- /dev/null +++ b/GeneralUtils/GeneralUtils/libs/ObjectMapper/EnumOperators.swift @@ -0,0 +1,91 @@ +// +// EnumOperators.swift +// ObjectMapper +// +// Created by Tristan Himmelman on 2016-09-26. +// Copyright © 2016 hearst. All rights reserved. +// + +import Foundation + + +// MARK:- Raw Representable types + +/// Object of Raw Representable type +public func <- (left: inout T, right: Map) { + left <- (right, EnumTransform()) +} + +public func >>> (left: T, right: Map) { + left >>> (right, EnumTransform()) +} + + +/// Optional Object of Raw Representable type +public func <- (left: inout T?, right: Map) { + left <- (right, EnumTransform()) +} + +public func >>> (left: T?, right: Map) { + left >>> (right, EnumTransform()) +} + + +/// Implicitly Unwrapped Optional Object of Raw Representable type +public func <- (left: inout T!, right: Map) { + left <- (right, EnumTransform()) +} + +// MARK:- Arrays of Raw Representable type + +/// Array of Raw Representable object +public func <- (left: inout [T], right: Map) { + left <- (right, EnumTransform()) +} + +public func >>> (left: [T], right: Map) { + left >>> (right, EnumTransform()) +} + + +/// Array of Raw Representable object +public func <- (left: inout [T]?, right: Map) { + left <- (right, EnumTransform()) +} + +public func >>> (left: [T]?, right: Map) { + left >>> (right, EnumTransform()) +} + + +/// Array of Raw Representable object +public func <- (left: inout [T]!, right: Map) { + left <- (right, EnumTransform()) +} + +// MARK:- Dictionaries of Raw Representable type + +/// Dictionary of Raw Representable object +public func <- (left: inout [String: T], right: Map) { + left <- (right, EnumTransform()) +} + +public func >>> (left: [String: T], right: Map) { + left >>> (right, EnumTransform()) +} + + +/// Dictionary of Raw Representable object +public func <- (left: inout [String: T]?, right: Map) { + left <- (right, EnumTransform()) +} + +public func >>> (left: [String: T]?, right: Map) { + left >>> (right, EnumTransform()) +} + + +/// Dictionary of Raw Representable object +public func <- (left: inout [String: T]!, right: Map) { + left <- (right, EnumTransform()) +} diff --git a/GeneralUtils/GeneralUtils/libs/ObjectMapper/EnumTransform.swift b/GeneralUtils/GeneralUtils/libs/ObjectMapper/EnumTransform.swift new file mode 100644 index 0000000..43e4ce7 --- /dev/null +++ b/GeneralUtils/GeneralUtils/libs/ObjectMapper/EnumTransform.swift @@ -0,0 +1,50 @@ +// +// EnumTransform.swift +// ObjectMapper +// +// Created by Kaan Dedeoglu on 3/20/15. +// +// The MIT License (MIT) +// +// Copyright (c) 2014-2016 Hearst +// +// Permission is hereby granted, free of charge, to any person obtaining a copy +// of this software and associated documentation files (the "Software"), to deal +// in the Software without restriction, including without limitation the rights +// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +// copies of the Software, and to permit persons to whom the Software is +// furnished to do so, subject to the following conditions: +// +// The above copyright notice and this permission notice shall be included in +// all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN +// THE SOFTWARE. + +import Foundation + +open class EnumTransform: TransformType { + public typealias Object = T + public typealias JSON = T.RawValue + + public init() {} + + open func transformFromJSON(_ value: Any?) -> T? { + if let raw = value as? T.RawValue { + return T(rawValue: raw) + } + return nil + } + + open func transformToJSON(_ value: T?) -> T.RawValue? { + if let obj = value { + return obj.rawValue + } + return nil + } +} diff --git a/GeneralUtils/GeneralUtils/libs/ObjectMapper/FromJSON.swift b/GeneralUtils/GeneralUtils/libs/ObjectMapper/FromJSON.swift new file mode 100644 index 0000000..7cb4655 --- /dev/null +++ b/GeneralUtils/GeneralUtils/libs/ObjectMapper/FromJSON.swift @@ -0,0 +1,181 @@ +// +// FromJSON.swift +// ObjectMapper +// +// Created by Tristan Himmelman on 2014-10-09. +// +// The MIT License (MIT) +// +// Copyright (c) 2014-2016 Hearst +// +// Permission is hereby granted, free of charge, to any person obtaining a copy +// of this software and associated documentation files (the "Software"), to deal +// in the Software without restriction, including without limitation the rights +// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +// copies of the Software, and to permit persons to whom the Software is +// furnished to do so, subject to the following conditions: +// +// The above copyright notice and this permission notice shall be included in +// all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN +// THE SOFTWARE. + +internal final class FromJSON { + + /// Basic type + class func basicType(_ field: inout FieldType, object: FieldType?) { + if let value = object { + field = value + } + } + + /// optional basic type + class func optionalBasicType(_ field: inout FieldType?, object: FieldType?) { + field = object + } + + /// Implicitly unwrapped optional basic type + class func optionalBasicType(_ field: inout FieldType!, object: FieldType?) { + field = object + } + + /// Mappable object + class func object(_ field: inout N, map: Map) { + if map.toObject { + _ = Mapper(context: map.context).map(JSONObject: map.currentValue, toObject: field) + } else if let value: N = Mapper(context: map.context).map(JSONObject: map.currentValue) { + field = value + } + } + + /// Optional Mappable Object + + class func optionalObject(_ field: inout N?, map: Map) { + if let field = field , map.toObject && map.currentValue != nil { + _ = Mapper(context: map.context).map(JSONObject: map.currentValue, toObject: field) + } else { + field = Mapper(context: map.context).map(JSONObject: map.currentValue) + } + } + + /// Implicitly unwrapped Optional Mappable Object + class func optionalObject(_ field: inout N!, map: Map) { + if let field = field , map.toObject && map.currentValue != nil { + _ = Mapper(context: map.context).map(JSONObject: map.currentValue, toObject: field) + } else { + field = Mapper(context: map.context).map(JSONObject: map.currentValue) + } + } + + /// mappable object array + class func objectArray(_ field: inout Array, map: Map) { + if let objects = Mapper(context: map.context).mapArray(JSONObject: map.currentValue) { + field = objects + } + } + + /// optional mappable object array + + class func optionalObjectArray(_ field: inout Array?, map: Map) { + if let objects: Array = Mapper(context: map.context).mapArray(JSONObject: map.currentValue) { + field = objects + } else { + field = nil + } + } + + /// Implicitly unwrapped optional mappable object array + class func optionalObjectArray(_ field: inout Array!, map: Map) { + if let objects: Array = Mapper(context: map.context).mapArray(JSONObject: map.currentValue) { + field = objects + } else { + field = nil + } + } + + /// mappable object array + class func twoDimensionalObjectArray(_ field: inout Array>, map: Map) { + if let objects = Mapper(context: map.context).mapArrayOfArrays(JSONObject: map.currentValue) { + field = objects + } + } + + /// optional mappable 2 dimentional object array + class func optionalTwoDimensionalObjectArray(_ field: inout Array>?, map: Map) { + field = Mapper(context: map.context).mapArrayOfArrays(JSONObject: map.currentValue) + } + + /// Implicitly unwrapped optional 2 dimentional mappable object array + class func optionalTwoDimensionalObjectArray(_ field: inout Array>!, map: Map) { + field = Mapper(context: map.context).mapArrayOfArrays(JSONObject: map.currentValue) + } + + /// Dctionary containing Mappable objects + class func objectDictionary(_ field: inout Dictionary, map: Map) { + if map.toObject { + _ = Mapper(context: map.context).mapDictionary(JSONObject: map.currentValue, toDictionary: field) + } else { + if let objects = Mapper(context: map.context).mapDictionary(JSONObject: map.currentValue) { + field = objects + } + } + } + + /// Optional dictionary containing Mappable objects + class func optionalObjectDictionary(_ field: inout Dictionary?, map: Map) { + if let field = field , map.toObject && map.currentValue != nil { + _ = Mapper(context: map.context).mapDictionary(JSONObject: map.currentValue, toDictionary: field) + } else { + field = Mapper(context: map.context).mapDictionary(JSONObject: map.currentValue) + } + } + + /// Implicitly unwrapped Dictionary containing Mappable objects + class func optionalObjectDictionary(_ field: inout Dictionary!, map: Map) { + if let field = field , map.toObject && map.currentValue != nil { + _ = Mapper(context: map.context).mapDictionary(JSONObject: map.currentValue, toDictionary: field) + } else { + field = Mapper(context: map.context).mapDictionary(JSONObject: map.currentValue) + } + } + + /// Dictionary containing Array of Mappable objects + class func objectDictionaryOfArrays(_ field: inout Dictionary, map: Map) { + if let objects = Mapper(context: map.context).mapDictionaryOfArrays(JSONObject: map.currentValue) { + field = objects + } + } + + /// Optional Dictionary containing Array of Mappable objects + class func optionalObjectDictionaryOfArrays(_ field: inout Dictionary?, map: Map) { + field = Mapper(context: map.context).mapDictionaryOfArrays(JSONObject: map.currentValue) + } + + /// Implicitly unwrapped Dictionary containing Array of Mappable objects + class func optionalObjectDictionaryOfArrays(_ field: inout Dictionary!, map: Map) { + field = Mapper(context: map.context).mapDictionaryOfArrays(JSONObject: map.currentValue) + } + + /// mappable object Set + class func objectSet(_ field: inout Set, map: Map) { + if let objects = Mapper(context: map.context).mapSet(JSONObject: map.currentValue) { + field = objects + } + } + + /// optional mappable object array + class func optionalObjectSet(_ field: inout Set?, map: Map) { + field = Mapper(context: map.context).mapSet(JSONObject: map.currentValue) + } + + /// Implicitly unwrapped optional mappable object array + class func optionalObjectSet(_ field: inout Set!, map: Map) { + field = Mapper(context: map.context).mapSet(JSONObject: map.currentValue) + } +} diff --git a/GeneralUtils/GeneralUtils/libs/ObjectMapper/HexColorTransform.swift b/GeneralUtils/GeneralUtils/libs/ObjectMapper/HexColorTransform.swift new file mode 100644 index 0000000..e2eb979 --- /dev/null +++ b/GeneralUtils/GeneralUtils/libs/ObjectMapper/HexColorTransform.swift @@ -0,0 +1,115 @@ +// +// HexColorTransform.swift +// ObjectMapper +// +// Created by Vitaliy Kuzmenko on 10/10/16. +// Copyright © 2016 hearst. All rights reserved. +// + +#if os(iOS) || os(tvOS) || os(watchOS) +import UIKit +#else +import Cocoa +#endif + +open class HexColorTransform: TransformType { + + #if os(iOS) || os(tvOS) || os(watchOS) + public typealias Object = UIColor + #else + public typealias Object = NSColor + #endif + + public typealias JSON = String + + var prefix: Bool = false + + var alpha: Bool = false + + public init(prefixToJSON: Bool = false, alphaToJSON: Bool = false) { + alpha = alphaToJSON + prefix = prefixToJSON + } + + open func transformFromJSON(_ value: Any?) -> Object? { + if let rgba = value as? String { + if rgba.hasPrefix("#") { + let index = rgba.characters.index(rgba.startIndex, offsetBy: 1) + let hex = rgba.substring(from: index) + return getColor(hex: hex) + } else { + return getColor(hex: rgba) + } + } + return nil + } + + open func transformToJSON(_ value: Object?) -> JSON? { + if let value = value { + return hexString(color: value) + } + return nil + } + + fileprivate func hexString(color: Object) -> String { + let comps = color.cgColor.components! + let r = Int(comps[0] * 255) + let g = Int(comps[1] * 255) + let b = Int(comps[2] * 255) + let a = Int(comps[3] * 255) + var hexString: String = "" + if prefix { + hexString = "#" + } + hexString += String(format: "%02X%02X%02X", r, g, b) + + if alpha { + hexString += String(format: "%02X", a) + } + return hexString + } + + fileprivate func getColor(hex: String) -> Object? { + var red: CGFloat = 0.0 + var green: CGFloat = 0.0 + var blue: CGFloat = 0.0 + var alpha: CGFloat = 1.0 + + let scanner = Scanner(string: hex) + var hexValue: CUnsignedLongLong = 0 + if scanner.scanHexInt64(&hexValue) { + switch (hex.characters.count) { + case 3: + red = CGFloat((hexValue & 0xF00) >> 8) / 15.0 + green = CGFloat((hexValue & 0x0F0) >> 4) / 15.0 + blue = CGFloat(hexValue & 0x00F) / 15.0 + case 4: + red = CGFloat((hexValue & 0xF000) >> 12) / 15.0 + green = CGFloat((hexValue & 0x0F00) >> 8) / 15.0 + blue = CGFloat((hexValue & 0x00F0) >> 4) / 15.0 + alpha = CGFloat(hexValue & 0x000F) / 15.0 + case 6: + red = CGFloat((hexValue & 0xFF0000) >> 16) / 255.0 + green = CGFloat((hexValue & 0x00FF00) >> 8) / 255.0 + blue = CGFloat(hexValue & 0x0000FF) / 255.0 + case 8: + red = CGFloat((hexValue & 0xFF000000) >> 24) / 255.0 + green = CGFloat((hexValue & 0x00FF0000) >> 16) / 255.0 + blue = CGFloat((hexValue & 0x0000FF00) >> 8) / 255.0 + alpha = CGFloat(hexValue & 0x000000FF) / 255.0 + default: + // Invalid RGB string, number of characters after '#' should be either 3, 4, 6 or 8 + return nil + } + } else { + // "Scan hex error + return nil + } + #if os(iOS) || os(tvOS) || os(watchOS) + return UIColor(red: red, green: green, blue: blue, alpha: alpha) + #else + return NSColor(calibratedRed: red, green: green, blue: blue, alpha: alpha) + #endif + } +} + diff --git a/GeneralUtils/GeneralUtils/libs/ObjectMapper/ISO8601DateTransform.swift b/GeneralUtils/GeneralUtils/libs/ObjectMapper/ISO8601DateTransform.swift new file mode 100644 index 0000000..5a17b73 --- /dev/null +++ b/GeneralUtils/GeneralUtils/libs/ObjectMapper/ISO8601DateTransform.swift @@ -0,0 +1,41 @@ +// +// ISO8601DateTransform.swift +// ObjectMapper +// +// Created by Jean-Pierre Mouilleseaux on 21 Nov 2014. +// +// The MIT License (MIT) +// +// Copyright (c) 2014-2016 Hearst +// +// Permission is hereby granted, free of charge, to any person obtaining a copy +// of this software and associated documentation files (the "Software"), to deal +// in the Software without restriction, including without limitation the rights +// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +// copies of the Software, and to permit persons to whom the Software is +// furnished to do so, subject to the following conditions: +// +// The above copyright notice and this permission notice shall be included in +// all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN +// THE SOFTWARE. + +import Foundation + +open class ISO8601DateTransform: DateFormatterTransform { + + public init() { + let formatter = DateFormatter() + formatter.locale = Locale(identifier: "en_US_POSIX") + formatter.dateFormat = "yyyy-MM-dd'T'HH:mm:ssZZZZZ" + + super.init(dateFormatter: formatter) + } + +} diff --git a/GeneralUtils/GeneralUtils/libs/ObjectMapper/ImmutableMappable.swift b/GeneralUtils/GeneralUtils/libs/ObjectMapper/ImmutableMappable.swift new file mode 100644 index 0000000..ae99179 --- /dev/null +++ b/GeneralUtils/GeneralUtils/libs/ObjectMapper/ImmutableMappable.swift @@ -0,0 +1,275 @@ +// +// ImmutableMappble.swift +// ObjectMapper +// +// Created by Suyeol Jeon on 23/09/2016. +// +// The MIT License (MIT) +// +// Copyright (c) 2014-2016 Hearst +// +// Permission is hereby granted, free of charge, to any person obtaining a copy +// of this software and associated documentation files (the "Software"), to deal +// in the Software without restriction, including without limitation the rights +// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +// copies of the Software, and to permit persons to whom the Software is +// furnished to do so, subject to the following conditions: +// +// The above copyright notice and this permission notice shall be included in +// all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN +// THE SOFTWARE. + +public protocol ImmutableMappable: BaseMappable { + init(map: Map) throws +} + +public extension ImmutableMappable { + + /// Implement this method to support object -> JSON transform. + public func mapping(map: Map) {} + + /// Initializes object from a JSON String + public init(JSONString: String, context: MapContext? = nil) throws { + self = try Mapper(context: context).map(JSONString: JSONString) + } + + /// Initializes object from a JSON Dictionary + public init(JSON: [String: Any], context: MapContext? = nil) throws { + self = try Mapper(context: context).map(JSON: JSON) + } + + /// Initializes object from a JSONObject + public init(JSONObject: Any, context: MapContext? = nil) throws { + self = try Mapper(context: context).map(JSONObject: JSONObject) + } + +} + +public extension Map { + + fileprivate func currentValue(for key: String, nested: Bool? = nil, delimiter: String = ".") -> Any? { + let isNested = nested ?? key.contains(delimiter) + return self[key, nested: isNested, delimiter: delimiter].currentValue + } + + // MARK: Basic + + /// Returns a value or throws an error. + public func value(_ key: String, nested: Bool? = nil, delimiter: String = ".", file: StaticString = #file, function: StaticString = #function, line: UInt = #line) throws -> T { + let currentValue = self.currentValue(for: key, nested: nested, delimiter: delimiter) + guard let value = currentValue as? T else { + throw MapError(key: key, currentValue: currentValue, reason: "Cannot cast to '\(T.self)'", file: file, function: function, line: line) + } + return value + } + + /// Returns a transformed value or throws an error. + public func value(_ key: String, nested: Bool? = nil, delimiter: String = ".", using transform: Transform, file: StaticString = #file, function: StaticString = #function, line: UInt = #line) throws -> Transform.Object { + let currentValue = self.currentValue(for: key, nested: nested, delimiter: delimiter) + guard let value = transform.transformFromJSON(currentValue) else { + throw MapError(key: key, currentValue: currentValue, reason: "Cannot transform to '\(Transform.Object.self)' using \(transform)", file: file, function: function, line: line) + } + return value + } + + /// Returns a RawRepresentable type or throws an error. + public func value(_ key: String, nested: Bool? = nil, delimiter: String = ".", file: StaticString = #file, function: StaticString = #function, line: UInt = #line) throws -> T { + return try self.value(key, nested: nested, delimiter: delimiter, using: EnumTransform(), file: file, function: function, line: line) + } + + // MARK: BaseMappable + + /// Returns a `BaseMappable` object or throws an error. + public func value(_ key: String, nested: Bool? = nil, delimiter: String = ".", file: StaticString = #file, function: StaticString = #function, line: UInt = #line) throws -> T { + let currentValue = self.currentValue(for: key, nested: nested, delimiter: delimiter) + guard let JSONObject = currentValue else { + throw MapError(key: key, currentValue: currentValue, reason: "Found unexpected nil value", file: file, function: function, line: line) + } + return try Mapper(context: context).mapOrFail(JSONObject: JSONObject) + } + + // MARK: [BaseMappable] + + /// Returns a `[BaseMappable]` or throws an error. + public func value(_ key: String, nested: Bool? = nil, delimiter: String = ".", file: StaticString = #file, function: StaticString = #function, line: UInt = #line) throws -> [T] { + let currentValue = self.currentValue(for: key, nested: nested, delimiter: delimiter) + guard let jsonArray = currentValue as? [Any] else { + throw MapError(key: key, currentValue: currentValue, reason: "Cannot cast to '[Any]'", file: file, function: function, line: line) + } + return try jsonArray.enumerated().map { i, JSONObject -> T in + return try Mapper(context: context).mapOrFail(JSONObject: JSONObject) + } + } + + /// Returns a `[BaseMappable]` using transform or throws an error. + public func value(_ key: String, nested: Bool? = nil, delimiter: String = ".", using transform: Transform, file: StaticString = #file, function: StaticString = #function, line: UInt = #line) throws -> [Transform.Object] { + let currentValue = self.currentValue(for: key, nested: nested, delimiter: delimiter) + guard let jsonArray = currentValue as? [Any] else { + throw MapError(key: key, currentValue: currentValue, reason: "Cannot cast to '[Any]'", file: file, function: function, line: line) + } + return try jsonArray.enumerated().map { i, json -> Transform.Object in + guard let object = transform.transformFromJSON(json) else { + throw MapError(key: "\(key)[\(i)]", currentValue: json, reason: "Cannot transform to '\(Transform.Object.self)' using \(transform)", file: file, function: function, line: line) + } + return object + } + } + + // MARK: [String: BaseMappable] + + /// Returns a `[String: BaseMappable]` or throws an error. + public func value(_ key: String, nested: Bool? = nil, delimiter: String = ".", file: StaticString = #file, function: StaticString = #function, line: UInt = #line) throws -> [String: T] { + let currentValue = self.currentValue(for: key, nested: nested, delimiter: delimiter) + guard let jsonDictionary = currentValue as? [String: Any] else { + throw MapError(key: key, currentValue: currentValue, reason: "Cannot cast to '[String: Any]'", file: file, function: function, line: line) + } + var value: [String: T] = [:] + for (key, json) in jsonDictionary { + value[key] = try Mapper(context: context).mapOrFail(JSONObject: json) + } + return value + } + + /// Returns a `[String: BaseMappable]` using transform or throws an error. + public func value(_ key: String, nested: Bool? = nil, delimiter: String = ".", using transform: Transform, file: StaticString = #file, function: StaticString = #function, line: UInt = #line) throws -> [String: Transform.Object] { + let currentValue = self.currentValue(for: key, nested: nested, delimiter: delimiter) + guard let jsonDictionary = currentValue as? [String: Any] else { + throw MapError(key: key, currentValue: currentValue, reason: "Cannot cast to '[String: Any]'", file: file, function: function, line: line) + } + var value: [String: Transform.Object] = [:] + for (key, json) in jsonDictionary { + guard let object = transform.transformFromJSON(json) else { + throw MapError(key: key, currentValue: json, reason: "Cannot transform to '\(Transform.Object.self)' using \(transform)", file: file, function: function, line: line) + } + value[key] = object + } + return value + } + +} + +public extension Mapper where N: ImmutableMappable { + + public func map(JSON: [String: Any]) throws -> N { + return try self.mapOrFail(JSON: JSON) + } + + public func map(JSONString: String) throws -> N { + return try mapOrFail(JSONString: JSONString) + } + + public func map(JSONObject: Any) throws -> N { + return try mapOrFail(JSONObject: JSONObject) + } + + // MARK: Array mapping functions + + public func mapArray(JSONArray: [[String: Any]]) throws -> [N] { + return try JSONArray.flatMap(mapOrFail) + } + + public func mapArray(JSONString: String) throws -> [N] { + guard let JSONObject = Mapper.parseJSONString(JSONString: JSONString) else { + throw MapError(key: nil, currentValue: JSONString, reason: "Cannot convert string into Any'") + } + + return try mapArray(JSONObject: JSONObject) + } + + public func mapArray(JSONObject: Any) throws -> [N] { + guard let JSONArray = JSONObject as? [[String: Any]] else { + throw MapError(key: nil, currentValue: JSONObject, reason: "Cannot cast to '[[String: Any]]'") + } + + return try mapArray(JSONArray: JSONArray) + } + + // MARK: Dictionary mapping functions + + public func mapDictionary(JSONString: String) throws -> [String: N] { + guard let JSONObject = Mapper.parseJSONString(JSONString: JSONString) else { + throw MapError(key: nil, currentValue: JSONString, reason: "Cannot convert string into Any'") + } + + return try mapDictionary(JSONObject: JSONObject) + } + + public func mapDictionary(JSONObject: Any?) throws -> [String: N] { + guard let JSON = JSONObject as? [String: [String: Any]] else { + throw MapError(key: nil, currentValue: JSONObject, reason: "Cannot cast to '[String: [String: Any]]''") + } + + return try mapDictionary(JSON: JSON) + } + + public func mapDictionary(JSON: [String: [String: Any]]) throws -> [String: N] { + return try JSON.filterMap(mapOrFail) + } + + // MARK: Dictinoary of arrays mapping functions + + public func mapDictionaryOfArrays(JSONObject: Any?) throws -> [String: [N]] { + guard let JSON = JSONObject as? [String: [[String: Any]]] else { + throw MapError(key: nil, currentValue: JSONObject, reason: "Cannot cast to '[String: [String: Any]]''") + } + return try mapDictionaryOfArrays(JSON: JSON) + } + + public func mapDictionaryOfArrays(JSON: [String: [[String: Any]]]) throws -> [String: [N]] { + return try JSON.filterMap { array -> [N] in + try mapArray(JSONArray: array) + } + } + + // MARK: 2 dimentional array mapping functions + + public func mapArrayOfArrays(JSONObject: Any?) throws -> [[N]] { + guard let JSONArray = JSONObject as? [[[String: Any]]] else { + throw MapError(key: nil, currentValue: JSONObject, reason: "Cannot cast to '[[[String: Any]]]''") + } + return try JSONArray.map(mapArray) + } + +} + +internal extension Mapper where N: BaseMappable { + + internal func mapOrFail(JSON: [String: Any]) throws -> N { + let map = Map(mappingType: .fromJSON, JSON: JSON, context: context, shouldIncludeNilValues: shouldIncludeNilValues) + + // Check if object is ImmutableMappable, if so use ImmutableMappable protocol for mapping + if let klass = N.self as? ImmutableMappable.Type, + var object = try klass.init(map: map) as? N { + object.mapping(map: map) + return object + } + + // If not, map the object the standard way + guard let value = self.map(JSON: JSON) else { + throw MapError(key: nil, currentValue: JSON, reason: "Cannot map to '\(N.self)'") + } + return value + } + + internal func mapOrFail(JSONString: String) throws -> N { + guard let JSON = Mapper.parseJSONStringIntoDictionary(JSONString: JSONString) else { + throw MapError(key: nil, currentValue: JSONString, reason: "Cannot parse into '[String: Any]'") + } + return try mapOrFail(JSON: JSON) + } + + internal func mapOrFail(JSONObject: Any) throws -> N { + guard let JSON = JSONObject as? [String: Any] else { + throw MapError(key: nil, currentValue: JSONObject, reason: "Cannot cast to '[String: Any]'") + } + return try mapOrFail(JSON: JSON) + } + +} diff --git a/GeneralUtils/GeneralUtils/libs/ObjectMapper/Map.swift b/GeneralUtils/GeneralUtils/libs/ObjectMapper/Map.swift new file mode 100644 index 0000000..22f87b5 --- /dev/null +++ b/GeneralUtils/GeneralUtils/libs/ObjectMapper/Map.swift @@ -0,0 +1,181 @@ +// +// Map.swift +// ObjectMapper +// +// Created by Tristan Himmelman on 2015-10-09. +// +// The MIT License (MIT) +// +// Copyright (c) 2014-2016 Hearst +// +// Permission is hereby granted, free of charge, to any person obtaining a copy +// of this software and associated documentation files (the "Software"), to deal +// in the Software without restriction, including without limitation the rights +// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +// copies of the Software, and to permit persons to whom the Software is +// furnished to do so, subject to the following conditions: +// +// The above copyright notice and this permission notice shall be included in +// all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN +// THE SOFTWARE. + + +import Foundation + +/// MapContext is available for developers who wish to pass information around during the mapping process. +public protocol MapContext { + +} + +/// A class used for holding mapping data +public final class Map { + public let mappingType: MappingType + + public internal(set) var JSON: [String: Any] = [:] + public internal(set) var isKeyPresent = false + public internal(set) var currentValue: Any? + public internal(set) var currentKey: String? + var keyIsNested = false + public internal(set) var nestedKeyDelimiter: String = "." + public var context: MapContext? + public var shouldIncludeNilValues = false /// If this is set to true, toJSON output will include null values for any variables that are not set. + + let toObject: Bool // indicates whether the mapping is being applied to an existing object + + public init(mappingType: MappingType, JSON: [String: Any], toObject: Bool = false, context: MapContext? = nil, shouldIncludeNilValues: Bool = false) { + + self.mappingType = mappingType + self.JSON = JSON + self.toObject = toObject + self.context = context + self.shouldIncludeNilValues = shouldIncludeNilValues + } + + /// Sets the current mapper value and key. + /// The Key paramater can be a period separated string (ex. "distance.value") to access sub objects. + public subscript(key: String) -> Map { + // save key and value associated to it + return self[key, delimiter: ".", ignoreNil: false] + } + + public subscript(key: String, delimiter delimiter: String) -> Map { + let nested = key.contains(delimiter) + return self[key, nested: nested, delimiter: delimiter, ignoreNil: false] + } + + public subscript(key: String, nested nested: Bool) -> Map { + return self[key, nested: nested, delimiter: ".", ignoreNil: false] + } + + public subscript(key: String, nested nested: Bool, delimiter delimiter: String) -> Map { + return self[key, nested: nested, delimiter: delimiter, ignoreNil: false] + } + + public subscript(key: String, ignoreNil ignoreNil: Bool) -> Map { + return self[key, delimiter: ".", ignoreNil: ignoreNil] + } + + public subscript(key: String, delimiter delimiter: String, ignoreNil ignoreNil: Bool) -> Map { + let nested = key.contains(delimiter) + return self[key, nested: nested, delimiter: delimiter, ignoreNil: ignoreNil] + } + + public subscript(key: String, nested nested: Bool, ignoreNil ignoreNil: Bool) -> Map { + return self[key, nested: nested, delimiter: ".", ignoreNil: ignoreNil] + } + + public subscript(key: String, nested nested: Bool, delimiter delimiter: String, ignoreNil ignoreNil: Bool) -> Map { + // save key and value associated to it + currentKey = key + keyIsNested = nested + nestedKeyDelimiter = delimiter + + if mappingType == .fromJSON { + // check if a value exists for the current key + // do this pre-check for performance reasons + if nested == false { + let object = JSON[key] + let isNSNull = object is NSNull + isKeyPresent = isNSNull ? true : object != nil + currentValue = isNSNull ? nil : object + } else { + // break down the components of the key that are separated by . + (isKeyPresent, currentValue) = valueFor(ArraySlice(key.components(separatedBy: delimiter)), dictionary: JSON) + } + + // update isKeyPresent if ignoreNil is true + if ignoreNil && currentValue == nil { + isKeyPresent = false + } + } + + return self + } + + public func value() -> T? { + return currentValue as? T + } + +} + +/// Fetch value from JSON dictionary, loop through keyPathComponents until we reach the desired object +private func valueFor(_ keyPathComponents: ArraySlice, dictionary: [String: Any]) -> (Bool, Any?) { + // Implement it as a tail recursive function. + if keyPathComponents.isEmpty { + return (false, nil) + } + + if let keyPath = keyPathComponents.first { + let object = dictionary[keyPath] + if object is NSNull { + return (true, nil) + } else if keyPathComponents.count > 1, let dict = object as? [String: Any] { + let tail = keyPathComponents.dropFirst() + return valueFor(tail, dictionary: dict) + } else if keyPathComponents.count > 1, let array = object as? [Any] { + let tail = keyPathComponents.dropFirst() + return valueFor(tail, array: array) + } else { + return (object != nil, object) + } + } + + return (false, nil) +} + +/// Fetch value from JSON Array, loop through keyPathComponents them until we reach the desired object +private func valueFor(_ keyPathComponents: ArraySlice, array: [Any]) -> (Bool, Any?) { + // Implement it as a tail recursive function. + + if keyPathComponents.isEmpty { + return (false, nil) + } + + //Try to convert keypath to Int as index + if let keyPath = keyPathComponents.first, + let index = Int(keyPath) , index >= 0 && index < array.count { + + let object = array[index] + + if object is NSNull { + return (true, nil) + } else if keyPathComponents.count > 1, let array = object as? [Any] { + let tail = keyPathComponents.dropFirst() + return valueFor(tail, array: array) + } else if keyPathComponents.count > 1, let dict = object as? [String: Any] { + let tail = keyPathComponents.dropFirst() + return valueFor(tail, dictionary: dict) + } else { + return (true, object) + } + } + + return (false, nil) +} diff --git a/GeneralUtils/GeneralUtils/libs/ObjectMapper/MapError.swift b/GeneralUtils/GeneralUtils/libs/ObjectMapper/MapError.swift new file mode 100644 index 0000000..21e20cb --- /dev/null +++ b/GeneralUtils/GeneralUtils/libs/ObjectMapper/MapError.swift @@ -0,0 +1,68 @@ +// +// MapError.swift +// ObjectMapper +// +// Created by Tristan Himmelman on 2016-09-26. +// +// The MIT License (MIT) +// +// Copyright (c) 2014-2016 Hearst +// +// Permission is hereby granted, free of charge, to any person obtaining a copy +// of this software and associated documentation files (the "Software"), to deal +// in the Software without restriction, including without limitation the rights +// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +// copies of the Software, and to permit persons to whom the Software is +// furnished to do so, subject to the following conditions: +// +// The above copyright notice and this permission notice shall be included in +// all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN +// THE SOFTWARE. + +import Foundation + +public struct MapError: Error { + public var key: String? + public var currentValue: Any? + public var reason: String? + public var file: StaticString? + public var function: StaticString? + public var line: UInt? + + public init(key: String?, currentValue: Any?, reason: String?, file: StaticString? = nil, function: StaticString? = nil, line: UInt? = nil) { + self.key = key + self.currentValue = currentValue + self.reason = reason + self.file = file + self.function = function + self.line = line + } +} + +extension MapError: CustomStringConvertible { + + private var location: String? { + guard let file = file, let function = function, let line = line else { return nil } + let fileName = ((String(describing: file).components(separatedBy: "/").last ?? "").components(separatedBy: ".").first ?? "") + return "\(fileName).\(function):\(line)" + } + + public var description: String { + let info: [(String, Any?)] = [ + ("- reason", reason), + ("- location", location), + ("- key", key), + ("- currentValue", currentValue), + ] + let infoString = info.map { "\($0): \($1 ?? "nil")" }.joined(separator: "\n") + return "Got an error while mapping.\n\(infoString)" + } + +} diff --git a/GeneralUtils/GeneralUtils/libs/ObjectMapper/Mappable.swift b/GeneralUtils/GeneralUtils/libs/ObjectMapper/Mappable.swift new file mode 100644 index 0000000..f8abb92 --- /dev/null +++ b/GeneralUtils/GeneralUtils/libs/ObjectMapper/Mappable.swift @@ -0,0 +1,139 @@ +// +// Mappable.swift +// ObjectMapper +// +// Created by Scott Hoyt on 10/25/15. +// +// The MIT License (MIT) +// +// Copyright (c) 2014-2016 Hearst +// +// Permission is hereby granted, free of charge, to any person obtaining a copy +// of this software and associated documentation files (the "Software"), to deal +// in the Software without restriction, including without limitation the rights +// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +// copies of the Software, and to permit persons to whom the Software is +// furnished to do so, subject to the following conditions: +// +// The above copyright notice and this permission notice shall be included in +// all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN +// THE SOFTWARE. + +import Foundation + +/// BaseMappable should not be implemented directly. Mappable or StaticMappable should be used instead +public protocol BaseMappable { + /// This function is where all variable mappings should occur. It is executed by Mapper during the mapping (serialization and deserialization) process. + mutating func mapping(map: Map) +} + +public protocol Mappable: BaseMappable { + /// This function can be used to validate JSON prior to mapping. Return nil to cancel mapping at this point + init?(map: Map) +} + +public protocol StaticMappable: BaseMappable { + /// This is function that can be used to: + /// 1) provide an existing cached object to be used for mapping + /// 2) return an object of another class (which conforms to BaseMappable) to be used for mapping. For instance, you may inspect the JSON to infer the type of object that should be used for any given mapping + static func objectForMapping(map: Map) -> BaseMappable? +} + +public extension BaseMappable { + + /// Initializes object from a JSON String + public init?(JSONString: String, context: MapContext? = nil) { + if let obj: Self = Mapper(context: context).map(JSONString: JSONString) { + self = obj + } else { + return nil + } + } + + /// Initializes object from a JSON Dictionary + public init?(JSON: [String: Any], context: MapContext? = nil) { + if let obj: Self = Mapper(context: context).map(JSON: JSON) { + self = obj + } else { + return nil + } + } + + /// Returns the JSON Dictionary for the object + public func toJSON() -> [String: Any] { + return Mapper().toJSON(self) + } + + /// Returns the JSON String for the object + public func toJSONString(prettyPrint: Bool = false) -> String? { + return Mapper().toJSONString(self, prettyPrint: prettyPrint) + } +} + +public extension Array where Element: BaseMappable { + + /// Initialize Array from a JSON String + public init?(JSONString: String, context: MapContext? = nil) { + if let obj: [Element] = Mapper(context: context).mapArray(JSONString: JSONString) { + self = obj + } else { + return nil + } + } + + /// Initialize Array from a JSON Array + public init?(JSONArray: [[String: Any]], context: MapContext? = nil) { + if let obj: [Element] = Mapper(context: context).mapArray(JSONArray: JSONArray) { + self = obj + } else { + return nil + } + } + + /// Returns the JSON Array + public func toJSON() -> [[String: Any]] { + return Mapper().toJSONArray(self) + } + + /// Returns the JSON String for the object + public func toJSONString(prettyPrint: Bool = false) -> String? { + return Mapper().toJSONString(self, prettyPrint: prettyPrint) + } +} + +public extension Set where Element: BaseMappable { + + /// Initializes a set from a JSON String + public init?(JSONString: String, context: MapContext? = nil) { + if let obj: Set = Mapper(context: context).mapSet(JSONString: JSONString) { + self = obj + } else { + return nil + } + } + + /// Initializes a set from JSON + public init?(JSONArray: [[String: Any]], context: MapContext? = nil) { + guard let obj = Mapper(context: context).mapSet(JSONArray: JSONArray) as Set? else { + return nil + } + self = obj + } + + /// Returns the JSON Set + public func toJSON() -> [[String: Any]] { + return Mapper().toJSONSet(self) + } + + /// Returns the JSON String for the object + public func toJSONString(prettyPrint: Bool = false) -> String? { + return Mapper().toJSONString(self, prettyPrint: prettyPrint) + } +} diff --git a/GeneralUtils/GeneralUtils/libs/ObjectMapper/Mapper.swift b/GeneralUtils/GeneralUtils/libs/ObjectMapper/Mapper.swift new file mode 100644 index 0000000..9071acc --- /dev/null +++ b/GeneralUtils/GeneralUtils/libs/ObjectMapper/Mapper.swift @@ -0,0 +1,433 @@ +// +// Mapper.swift +// ObjectMapper +// +// Created by Tristan Himmelman on 2014-10-09. +// +// The MIT License (MIT) +// +// Copyright (c) 2014-2016 Hearst +// +// Permission is hereby granted, free of charge, to any person obtaining a copy +// of this software and associated documentation files (the "Software"), to deal +// in the Software without restriction, including without limitation the rights +// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +// copies of the Software, and to permit persons to whom the Software is +// furnished to do so, subject to the following conditions: +// +// The above copyright notice and this permission notice shall be included in +// all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN +// THE SOFTWARE. + +import Foundation + +public enum MappingType { + case fromJSON + case toJSON +} + +/// The Mapper class provides methods for converting Model objects to JSON and methods for converting JSON to Model objects +public final class Mapper { + + public var context: MapContext? + public var shouldIncludeNilValues = false /// If this is set to true, toJSON output will include null values for any variables that are not set. + + public init(context: MapContext? = nil, shouldIncludeNilValues: Bool = false){ + self.context = context + self.shouldIncludeNilValues = shouldIncludeNilValues + } + + // MARK: Mapping functions that map to an existing object toObject + + /// Maps a JSON object to an existing Mappable object if it is a JSON dictionary, or returns the passed object as is + public func map(JSONObject: Any?, toObject object: N) -> N { + if let JSON = JSONObject as? [String: Any] { + return map(JSON: JSON, toObject: object) + } + + return object + } + + /// Map a JSON string onto an existing object + public func map(JSONString: String, toObject object: N) -> N { + if let JSON = Mapper.parseJSONStringIntoDictionary(JSONString: JSONString) { + return map(JSON: JSON, toObject: object) + } + return object + } + + /// Maps a JSON dictionary to an existing object that conforms to Mappable. + /// Usefull for those pesky objects that have crappy designated initializers like NSManagedObject + public func map(JSON: [String: Any], toObject object: N) -> N { + var mutableObject = object + let map = Map(mappingType: .fromJSON, JSON: JSON, toObject: true, context: context, shouldIncludeNilValues: shouldIncludeNilValues) + mutableObject.mapping(map: map) + return mutableObject + } + + //MARK: Mapping functions that create an object + + /// Map a JSON string to an object that conforms to Mappable + public func map(JSONString: String) -> N? { + if let JSON = Mapper.parseJSONStringIntoDictionary(JSONString: JSONString) { + return map(JSON: JSON) + } + + return nil + } + + /// Maps a JSON object to a Mappable object if it is a JSON dictionary or NSString, or returns nil. + public func map(JSONObject: Any?) -> N? { + if let JSON = JSONObject as? [String: Any] { + return map(JSON: JSON) + } + + return nil + } + + /// Maps a JSON dictionary to an object that conforms to Mappable + public func map(JSON: [String: Any]) -> N? { + let map = Map(mappingType: .fromJSON, JSON: JSON, context: context, shouldIncludeNilValues: shouldIncludeNilValues) + + if let klass = N.self as? StaticMappable.Type { // Check if object is StaticMappable + if var object = klass.objectForMapping(map: map) as? N { + object.mapping(map: map) + return object + } + } else if let klass = N.self as? Mappable.Type { // Check if object is Mappable + if var object = klass.init(map: map) as? N { + object.mapping(map: map) + return object + } + } else if N.self is ImmutableMappable.Type { // Check if object is ImmutableMappable + assert(false, "'ImmutableMappable' type requires throwing version of function \(#function) - use 'try' before \(#function)") + } else { + // Ensure BaseMappable is not implemented directly + assert(false, "BaseMappable should not be implemented directly. Please implement Mappable, StaticMappable or ImmutableMappable") + } + + return nil + } + + // MARK: Mapping functions for Arrays and Dictionaries + + /// Maps a JSON array to an object that conforms to Mappable + public func mapArray(JSONString: String) -> [N]? { + let parsedJSON: Any? = Mapper.parseJSONString(JSONString: JSONString) + + if let objectArray = mapArray(JSONObject: parsedJSON) { + return objectArray + } + + // failed to parse JSON into array form + // try to parse it into a dictionary and then wrap it in an array + if let object = map(JSONObject: parsedJSON) { + return [object] + } + + return nil + } + + /// Maps a JSON object to an array of Mappable objects if it is an array of JSON dictionary, or returns nil. + public func mapArray(JSONObject: Any?) -> [N]? { + if let JSONArray = JSONObject as? [[String: Any]] { + return mapArray(JSONArray: JSONArray) + } + + return nil + } + + /// Maps an array of JSON dictionary to an array of Mappable objects + public func mapArray(JSONArray: [[String: Any]]) -> [N]? { + // map every element in JSON array to type N + let result = JSONArray.flatMap(map) + return result + } + + /// Maps a JSON object to a dictionary of Mappable objects if it is a JSON dictionary of dictionaries, or returns nil. + public func mapDictionary(JSONString: String) -> [String: N]? { + let parsedJSON: Any? = Mapper.parseJSONString(JSONString: JSONString) + return mapDictionary(JSONObject: parsedJSON) + } + + /// Maps a JSON object to a dictionary of Mappable objects if it is a JSON dictionary of dictionaries, or returns nil. + public func mapDictionary(JSONObject: Any?) -> [String: N]? { + if let JSON = JSONObject as? [String: [String: Any]] { + return mapDictionary(JSON: JSON) + } + + return nil + } + + /// Maps a JSON dictionary of dictionaries to a dictionary of Mappable objects + public func mapDictionary(JSON: [String: [String: Any]]) -> [String: N]? { + // map every value in dictionary to type N + let result = JSON.filterMap(map) + if result.isEmpty == false { + return result + } + + return nil + } + + /// Maps a JSON object to a dictionary of Mappable objects if it is a JSON dictionary of dictionaries, or returns nil. + public func mapDictionary(JSONObject: Any?, toDictionary dictionary: [String: N]) -> [String: N] { + if let JSON = JSONObject as? [String : [String : Any]] { + return mapDictionary(JSON: JSON, toDictionary: dictionary) + } + + return dictionary + } + + /// Maps a JSON dictionary of dictionaries to an existing dictionary of Mappable objects + public func mapDictionary(JSON: [String: [String: Any]], toDictionary dictionary: [String: N]) -> [String: N] { + var mutableDictionary = dictionary + for (key, value) in JSON { + if let object = dictionary[key] { + _ = map(JSON: value, toObject: object) + } else { + mutableDictionary[key] = map(JSON: value) + } + } + + return mutableDictionary + } + + /// Maps a JSON object to a dictionary of arrays of Mappable objects + public func mapDictionaryOfArrays(JSONObject: Any?) -> [String: [N]]? { + if let JSON = JSONObject as? [String: [[String: Any]]] { + return mapDictionaryOfArrays(JSON: JSON) + } + + return nil + } + + ///Maps a JSON dictionary of arrays to a dictionary of arrays of Mappable objects + public func mapDictionaryOfArrays(JSON: [String: [[String: Any]]]) -> [String: [N]]? { + // map every value in dictionary to type N + let result = JSON.filterMap { + mapArray(JSONArray: $0) + } + + if result.isEmpty == false { + return result + } + + return nil + } + + /// Maps an 2 dimentional array of JSON dictionaries to a 2 dimentional array of Mappable objects + public func mapArrayOfArrays(JSONObject: Any?) -> [[N]]? { + if let JSONArray = JSONObject as? [[[String: Any]]] { + var objectArray = [[N]]() + for innerJSONArray in JSONArray { + if let array = mapArray(JSONArray: innerJSONArray){ + objectArray.append(array) + } + } + + if objectArray.isEmpty == false { + return objectArray + } + } + + return nil + } + + // MARK: Utility functions for converting strings to JSON objects + + /// Convert a JSON String into a Dictionary using NSJSONSerialization + public static func parseJSONStringIntoDictionary(JSONString: String) -> [String: Any]? { + let parsedJSON: Any? = Mapper.parseJSONString(JSONString: JSONString) + return parsedJSON as? [String: Any] + } + + /// Convert a JSON String into an Object using NSJSONSerialization + public static func parseJSONString(JSONString: String) -> Any? { + let data = JSONString.data(using: String.Encoding.utf8, allowLossyConversion: true) + if let data = data { + let parsedJSON: Any? + do { + parsedJSON = try JSONSerialization.jsonObject(with: data, options: JSONSerialization.ReadingOptions.allowFragments) + } catch let error { + print(error) + parsedJSON = nil + } + return parsedJSON + } + + return nil + } +} + +extension Mapper { + + // MARK: Functions that create JSON from objects + + ///Maps an object that conforms to Mappable to a JSON dictionary + public func toJSON(_ object: N) -> [String: Any] { + var mutableObject = object + let map = Map(mappingType: .toJSON, JSON: [:], context: context, shouldIncludeNilValues: shouldIncludeNilValues) + mutableObject.mapping(map: map) + return map.JSON + } + + ///Maps an array of Objects to an array of JSON dictionaries [[String: Any]] + public func toJSONArray(_ array: [N]) -> [[String: Any]] { + return array.map { + // convert every element in array to JSON dictionary equivalent + self.toJSON($0) + } + } + + ///Maps a dictionary of Objects that conform to Mappable to a JSON dictionary of dictionaries. + public func toJSONDictionary(_ dictionary: [String: N]) -> [String: [String: Any]] { + return dictionary.map { k, v in + // convert every value in dictionary to its JSON dictionary equivalent + return (k, self.toJSON(v)) + } + } + + ///Maps a dictionary of Objects that conform to Mappable to a JSON dictionary of dictionaries. + public func toJSONDictionaryOfArrays(_ dictionary: [String: [N]]) -> [String: [[String: Any]]] { + return dictionary.map { k, v in + // convert every value (array) in dictionary to its JSON dictionary equivalent + return (k, self.toJSONArray(v)) + } + } + + /// Maps an Object to a JSON string with option of pretty formatting + public func toJSONString(_ object: N, prettyPrint: Bool = false) -> String? { + let JSONDict = toJSON(object) + + return Mapper.toJSONString(JSONDict as Any, prettyPrint: prettyPrint) + } + + /// Maps an array of Objects to a JSON string with option of pretty formatting + public func toJSONString(_ array: [N], prettyPrint: Bool = false) -> String? { + let JSONDict = toJSONArray(array) + + return Mapper.toJSONString(JSONDict as Any, prettyPrint: prettyPrint) + } + + /// Converts an Object to a JSON string with option of pretty formatting + public static func toJSONString(_ JSONObject: Any, prettyPrint: Bool) -> String? { + let options: JSONSerialization.WritingOptions = prettyPrint ? .prettyPrinted : [] + if let JSON = Mapper.toJSONData(JSONObject, options: options) { + return String(data: JSON, encoding: String.Encoding.utf8) + } + + return nil + } + + /// Converts an Object to JSON data with options + public static func toJSONData(_ JSONObject: Any, options: JSONSerialization.WritingOptions) -> Data? { + if JSONSerialization.isValidJSONObject(JSONObject) { + let JSONData: Data? + do { + JSONData = try JSONSerialization.data(withJSONObject: JSONObject, options: options) + } catch let error { + print(error) + JSONData = nil + } + + return JSONData + } + + return nil + } +} + +extension Mapper where N: Hashable { + + /// Maps a JSON array to an object that conforms to Mappable + public func mapSet(JSONString: String) -> Set? { + let parsedJSON: Any? = Mapper.parseJSONString(JSONString: JSONString) + + if let objectArray = mapArray(JSONObject: parsedJSON) { + return Set(objectArray) + } + + // failed to parse JSON into array form + // try to parse it into a dictionary and then wrap it in an array + if let object = map(JSONObject: parsedJSON) { + return Set([object]) + } + + return nil + } + + /// Maps a JSON object to an Set of Mappable objects if it is an array of JSON dictionary, or returns nil. + public func mapSet(JSONObject: Any?) -> Set? { + if let JSONArray = JSONObject as? [[String: Any]] { + return mapSet(JSONArray: JSONArray) + } + + return nil + } + + /// Maps an Set of JSON dictionary to an array of Mappable objects + public func mapSet(JSONArray: [[String: Any]]) -> Set { + // map every element in JSON array to type N + return Set(JSONArray.flatMap(map)) + } + + ///Maps a Set of Objects to a Set of JSON dictionaries [[String : Any]] + public func toJSONSet(_ set: Set) -> [[String: Any]] { + return set.map { + // convert every element in set to JSON dictionary equivalent + self.toJSON($0) + } + } + + /// Maps a set of Objects to a JSON string with option of pretty formatting + public func toJSONString(_ set: Set, prettyPrint: Bool = false) -> String? { + let JSONDict = toJSONSet(set) + + return Mapper.toJSONString(JSONDict as Any, prettyPrint: prettyPrint) + } +} + +extension Dictionary { + internal func map(_ f: (Element) throws -> (K, V)) rethrows -> [K: V] { + var mapped = [K: V]() + + for element in self { + let newElement = try f(element) + mapped[newElement.0] = newElement.1 + } + + return mapped + } + + internal func map(_ f: (Element) throws -> (K, [V])) rethrows -> [K: [V]] { + var mapped = [K: [V]]() + + for element in self { + let newElement = try f(element) + mapped[newElement.0] = newElement.1 + } + + return mapped + } + + + internal func filterMap(_ f: (Value) throws -> U?) rethrows -> [Key: U] { + var mapped = [Key: U]() + + for (key, value) in self { + if let newValue = try f(value) { + mapped[key] = newValue + } + } + + return mapped + } +} diff --git a/GeneralUtils/GeneralUtils/libs/ObjectMapper/NSDecimalNumberTransform.swift b/GeneralUtils/GeneralUtils/libs/ObjectMapper/NSDecimalNumberTransform.swift new file mode 100644 index 0000000..3b3ebab --- /dev/null +++ b/GeneralUtils/GeneralUtils/libs/ObjectMapper/NSDecimalNumberTransform.swift @@ -0,0 +1,51 @@ +// +// TransformOf.swift +// ObjectMapper +// +// Created by Tristan Himmelman on 8/22/16. +// +// The MIT License (MIT) +// +// Copyright (c) 2014-2016 Hearst +// +// Permission is hereby granted, free of charge, to any person obtaining a copy +// of this software and associated documentation files (the "Software"), to deal +// in the Software without restriction, including without limitation the rights +// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +// copies of the Software, and to permit persons to whom the Software is +// furnished to do so, subject to the following conditions: +// +// The above copyright notice and this permission notice shall be included in +// all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN +// THE SOFTWARE. + +import Foundation + +open class NSDecimalNumberTransform: TransformType { + public typealias Object = NSDecimalNumber + public typealias JSON = String + + public init() {} + + open func transformFromJSON(_ value: Any?) -> NSDecimalNumber? { + if let string = value as? String { + return NSDecimalNumber(string: string) + } + if let double = value as? Double { + return NSDecimalNumber(value: double) + } + return nil + } + + open func transformToJSON(_ value: NSDecimalNumber?) -> String? { + guard let value = value else { return nil } + return value.description + } +} diff --git a/GeneralUtils/GeneralUtils/libs/ObjectMapper/Operators.swift b/GeneralUtils/GeneralUtils/libs/ObjectMapper/Operators.swift new file mode 100644 index 0000000..57741f8 --- /dev/null +++ b/GeneralUtils/GeneralUtils/libs/ObjectMapper/Operators.swift @@ -0,0 +1,377 @@ +// +// Operators.swift +// ObjectMapper +// +// Created by Tristan Himmelman on 2014-10-09. +// +// The MIT License (MIT) +// +// Copyright (c) 2014-2016 Hearst +// +// Permission is hereby granted, free of charge, to any person obtaining a copy +// of this software and associated documentation files (the "Software"), to deal +// in the Software without restriction, including without limitation the rights +// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +// copies of the Software, and to permit persons to whom the Software is +// furnished to do so, subject to the following conditions: +// +// The above copyright notice and this permission notice shall be included in +// all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN +// THE SOFTWARE. + +/** +* This file defines a new operator which is used to create a mapping between an object and a JSON key value. +* There is an overloaded operator definition for each type of object that is supported in ObjectMapper. +* This provides a way to add custom logic to handle specific types of objects +*/ + +/// Operator used for defining mappings to and from JSON +infix operator <- + +/// Operator used to define mappings to JSON +infix operator >>> + +// MARK:- Objects with Basic types + +/// Object of Basic type +public func <- (left: inout T, right: Map) { + switch right.mappingType { + case .fromJSON where right.isKeyPresent: + FromJSON.basicType(&left, object: right.value()) + case .toJSON: + left >>> right + default: () + } +} + +public func >>> (left: T, right: Map) { + if right.mappingType == .toJSON { + ToJSON.basicType(left, map: right) + } +} + + +/// Optional object of basic type +public func <- (left: inout T?, right: Map) { + switch right.mappingType { + case .fromJSON where right.isKeyPresent: + FromJSON.optionalBasicType(&left, object: right.value()) + case .toJSON: + left >>> right + default: () + } +} + +public func >>> (left: T?, right: Map) { + if right.mappingType == .toJSON { + ToJSON.optionalBasicType(left, map: right) + } +} + + +/// Implicitly unwrapped optional object of basic type +public func <- (left: inout T!, right: Map) { + switch right.mappingType { + case .fromJSON where right.isKeyPresent: + FromJSON.optionalBasicType(&left, object: right.value()) + case .toJSON: + left >>> right + default: () + } +} + +// MARK:- Mappable Objects - + +/// Object conforming to Mappable +public func <- (left: inout T, right: Map) { + switch right.mappingType { + case .fromJSON: + FromJSON.object(&left, map: right) + case .toJSON: + left >>> right + } +} + +public func >>> (left: T, right: Map) { + if right.mappingType == .toJSON { + ToJSON.object(left, map: right) + } +} + + +/// Optional Mappable objects +public func <- (left: inout T?, right: Map) { + switch right.mappingType { + case .fromJSON where right.isKeyPresent: + FromJSON.optionalObject(&left, map: right) + case .toJSON: + left >>> right + default: () + } +} + +public func >>> (left: T?, right: Map) { + if right.mappingType == .toJSON { + ToJSON.optionalObject(left, map: right) + } +} + + +/// Implicitly unwrapped optional Mappable objects +public func <- (left: inout T!, right: Map) { + switch right.mappingType { + case .fromJSON where right.isKeyPresent: + FromJSON.optionalObject(&left, map: right) + case .toJSON: + left >>> right + default: () + } +} + +// MARK:- Dictionary of Mappable objects - Dictionary + +/// Dictionary of Mappable objects +public func <- (left: inout Dictionary, right: Map) { + switch right.mappingType { + case .fromJSON where right.isKeyPresent: + FromJSON.objectDictionary(&left, map: right) + case .toJSON: + left >>> right + default: () + } +} + +public func >>> (left: Dictionary, right: Map) { + if right.mappingType == .toJSON { + ToJSON.objectDictionary(left, map: right) + } +} + + +/// Optional Dictionary of Mappable object +public func <- (left: inout Dictionary?, right: Map) { + switch right.mappingType { + case .fromJSON where right.isKeyPresent: + FromJSON.optionalObjectDictionary(&left, map: right) + case .toJSON: + left >>> right + default: () + } +} + +public func >>> (left: Dictionary?, right: Map) { + if right.mappingType == .toJSON { + ToJSON.optionalObjectDictionary(left, map: right) + } +} + + +/// Implicitly unwrapped Optional Dictionary of Mappable object +public func <- (left: inout Dictionary!, right: Map) { + switch right.mappingType { + case .fromJSON where right.isKeyPresent: + FromJSON.optionalObjectDictionary(&left, map: right) + case .toJSON: + left >>> right + default: () + } +} + +/// Dictionary of Mappable objects +public func <- (left: inout Dictionary, right: Map) { + switch right.mappingType { + case .fromJSON where right.isKeyPresent: + FromJSON.objectDictionaryOfArrays(&left, map: right) + case .toJSON: + left >>> right + default: () + } +} + +public func >>> (left: Dictionary, right: Map) { + if right.mappingType == .toJSON { + ToJSON.objectDictionaryOfArrays(left, map: right) + } +} + +/// Optional Dictionary of Mappable object +public func <- (left: inout Dictionary?, right: Map) { + switch right.mappingType { + case .fromJSON where right.isKeyPresent: + FromJSON.optionalObjectDictionaryOfArrays(&left, map: right) + case .toJSON: + left >>> right + default: () + } +} + +public func >>> (left: Dictionary?, right: Map) { + if right.mappingType == .toJSON { + ToJSON.optionalObjectDictionaryOfArrays(left, map: right) + } +} + + +/// Implicitly unwrapped Optional Dictionary of Mappable object +public func <- (left: inout Dictionary!, right: Map) { + switch right.mappingType { + case .fromJSON where right.isKeyPresent: + FromJSON.optionalObjectDictionaryOfArrays(&left, map: right) + case .toJSON: + left >>> right + default: () + } +} + +// MARK:- Array of Mappable objects - Array + +/// Array of Mappable objects +public func <- (left: inout Array, right: Map) { + switch right.mappingType { + case .fromJSON where right.isKeyPresent: + FromJSON.objectArray(&left, map: right) + case .toJSON: + left >>> right + default: () + } +} + +public func >>> (left: Array, right: Map) { + if right.mappingType == .toJSON { + ToJSON.objectArray(left, map: right) + } +} + +/// Optional array of Mappable objects +public func <- (left: inout Array?, right: Map) { + switch right.mappingType { + case .fromJSON where right.isKeyPresent: + FromJSON.optionalObjectArray(&left, map: right) + case .toJSON: + left >>> right + default: () + } +} + +public func >>> (left: Array?, right: Map) { + if right.mappingType == .toJSON { + ToJSON.optionalObjectArray(left, map: right) + } +} + + +/// Implicitly unwrapped Optional array of Mappable objects +public func <- (left: inout Array!, right: Map) { + switch right.mappingType { + case .fromJSON where right.isKeyPresent: + FromJSON.optionalObjectArray(&left, map: right) + case .toJSON: + left >>> right + default: () + } +} + +// MARK:- Array of Array of Mappable objects - Array> + +/// Array of Array Mappable objects +public func <- (left: inout Array>, right: Map) { + switch right.mappingType { + case .fromJSON where right.isKeyPresent: + FromJSON.twoDimensionalObjectArray(&left, map: right) + case .toJSON: + left >>> right + default: () + } +} + +public func >>> (left: Array>, right: Map) { + if right.mappingType == .toJSON { + ToJSON.twoDimensionalObjectArray(left, map: right) + } +} + + +/// Optional array of Mappable objects +public func <- (left:inout Array>?, right: Map) { + switch right.mappingType { + case .fromJSON where right.isKeyPresent: + FromJSON.optionalTwoDimensionalObjectArray(&left, map: right) + case .toJSON: + left >>> right + default: () + } +} + +public func >>> (left: Array>?, right: Map) { + if right.mappingType == .toJSON { + ToJSON.optionalTwoDimensionalObjectArray(left, map: right) + } +} + + +/// Implicitly unwrapped Optional array of Mappable objects +public func <- (left: inout Array>!, right: Map) { + switch right.mappingType { + case .fromJSON where right.isKeyPresent: + FromJSON.optionalTwoDimensionalObjectArray(&left, map: right) + case .toJSON: + left >>> right + default: () + } +} + +// MARK:- Set of Mappable objects - Set + +/// Set of Mappable objects +public func <- (left: inout Set, right: Map) where T: Hashable { + switch right.mappingType { + case .fromJSON where right.isKeyPresent: + FromJSON.objectSet(&left, map: right) + case .toJSON: + left >>> right + default: () + } +} + +public func >>> (left: Set, right: Map) where T: Hashable { + if right.mappingType == .toJSON { + ToJSON.objectSet(left, map: right) + } +} + + +/// Optional Set of Mappable objects +public func <- (left: inout Set?, right: Map) where T: Hashable, T: Hashable { + switch right.mappingType { + case .fromJSON where right.isKeyPresent: + FromJSON.optionalObjectSet(&left, map: right) + case .toJSON: + left >>> right + default: () + } +} + +public func >>> (left: Set?, right: Map) where T: Hashable, T: Hashable { + if right.mappingType == .toJSON { + ToJSON.optionalObjectSet(left, map: right) + } +} + + +/// Implicitly unwrapped Optional Set of Mappable objects +public func <- (left: inout Set!, right: Map) where T: Hashable { + switch right.mappingType { + case .fromJSON where right.isKeyPresent: + FromJSON.optionalObjectSet(&left, map: right) + case .toJSON: + left >>> right + default: () + } +} diff --git a/GeneralUtils/GeneralUtils/libs/ObjectMapper/ToJSON.swift b/GeneralUtils/GeneralUtils/libs/ObjectMapper/ToJSON.swift new file mode 100644 index 0000000..b1eff4b --- /dev/null +++ b/GeneralUtils/GeneralUtils/libs/ObjectMapper/ToJSON.swift @@ -0,0 +1,179 @@ +// +// ToJSON.swift +// ObjectMapper +// +// Created by Tristan Himmelman on 2014-10-13. +// +// The MIT License (MIT) +// +// Copyright (c) 2014-2016 Hearst +// +// Permission is hereby granted, free of charge, to any person obtaining a copy +// of this software and associated documentation files (the "Software"), to deal +// in the Software without restriction, including without limitation the rights +// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +// copies of the Software, and to permit persons to whom the Software is +// furnished to do so, subject to the following conditions: +// +// The above copyright notice and this permission notice shall be included in +// all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN +// THE SOFTWARE. + +import class Foundation.NSNumber + +private func setValue(_ value: Any, map: Map) { + setValue(value, key: map.currentKey!, checkForNestedKeys: map.keyIsNested, delimiter: map.nestedKeyDelimiter, dictionary: &map.JSON) +} + +private func setValue(_ value: Any, key: String, checkForNestedKeys: Bool, delimiter: String, dictionary: inout [String : Any]) { + if checkForNestedKeys { + let keyComponents = ArraySlice(key.components(separatedBy: delimiter).filter { !$0.isEmpty }.map { $0.characters }) + setValue(value, forKeyPathComponents: keyComponents, dictionary: &dictionary) + } else { + dictionary[key] = value + } +} + +private func setValue(_ value: Any, forKeyPathComponents components: ArraySlice, dictionary: inout [String : Any]) { + if components.isEmpty { + return + } + + let head = components.first! + + if components.count == 1 { + dictionary[String(head)] = value + } else { + var child = dictionary[String(head)] as? [String : Any] + if child == nil { + child = [:] + } + + let tail = components.dropFirst() + setValue(value, forKeyPathComponents: tail, dictionary: &child!) + + dictionary[String(head)] = child + } +} + +internal final class ToJSON { + + class func basicType(_ field: N, map: Map) { + if let x = field as Any? , false + || x is NSNumber // Basic types + || x is Bool + || x is Int + || x is Double + || x is Float + || x is String + || x is NSNull + || x is Array // Arrays + || x is Array + || x is Array + || x is Array + || x is Array + || x is Array + || x is Array + || x is Array> + || x is Dictionary // Dictionaries + || x is Dictionary + || x is Dictionary + || x is Dictionary + || x is Dictionary + || x is Dictionary + || x is Dictionary + { + setValue(x, map: map) + } + } + + class func optionalBasicType(_ field: N?, map: Map) { + if let field = field { + basicType(field, map: map) + } else if map.shouldIncludeNilValues { + basicType(NSNull(), map: map) //If BasicType is nil, emil NSNull into the JSON output + } + } + + class func object(_ field: N, map: Map) { + if let result = Mapper(context: map.context).toJSON(field) as Any? { + setValue(result, map: map) + } + } + + class func optionalObject(_ field: N?, map: Map) { + if let field = field { + object(field, map: map) + } + } + + class func objectArray(_ field: Array, map: Map) { + let JSONObjects = Mapper(context: map.context).toJSONArray(field) + + setValue(JSONObjects, map: map) + } + + class func optionalObjectArray(_ field: Array?, map: Map) { + if let field = field { + objectArray(field, map: map) + } + } + + class func twoDimensionalObjectArray(_ field: Array>, map: Map) { + var array = [[[String: Any]]]() + for innerArray in field { + let JSONObjects = Mapper(context: map.context).toJSONArray(innerArray) + array.append(JSONObjects) + } + setValue(array, map: map) + } + + class func optionalTwoDimensionalObjectArray(_ field: Array>?, map: Map) { + if let field = field { + twoDimensionalObjectArray(field, map: map) + } + } + + class func objectSet(_ field: Set, map: Map) where N: Hashable { + let JSONObjects = Mapper(context: map.context).toJSONSet(field) + + setValue(JSONObjects, map: map) + } + + class func optionalObjectSet(_ field: Set?, map: Map) where N: Hashable { + if let field = field { + objectSet(field, map: map) + } + } + + class func objectDictionary(_ field: Dictionary, map: Map) { + let JSONObjects = Mapper(context: map.context).toJSONDictionary(field) + + setValue(JSONObjects, map: map) + } + + class func optionalObjectDictionary(_ field: Dictionary?, map: Map) { + if let field = field { + objectDictionary(field, map: map) + } + } + + class func objectDictionaryOfArrays(_ field: Dictionary, map: Map) { + let JSONObjects = Mapper(context: map.context).toJSONDictionaryOfArrays(field) + + setValue(JSONObjects, map: map) + } + + class func optionalObjectDictionaryOfArrays(_ field: Dictionary?, map: Map) { + if let field = field { + objectDictionaryOfArrays(field, map: map) + } + } +} diff --git a/GeneralUtils/GeneralUtils/libs/ObjectMapper/TransformOf.swift b/GeneralUtils/GeneralUtils/libs/ObjectMapper/TransformOf.swift new file mode 100644 index 0000000..97056c6 --- /dev/null +++ b/GeneralUtils/GeneralUtils/libs/ObjectMapper/TransformOf.swift @@ -0,0 +1,48 @@ +// +// TransformOf.swift +// ObjectMapper +// +// Created by Syo Ikeda on 1/23/15. +// +// The MIT License (MIT) +// +// Copyright (c) 2014-2016 Hearst +// +// Permission is hereby granted, free of charge, to any person obtaining a copy +// of this software and associated documentation files (the "Software"), to deal +// in the Software without restriction, including without limitation the rights +// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +// copies of the Software, and to permit persons to whom the Software is +// furnished to do so, subject to the following conditions: +// +// The above copyright notice and this permission notice shall be included in +// all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN +// THE SOFTWARE. + +open class TransformOf: TransformType { + public typealias Object = ObjectType + public typealias JSON = JSONType + + private let fromJSON: (JSONType?) -> ObjectType? + private let toJSON: (ObjectType?) -> JSONType? + + public init(fromJSON: @escaping(JSONType?) -> ObjectType?, toJSON: @escaping(ObjectType?) -> JSONType?) { + self.fromJSON = fromJSON + self.toJSON = toJSON + } + + open func transformFromJSON(_ value: Any?) -> ObjectType? { + return fromJSON(value as? JSONType) + } + + open func transformToJSON(_ value: ObjectType?) -> JSONType? { + return toJSON(value) + } +} diff --git a/GeneralUtils/GeneralUtils/libs/ObjectMapper/TransformOperators.swift b/GeneralUtils/GeneralUtils/libs/ObjectMapper/TransformOperators.swift new file mode 100644 index 0000000..dbe5ad2 --- /dev/null +++ b/GeneralUtils/GeneralUtils/libs/ObjectMapper/TransformOperators.swift @@ -0,0 +1,606 @@ +// +// TransformOperators.swift +// ObjectMapper +// +// Created by Tristan Himmelman on 2016-09-26. +// Copyright © 2016 hearst. All rights reserved. +// + +import Foundation + +// MARK:- Transforms + +/// Object of Basic type with Transform +public func <- (left: inout Transform.Object, right: (Map, Transform)) { + let (map, transform) = right + switch map.mappingType { + case .fromJSON where map.isKeyPresent: + let value = transform.transformFromJSON(map.currentValue) + FromJSON.basicType(&left, object: value) + case .toJSON: + left >>> right + default: () + } +} + +public func >>> (left: Transform.Object, right: (Map, Transform)) { + let (map, transform) = right + if map.mappingType == .toJSON { + let value: Transform.JSON? = transform.transformToJSON(left) + ToJSON.optionalBasicType(value, map: map) + } +} + + +/// Optional object of basic type with Transform +public func <- (left: inout Transform.Object?, right: (Map, Transform)) { + let (map, transform) = right + switch map.mappingType { + case .fromJSON where map.isKeyPresent: + let value = transform.transformFromJSON(map.currentValue) + FromJSON.optionalBasicType(&left, object: value) + case .toJSON: + left >>> right + default: () + } +} + +public func >>> (left: Transform.Object?, right: (Map, Transform)) { + let (map, transform) = right + if map.mappingType == .toJSON { + let value: Transform.JSON? = transform.transformToJSON(left) + ToJSON.optionalBasicType(value, map: map) + } +} + + +/// Implicitly unwrapped optional object of basic type with Transform +public func <- (left: inout Transform.Object!, right: (Map, Transform)) { + let (map, transform) = right + switch map.mappingType { + case .fromJSON where map.isKeyPresent: + let value = transform.transformFromJSON(map.currentValue) + FromJSON.optionalBasicType(&left, object: value) + case .toJSON: + left >>> right + default: () + } +} + +/// Array of Basic type with Transform +public func <- (left: inout [Transform.Object], right: (Map, Transform)) { + let (map, transform) = right + switch map.mappingType { + case .fromJSON where map.isKeyPresent: + let values = fromJSONArrayWithTransform(map.currentValue, transform: transform) + FromJSON.basicType(&left, object: values) + case .toJSON: + left >>> right + default: () + } +} + +public func >>> (left: [Transform.Object], right: (Map, Transform)) { + let (map, transform) = right + if map.mappingType == .toJSON{ + let values = toJSONArrayWithTransform(left, transform: transform) + ToJSON.optionalBasicType(values, map: map) + } +} + + +/// Optional array of Basic type with Transform +public func <- (left: inout [Transform.Object]?, right: (Map, Transform)) { + let (map, transform) = right + switch map.mappingType { + case .fromJSON where map.isKeyPresent: + let values = fromJSONArrayWithTransform(map.currentValue, transform: transform) + FromJSON.optionalBasicType(&left, object: values) + case .toJSON: + left >>> right + default: () + } +} + +public func >>> (left: [Transform.Object]?, right: (Map, Transform)) { + let (map, transform) = right + if map.mappingType == .toJSON { + let values = toJSONArrayWithTransform(left, transform: transform) + ToJSON.optionalBasicType(values, map: map) + } +} + + +/// Implicitly unwrapped optional array of Basic type with Transform +public func <- (left: inout [Transform.Object]!, right: (Map, Transform)) { + let (map, transform) = right + switch map.mappingType { + case .fromJSON where map.isKeyPresent: + let values = fromJSONArrayWithTransform(map.currentValue, transform: transform) + FromJSON.optionalBasicType(&left, object: values) + case .toJSON: + left >>> right + default: () + } +} + +/// Dictionary of Basic type with Transform +public func <- (left: inout [String: Transform.Object], right: (Map, Transform)) { + let (map, transform) = right + switch map.mappingType { + case .fromJSON where map.isKeyPresent: + let values = fromJSONDictionaryWithTransform(map.currentValue, transform: transform) + FromJSON.basicType(&left, object: values) + case .toJSON: + left >>> right + default: () + } +} + +public func >>> (left: [String: Transform.Object], right: (Map, Transform)) { + let (map, transform) = right + if map.mappingType == . toJSON { + let values = toJSONDictionaryWithTransform(left, transform: transform) + ToJSON.optionalBasicType(values, map: map) + } +} + + +/// Optional dictionary of Basic type with Transform +public func <- (left: inout [String: Transform.Object]?, right: (Map, Transform)) { + let (map, transform) = right + switch map.mappingType { + case .fromJSON where map.isKeyPresent: + let values = fromJSONDictionaryWithTransform(map.currentValue, transform: transform) + FromJSON.optionalBasicType(&left, object: values) + case .toJSON: + left >>> right + default: () + } +} + +public func >>> (left: [String: Transform.Object]?, right: (Map, Transform)) { + let (map, transform) = right + if map.mappingType == .toJSON { + let values = toJSONDictionaryWithTransform(left, transform: transform) + ToJSON.optionalBasicType(values, map: map) + } +} + + +/// Implicitly unwrapped optional dictionary of Basic type with Transform +public func <- (left: inout [String: Transform.Object]!, right: (Map, Transform)) { + let (map, transform) = right + switch map.mappingType { + case .fromJSON where map.isKeyPresent: + let values = fromJSONDictionaryWithTransform(map.currentValue, transform: transform) + FromJSON.optionalBasicType(&left, object: values) + case .toJSON: + left >>> right + default: () + } +} + +// MARK:- Transforms of Mappable Objects - + +/// Object conforming to Mappable that have transforms +public func <- (left: inout Transform.Object, right: (Map, Transform)) where Transform.Object: BaseMappable { + let (map, transform) = right + switch map.mappingType { + case .fromJSON where map.isKeyPresent: + let value: Transform.Object? = transform.transformFromJSON(map.currentValue) + FromJSON.basicType(&left, object: value) + case .toJSON: + left >>> right + default: () + } +} + +public func >>> (left: Transform.Object, right: (Map, Transform)) where Transform.Object: BaseMappable { + let (map, transform) = right + if map.mappingType == .toJSON { + let value: Transform.JSON? = transform.transformToJSON(left) + ToJSON.optionalBasicType(value, map: map) + } +} + + +/// Optional Mappable objects that have transforms +public func <- (left: inout Transform.Object?, right: (Map, Transform)) where Transform.Object: BaseMappable { + let (map, transform) = right + switch map.mappingType { + case .fromJSON where map.isKeyPresent: + let value: Transform.Object? = transform.transformFromJSON(map.currentValue) + FromJSON.optionalBasicType(&left, object: value) + case .toJSON: + left >>> right + default: () + } +} + +public func >>> (left: Transform.Object?, right: (Map, Transform)) where Transform.Object: BaseMappable { + let (map, transform) = right + if map.mappingType == .toJSON{ + let value: Transform.JSON? = transform.transformToJSON(left) + ToJSON.optionalBasicType(value, map: map) + } +} + + +/// Implicitly unwrapped optional Mappable objects that have transforms +public func <- (left: inout Transform.Object!, right: (Map, Transform)) where Transform.Object: BaseMappable { + let (map, transform) = right + switch map.mappingType { + case .fromJSON where map.isKeyPresent: + let value: Transform.Object? = transform.transformFromJSON(map.currentValue) + FromJSON.optionalBasicType(&left, object: value) + case .toJSON: + left >>> right + default: () + } +} + + +// MARK:- Dictionary of Mappable objects with a transform - Dictionary + +/// Dictionary of Mappable objects with a transform +public func <- (left: inout Dictionary, right: (Map, Transform)) where Transform.Object: BaseMappable { + let (map, transform) = right + if map.mappingType == .fromJSON && map.isKeyPresent, + let object = map.currentValue as? [String: AnyObject] { + let value = fromJSONDictionaryWithTransform(object as AnyObject?, transform: transform) ?? left + FromJSON.basicType(&left, object: value) + } else if map.mappingType == .toJSON { + left >>> right + } +} + +public func >>> (left: Dictionary, right: (Map, Transform)) where Transform.Object: BaseMappable { + let (map, transform) = right + if map.mappingType == .toJSON { + let value = toJSONDictionaryWithTransform(left, transform: transform) + ToJSON.basicType(value, map: map) + } +} + + +/// Optional Dictionary of Mappable object with a transform +public func <- (left: inout Dictionary?, right: (Map, Transform)) where Transform.Object: BaseMappable { + let (map, transform) = right + if map.mappingType == .fromJSON && map.isKeyPresent, let object = map.currentValue as? [String : AnyObject]{ + let value = fromJSONDictionaryWithTransform(object as AnyObject?, transform: transform) ?? left + FromJSON.optionalBasicType(&left, object: value) + } else if map.mappingType == .toJSON { + left >>> right + } +} + +public func >>> (left: Dictionary?, right: (Map, Transform)) where Transform.Object: BaseMappable { + let (map, transform) = right + if map.mappingType == .toJSON { + let value = toJSONDictionaryWithTransform(left, transform: transform) + ToJSON.optionalBasicType(value, map: map) + } +} + + +/// Implicitly unwrapped Optional Dictionary of Mappable object with a transform +public func <- (left: inout Dictionary!, right: (Map, Transform)) where Transform.Object: BaseMappable { + let (map, transform) = right + if map.mappingType == .fromJSON && map.isKeyPresent, let dictionary = map.currentValue as? [String : AnyObject]{ + let transformedDictionary = fromJSONDictionaryWithTransform(dictionary as AnyObject?, transform: transform) ?? left + FromJSON.optionalBasicType(&left, object: transformedDictionary) + } else if map.mappingType == .toJSON { + left >>> right + } +} + +/// Dictionary of Mappable objects with a transform +public func <- (left: inout Dictionary, right: (Map, Transform)) where Transform.Object: BaseMappable { + let (map, transform) = right + + if let dictionary = map.currentValue as? [String : [AnyObject]], map.mappingType == .fromJSON && map.isKeyPresent { + let transformedDictionary = dictionary.map { (key: String, values: [AnyObject]) -> (String, [Transform.Object]) in + if let jsonArray = fromJSONArrayWithTransform(values, transform: transform) { + return (key, jsonArray) + } + if let leftValue = left[key] { + return (key, leftValue) + } + return (key, []) + } + + FromJSON.basicType(&left, object: transformedDictionary) + } else if map.mappingType == .toJSON { + left >>> right + } +} + +public func >>> (left: Dictionary, right: (Map, Transform)) where Transform.Object: BaseMappable { + let (map, transform) = right + + if map.mappingType == .toJSON { + let transformedDictionary = left.map { (key, values) in + return (key, toJSONArrayWithTransform(values, transform: transform) ?? []) + } + + ToJSON.basicType(transformedDictionary, map: map) + } +} + + +/// Optional Dictionary of Mappable object with a transform +public func <- (left: inout Dictionary?, right: (Map, Transform)) where Transform.Object: BaseMappable { + let (map, transform) = right + + if let dictionary = map.currentValue as? [String : [AnyObject]], map.mappingType == .fromJSON && map.isKeyPresent { + + let transformedDictionary = dictionary.map { (key: String, values: [AnyObject]) -> (String, [Transform.Object]) in + if let jsonArray = fromJSONArrayWithTransform(values, transform: transform) { + return (key, jsonArray) + } + if let leftValue = left?[key] { + return (key, leftValue) + } + return (key, []) + + } + + FromJSON.optionalBasicType(&left, object: transformedDictionary) + } else if map.mappingType == .toJSON { + left >>> right + } +} + +public func >>> (left: Dictionary?, right: (Map, Transform)) where Transform.Object: BaseMappable { + let (map, transform) = right + + if map.mappingType == .toJSON { + let transformedDictionary = left?.map { (key, values) in + return (key, toJSONArrayWithTransform(values, transform: transform) ?? []) + } + + ToJSON.optionalBasicType(transformedDictionary, map: map) + } +} + + +/// Implicitly unwrapped Optional Dictionary of Mappable object with a transform +public func <- (left: inout Dictionary!, right: (Map, Transform)) where Transform.Object: BaseMappable { + let (map, transform) = right + + if let dictionary = map.currentValue as? [String : [AnyObject]], map.mappingType == .fromJSON && map.isKeyPresent { + let transformedDictionary = dictionary.map { (key: String, values: [AnyObject]) -> (String, [Transform.Object]) in + if let jsonArray = fromJSONArrayWithTransform(values, transform: transform) { + return (key, jsonArray) + } + if let leftValue = left?[key] { + return (key, leftValue) + } + return (key, []) + } + FromJSON.optionalBasicType(&left, object: transformedDictionary) + } else if map.mappingType == .toJSON { + left >>> right + } +} + +// MARK:- Array of Mappable objects with transforms - Array + +/// Array of Mappable objects +public func <- (left: inout Array, right: (Map, Transform)) where Transform.Object: BaseMappable { + let (map, transform) = right + switch map.mappingType { + case .fromJSON where map.isKeyPresent: + if let transformedValues = fromJSONArrayWithTransform(map.currentValue, transform: transform) { + FromJSON.basicType(&left, object: transformedValues) + } + case .toJSON: + left >>> right + default: () + } +} + +public func >>> (left: Array, right: (Map, Transform)) where Transform.Object: BaseMappable { + let (map, transform) = right + if map.mappingType == .toJSON { + let transformedValues = toJSONArrayWithTransform(left, transform: transform) + ToJSON.optionalBasicType(transformedValues, map: map) + } +} + + +/// Optional array of Mappable objects +public func <- (left: inout Array?, right: (Map, Transform)) where Transform.Object: BaseMappable { + let (map, transform) = right + switch map.mappingType { + case .fromJSON where map.isKeyPresent: + let transformedValues = fromJSONArrayWithTransform(map.currentValue, transform: transform) + FromJSON.optionalBasicType(&left, object: transformedValues) + case .toJSON: + left >>> right + default: () + } +} + +public func >>> (left: Array?, right: (Map, Transform)) where Transform.Object: BaseMappable { + let (map, transform) = right + if map.mappingType == .toJSON { + let transformedValues = toJSONArrayWithTransform(left, transform: transform) + ToJSON.optionalBasicType(transformedValues, map: map) + } +} + + +/// Implicitly unwrapped Optional array of Mappable objects +public func <- (left: inout Array!, right: (Map, Transform)) where Transform.Object: BaseMappable { + let (map, transform) = right + switch map.mappingType { + case .fromJSON where map.isKeyPresent: + let transformedValues = fromJSONArrayWithTransform(map.currentValue, transform: transform) + FromJSON.optionalBasicType(&left, object: transformedValues) + case .toJSON: + left >>> right + default: () + } +} + +// MARK:- Array of Array of Mappable objects - Array>> with transforms + +/// Array of Array Mappable objects with transform +public func <- (left: inout Array>, right: (Map, Transform)) where Transform.Object: BaseMappable { + let (map, transform) = right + if map.mappingType == .fromJSON && map.isKeyPresent, let original2DArray = map.currentValue as? [[AnyObject]]{ + let transformed2DArray = original2DArray.flatMap { values in + fromJSONArrayWithTransform(values as AnyObject?, transform: transform) + } + FromJSON.basicType(&left, object: transformed2DArray) + } else if map.mappingType == .toJSON { + left >>> right + } +} + +public func >>> (left: Array>, right: (Map, Transform)) where Transform.Object: BaseMappable { + let (map, transform) = right + if map.mappingType == .toJSON { + let transformed2DArray = left.flatMap { values in + toJSONArrayWithTransform(values, transform: transform) + } + ToJSON.basicType(transformed2DArray, map: map) + } +} + + +/// Optional array of Mappable objects with transform +public func <- (left:inout Array>?, right: (Map, Transform)) where Transform.Object: BaseMappable { + let (map, transform) = right + if map.mappingType == .fromJSON && map.isKeyPresent, let original2DArray = map.currentValue as? [[AnyObject]]{ + let transformed2DArray = original2DArray.flatMap { values in + fromJSONArrayWithTransform(values as AnyObject?, transform: transform) + } + FromJSON.optionalBasicType(&left, object: transformed2DArray) + } else if map.mappingType == .toJSON { + left >>> right + } +} + +public func >>> (left: Array>?, right: (Map, Transform)) where Transform.Object: BaseMappable { + let (map, transform) = right + if map.mappingType == .toJSON { + let transformed2DArray = left?.flatMap { values in + toJSONArrayWithTransform(values, transform: transform) + } + ToJSON.optionalBasicType(transformed2DArray, map: map) + } +} + + +/// Implicitly unwrapped Optional array of Mappable objects with transform +public func <- (left: inout Array>!, right: (Map, Transform)) where Transform.Object: BaseMappable { + let (map, transform) = right + if map.mappingType == .fromJSON && map.isKeyPresent, let original2DArray = map.currentValue as? [[AnyObject]] { + let transformed2DArray = original2DArray.flatMap { values in + fromJSONArrayWithTransform(values as AnyObject?, transform: transform) + } + FromJSON.optionalBasicType(&left, object: transformed2DArray) + } else if map.mappingType == .toJSON { + left >>> right + } +} + +// MARK:- Set of Mappable objects with a transform - Set + +/// Set of Mappable objects with transform +public func <- (left: inout Set, right: (Map, Transform)) where Transform.Object: Hashable & BaseMappable { + let (map, transform) = right + switch map.mappingType { + case .fromJSON where map.isKeyPresent: + if let transformedValues = fromJSONArrayWithTransform(map.currentValue, transform: transform) { + FromJSON.basicType(&left, object: Set(transformedValues)) + } + case .toJSON: + left >>> right + default: () + } +} + +public func >>> (left: Set, right: (Map, Transform)) where Transform.Object: Hashable & BaseMappable { + let (map, transform) = right + if map.mappingType == .toJSON { + let transformedValues = toJSONArrayWithTransform(Array(left), transform: transform) + ToJSON.optionalBasicType(transformedValues, map: map) + } +} + + +/// Optional Set of Mappable objects with transform +public func <- (left: inout Set?, right: (Map, Transform)) where Transform.Object: Hashable & BaseMappable { + let (map, transform) = right + switch map.mappingType { + case .fromJSON where map.isKeyPresent: + if let transformedValues = fromJSONArrayWithTransform(map.currentValue, transform: transform) { + FromJSON.basicType(&left, object: Set(transformedValues)) + } + case .toJSON: + left >>> right + default: () + } +} + +public func >>> (left: Set?, right: (Map, Transform)) where Transform.Object: Hashable & BaseMappable { + let (map, transform) = right + if map.mappingType == .toJSON { + if let values = left { + let transformedValues = toJSONArrayWithTransform(Array(values), transform: transform) + ToJSON.optionalBasicType(transformedValues, map: map) + } + } +} + + +/// Implicitly unwrapped Optional set of Mappable objects with transform +public func <- (left: inout Set!, right: (Map, Transform)) where Transform.Object: Hashable & BaseMappable { + let (map, transform) = right + switch map.mappingType { + case .fromJSON where map.isKeyPresent: + if let transformedValues = fromJSONArrayWithTransform(map.currentValue, transform: transform) { + FromJSON.basicType(&left, object: Set(transformedValues)) + } + case .toJSON: + left >>> right + default: () + } +} + + +private func fromJSONArrayWithTransform(_ input: Any?, transform: Transform) -> [Transform.Object]? { + if let values = input as? [AnyObject] { + return values.flatMap { value in + return transform.transformFromJSON(value) + } + } else { + return nil + } +} + +private func fromJSONDictionaryWithTransform(_ input: Any?, transform: Transform) -> [String: Transform.Object]? { + if let values = input as? [String: AnyObject] { + return values.filterMap { value in + return transform.transformFromJSON(value) + } + } else { + return nil + } +} + +private func toJSONArrayWithTransform(_ input: [Transform.Object]?, transform: Transform) -> [Transform.JSON]? { + return input?.flatMap { value in + return transform.transformToJSON(value) + } +} + +private func toJSONDictionaryWithTransform(_ input: [String: Transform.Object]?, transform: Transform) -> [String: Transform.JSON]? { + return input?.filterMap { value in + return transform.transformToJSON(value) + } +} diff --git a/GeneralUtils/GeneralUtils/libs/ObjectMapper/TransformType.swift b/GeneralUtils/GeneralUtils/libs/ObjectMapper/TransformType.swift new file mode 100644 index 0000000..61578c3 --- /dev/null +++ b/GeneralUtils/GeneralUtils/libs/ObjectMapper/TransformType.swift @@ -0,0 +1,35 @@ +// +// TransformType.swift +// ObjectMapper +// +// Created by Syo Ikeda on 2/4/15. +// +// The MIT License (MIT) +// +// Copyright (c) 2014-2016 Hearst +// +// Permission is hereby granted, free of charge, to any person obtaining a copy +// of this software and associated documentation files (the "Software"), to deal +// in the Software without restriction, including without limitation the rights +// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +// copies of the Software, and to permit persons to whom the Software is +// furnished to do so, subject to the following conditions: +// +// The above copyright notice and this permission notice shall be included in +// all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN +// THE SOFTWARE. + +public protocol TransformType { + associatedtype Object + associatedtype JSON + + func transformFromJSON(_ value: Any?) -> Object? + func transformToJSON(_ value: Object?) -> JSON? +} diff --git a/GeneralUtils/GeneralUtils/libs/ObjectMapper/URLTransform.swift b/GeneralUtils/GeneralUtils/libs/ObjectMapper/URLTransform.swift new file mode 100644 index 0000000..4ef109f --- /dev/null +++ b/GeneralUtils/GeneralUtils/libs/ObjectMapper/URLTransform.swift @@ -0,0 +1,65 @@ +// +// URLTransform.swift +// ObjectMapper +// +// Created by Tristan Himmelman on 2014-10-27. +// +// The MIT License (MIT) +// +// Copyright (c) 2014-2016 Hearst +// +// Permission is hereby granted, free of charge, to any person obtaining a copy +// of this software and associated documentation files (the "Software"), to deal +// in the Software without restriction, including without limitation the rights +// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +// copies of the Software, and to permit persons to whom the Software is +// furnished to do so, subject to the following conditions: +// +// The above copyright notice and this permission notice shall be included in +// all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN +// THE SOFTWARE. + +import Foundation + +open class URLTransform: TransformType { + public typealias Object = URL + public typealias JSON = String + private let shouldEncodeURLString: Bool + + /** + Initializes the URLTransform with an option to encode URL strings before converting them to an NSURL + - parameter shouldEncodeUrlString: when true (the default) the string is encoded before passing + to `NSURL(string:)` + - returns: an initialized transformer + */ + public init(shouldEncodeURLString: Bool = true) { + self.shouldEncodeURLString = shouldEncodeURLString + } + + open func transformFromJSON(_ value: Any?) -> URL? { + guard let URLString = value as? String else { return nil } + + if !shouldEncodeURLString { + return URL(string: URLString) + } + + guard let escapedURLString = URLString.addingPercentEncoding(withAllowedCharacters: CharacterSet.urlQueryAllowed) else { + return nil + } + return URL(string: escapedURLString) + } + + open func transformToJSON(_ value: URL?) -> String? { + if let URL = value { + return URL.absoluteString + } + return nil + } +} diff --git a/GeneralUtils/GeneralUtils/libs/SCLAlertView/SCLAlertView.swift b/GeneralUtils/GeneralUtils/libs/SCLAlertView/SCLAlertView.swift new file mode 100644 index 0000000..714f41e --- /dev/null +++ b/GeneralUtils/GeneralUtils/libs/SCLAlertView/SCLAlertView.swift @@ -0,0 +1,1133 @@ +// +// SCLAlertView.swift +// SCLAlertView Example +// +// Created by Viktor Radchenko on 6/5/14. +// Copyright (c) 2014 Viktor Radchenko. All rights reserved. +// + +import Foundation +import UIKit +fileprivate func < (lhs: T?, rhs: T?) -> Bool { + switch (lhs, rhs) { + case let (l?, r?): + return l < r + case (nil, _?): + return true + default: + return false + } +} + +fileprivate func > (lhs: T?, rhs: T?) -> Bool { + switch (lhs, rhs) { + case let (l?, r?): + return l > r + default: + return rhs < lhs + } +} + + +// Pop Up Styles +public enum SCLAlertViewStyle { + case success, error, notice, warning, info, edit, wait + + var defaultColorInt: UInt { + switch self { + case .success: + return 0x22B573 + case .error: + return 0xC1272D + case .notice: + return 0x727375 + case .warning: + return 0xFFD110 + case .info: + return 0x2866BF + case .edit: + return 0xA429FF + case .wait: + return 0xD62DA5 + } + + } + +} + +// Animation Styles +public enum SCLAnimationStyle { + case noAnimation, topToBottom, bottomToTop, leftToRight, rightToLeft +} + +// Action Types +public enum SCLActionType { + case none, selector, closure +} + +// Button sub-class +open class SCLButton: UIButton { + var actionType = SCLActionType.none + var target:AnyObject! + var selector:Selector! + var action:(()->Void)! + var customBackgroundColor:UIColor? + var customTextColor:UIColor? + var initialTitle:String! + var showDurationStatus:Bool=false + + public init() { + super.init(frame: CGRect.zero) + } + + required public init?(coder aDecoder: NSCoder) { + super.init(coder:aDecoder) + } + + override public init(frame:CGRect) { + super.init(frame:frame) + } +} + +// Allow alerts to be closed/renamed in a chainable manner +// Example: SCLAlertView().showSuccess(self, title: "Test", subTitle: "Value").close() +open class SCLAlertViewResponder { + let alertview: SCLAlertView + + // Initialisation and Title/Subtitle/Close functions + public init(alertview: SCLAlertView) { + self.alertview = alertview + } + + open func setTitle(_ title: String) { + self.alertview.labelTitle.text = title + } + + open func setSubTitle(_ subTitle: String) { + self.alertview.viewText.text = subTitle + } + + open func close() { + self.alertview.hideView() + } + + open func setDismissBlock(_ dismissBlock: @escaping DismissBlock) { + self.alertview.dismissBlock = dismissBlock + } +} + +let kCircleHeightBackground: CGFloat = 62.0 + +public typealias DismissBlock = () -> Void + +// The Main Class +open class SCLAlertView: UIViewController { + + public struct SCLAppearance { + let kDefaultShadowOpacity: CGFloat + let kCircleTopPosition: CGFloat + let kCircleBackgroundTopPosition: CGFloat + let kCircleHeight: CGFloat + let kCircleIconHeight: CGFloat + let kTitleTop:CGFloat + let kTitleHeight:CGFloat + let kWindowWidth: CGFloat + var kWindowHeight: CGFloat + var kTextHeight: CGFloat + let kTextFieldHeight: CGFloat + let kTextViewdHeight: CGFloat + let kButtonHeight: CGFloat + let contentViewColor: UIColor + let contentViewBorderColor: UIColor + let titleColor: UIColor + + // Fonts + let kTitleFont: UIFont + let kTextFont: UIFont + let kButtonFont: UIFont + + // UI Options + var showCloseButton: Bool + var showCircularIcon: Bool + var shouldAutoDismiss: Bool // Set this false to 'Disable' Auto hideView when SCLButton is tapped + var contentViewCornerRadius : CGFloat + var fieldCornerRadius : CGFloat + var buttonCornerRadius : CGFloat + + // Actions + var hideWhenBackgroundViewIsTapped: Bool + + public init(kDefaultShadowOpacity: CGFloat = 0.7, kCircleTopPosition: CGFloat = -12.0, kCircleBackgroundTopPosition: CGFloat = -15.0, kCircleHeight: CGFloat = 56.0, kCircleIconHeight: CGFloat = 20.0, kTitleTop:CGFloat = 30.0, kTitleHeight:CGFloat = 25.0, kWindowWidth: CGFloat = 240.0, kWindowHeight: CGFloat = 178.0, kTextHeight: CGFloat = 90.0, kTextFieldHeight: CGFloat = 45.0, kTextViewdHeight: CGFloat = 80.0, kButtonHeight: CGFloat = 45.0, kTitleFont: UIFont = UIFont.systemFont(ofSize: 20), kTextFont: UIFont = UIFont.systemFont(ofSize: 14), kButtonFont: UIFont = UIFont.boldSystemFont(ofSize: 14), showCloseButton: Bool = true, showCircularIcon: Bool = true, shouldAutoDismiss: Bool = true, contentViewCornerRadius: CGFloat = 5.0, fieldCornerRadius: CGFloat = 3.0, buttonCornerRadius: CGFloat = 3.0, hideWhenBackgroundViewIsTapped: Bool = false, contentViewColor: UIColor = UIColorFromRGB(0xFFFFFF), contentViewBorderColor: UIColor = UIColorFromRGB(0xCCCCCC), titleColor: UIColor = UIColorFromRGB(0x4D4D4D)) { + + self.kDefaultShadowOpacity = kDefaultShadowOpacity + self.kCircleTopPosition = kCircleTopPosition + self.kCircleBackgroundTopPosition = kCircleBackgroundTopPosition + self.kCircleHeight = kCircleHeight + self.kCircleIconHeight = kCircleIconHeight + self.kTitleTop = kTitleTop + self.kTitleHeight = kTitleHeight + self.kWindowWidth = kWindowWidth + self.kWindowHeight = kWindowHeight + self.kTextHeight = kTextHeight + self.kTextFieldHeight = kTextFieldHeight + self.kTextViewdHeight = kTextViewdHeight + self.kButtonHeight = kButtonHeight + self.contentViewColor = contentViewColor + self.contentViewBorderColor = contentViewBorderColor + self.titleColor = titleColor + + self.kTitleFont = kTitleFont + self.kTextFont = kTextFont + self.kButtonFont = kButtonFont + + self.showCloseButton = showCloseButton + self.showCircularIcon = showCircularIcon + self.shouldAutoDismiss = shouldAutoDismiss + self.contentViewCornerRadius = contentViewCornerRadius + self.fieldCornerRadius = fieldCornerRadius + self.buttonCornerRadius = buttonCornerRadius + + self.hideWhenBackgroundViewIsTapped = hideWhenBackgroundViewIsTapped + } + + mutating func setkWindowHeight(_ kWindowHeight:CGFloat) { + self.kWindowHeight = kWindowHeight + } + + mutating func setkTextHeight(_ kTextHeight:CGFloat) { + self.kTextHeight = kTextHeight + } + } + + var appearance: SCLAppearance! + + // UI Colour + var viewColor = UIColor() + + // UI Options + open var iconTintColor: UIColor? + open var customSubview : UIView? + + + + // Members declaration + var baseView = UIView() + var labelTitle = UILabel() + var viewText = UITextView() + var contentView = UIView() + var circleBG = UIView(frame:CGRect(x:0, y:0, width:kCircleHeightBackground, height:kCircleHeightBackground)) + var circleView = UIView() + var circleIconView : UIView? + var duration: TimeInterval! + var durationStatusTimer: Timer! + var durationTimer: Timer! + var dismissBlock : DismissBlock? + fileprivate var inputs = [UITextField]() + fileprivate var input = [UITextView]() + internal var buttons = [SCLButton]() + fileprivate var selfReference: SCLAlertView? + + public init(appearance: SCLAppearance) { + self.appearance = appearance + super.init(nibName:nil, bundle:nil) + setup() + } + + required public init?(coder aDecoder: NSCoder) { + fatalError("NSCoding not supported") + } + + required public init() { + appearance = SCLAppearance() + super.init(nibName:nil, bundle:nil) + setup() + } + + override public init(nibName nibNameOrNil: String?, bundle nibBundleOrNil: Bundle?) { + appearance = SCLAppearance() + super.init(nibName:nibNameOrNil, bundle:nibBundleOrNil) + } + + fileprivate func setup() { + // Set up main view + view.frame = UIScreen.main.bounds + view.autoresizingMask = [UIViewAutoresizing.flexibleHeight, UIViewAutoresizing.flexibleWidth] + view.backgroundColor = UIColor(red:0, green:0, blue:0, alpha:appearance.kDefaultShadowOpacity) + view.addSubview(baseView) + // Base View + baseView.frame = view.frame + baseView.addSubview(contentView) + // Content View + contentView.layer.cornerRadius = appearance.contentViewCornerRadius + contentView.layer.masksToBounds = true + contentView.layer.borderWidth = 0.5 + contentView.addSubview(labelTitle) + contentView.addSubview(viewText) + // Circle View + circleBG.backgroundColor = UIColor.white + circleBG.layer.cornerRadius = circleBG.frame.size.height / 2 + baseView.addSubview(circleBG) + circleBG.addSubview(circleView) + let x = (kCircleHeightBackground - appearance.kCircleHeight) / 2 + circleView.frame = CGRect(x:x, y:x, width:appearance.kCircleHeight, height:appearance.kCircleHeight) + circleView.layer.cornerRadius = circleView.frame.size.height / 2 + // Title + labelTitle.numberOfLines = 1 + labelTitle.textAlignment = .center + labelTitle.font = appearance.kTitleFont + labelTitle.frame = CGRect(x:12, y:appearance.kTitleTop, width: appearance.kWindowWidth - 24, height:appearance.kTitleHeight) + // View text + viewText.isEditable = false + viewText.textAlignment = .center + viewText.textContainerInset = UIEdgeInsets.zero + viewText.textContainer.lineFragmentPadding = 0; + viewText.font = appearance.kTextFont + // Colours + contentView.backgroundColor = appearance.contentViewColor + viewText.backgroundColor = appearance.contentViewColor + labelTitle.textColor = appearance.titleColor + viewText.textColor = appearance.titleColor + contentView.layer.borderColor = appearance.contentViewBorderColor.cgColor + //Gesture Recognizer for tapping outside the textinput + let tapGesture = UITapGestureRecognizer(target: self, action: #selector(SCLAlertView.tapped(_:))) + tapGesture.numberOfTapsRequired = 1 + self.view.addGestureRecognizer(tapGesture) + } + + override open func viewWillLayoutSubviews() { + super.viewWillLayoutSubviews() + let rv = UIApplication.shared.keyWindow! as UIWindow + let sz = rv.frame.size + + // Set background frame + view.frame.size = sz + + // computing the right size to use for the textView + let maxHeight = sz.height - 100 // max overall height + var consumedHeight = CGFloat(0) + consumedHeight += appearance.kTitleTop + appearance.kTitleHeight + consumedHeight += 14 + consumedHeight += appearance.kButtonHeight * CGFloat(buttons.count) + consumedHeight += appearance.kTextFieldHeight * CGFloat(inputs.count) + consumedHeight += appearance.kTextViewdHeight * CGFloat(input.count) + let maxViewTextHeight = maxHeight - consumedHeight + let viewTextWidth = appearance.kWindowWidth - 24 + var viewTextHeight = appearance.kTextHeight + + // Check if there is a custom subview and add it over the textview + if let customSubview = customSubview { + viewTextHeight = min(customSubview.frame.height, maxViewTextHeight) + viewText.text = "" + viewText.addSubview(customSubview) + } else { + // computing the right size to use for the textView + let suggestedViewTextSize = viewText.sizeThatFits(CGSize(width: viewTextWidth, height: CGFloat.greatestFiniteMagnitude)) + viewTextHeight = min(suggestedViewTextSize.height, maxViewTextHeight) + + // scroll management + if (suggestedViewTextSize.height > maxViewTextHeight) { + viewText.isScrollEnabled = true + } else { + viewText.isScrollEnabled = false + } + } + + let windowHeight = consumedHeight + viewTextHeight + // Set frames + var x = (sz.width - appearance.kWindowWidth) / 2 + var y = (sz.height - windowHeight - (appearance.kCircleHeight / 8)) / 2 + contentView.frame = CGRect(x:x, y:y, width:appearance.kWindowWidth, height:windowHeight) + contentView.layer.cornerRadius = appearance.contentViewCornerRadius + y -= kCircleHeightBackground * 0.6 + x = (sz.width - kCircleHeightBackground) / 2 + circleBG.frame = CGRect(x:x, y:y+6, width:kCircleHeightBackground, height:kCircleHeightBackground) + + //adjust Title frame based on circularIcon show/hide flag + let titleOffset : CGFloat = appearance.showCircularIcon ? 0.0 : -12.0 + labelTitle.frame = labelTitle.frame.offsetBy(dx: 0, dy: titleOffset) + + // Subtitle + y = appearance.kTitleTop + appearance.kTitleHeight + titleOffset + viewText.frame = CGRect(x:12, y:y, width: appearance.kWindowWidth - 24, height:appearance.kTextHeight) + viewText.frame = CGRect(x:12, y:y, width: viewTextWidth, height:viewTextHeight) + // Text fields + y += viewTextHeight + 14.0 + for txt in inputs { + txt.frame = CGRect(x:12, y:y, width:appearance.kWindowWidth - 24, height:30) + txt.layer.cornerRadius = appearance.fieldCornerRadius + y += appearance.kTextFieldHeight + } + for txt in input { + txt.frame = CGRect(x:12, y:y, width:appearance.kWindowWidth - 24, height:70) + //txt.layer.cornerRadius = fieldCornerRadius + y += appearance.kTextViewdHeight + } + // Buttons + for btn in buttons { + btn.frame = CGRect(x:12, y:y, width:appearance.kWindowWidth - 24, height:35) + btn.layer.cornerRadius = appearance.buttonCornerRadius + y += appearance.kButtonHeight + } + } + + override open func viewDidAppear(_ animated: Bool) { + super.viewDidAppear(animated) + NotificationCenter.default.addObserver(self, selector: #selector(SCLAlertView.keyboardWillShow(_:)), name:NSNotification.Name.UIKeyboardWillShow, object: nil); + NotificationCenter.default.addObserver(self, selector: #selector(SCLAlertView.keyboardWillHide(_:)), name:NSNotification.Name.UIKeyboardWillHide, object: nil); + } + + open override func viewDidDisappear(_ animated: Bool) { + super.viewDidDisappear(animated) + NotificationCenter.default.removeObserver(self, name: NSNotification.Name.UIKeyboardWillShow, object: nil) + NotificationCenter.default.removeObserver(self, name: NSNotification.Name.UIKeyboardWillHide, object: nil) + } + + override open func touchesEnded(_ touches:Set, with event:UIEvent?) { + if event?.touches(for: view)?.count > 0 { + view.endEditing(true) + } + } + + open func addTextField(_ title:String?=nil)->UITextField { + // Update view height + appearance.setkWindowHeight(appearance.kWindowHeight + appearance.kTextFieldHeight) + // Add text field + let txt = UITextField() + txt.borderStyle = UITextBorderStyle.roundedRect + txt.font = appearance.kTextFont + txt.autocapitalizationType = UITextAutocapitalizationType.words + txt.clearButtonMode = UITextFieldViewMode.whileEditing + txt.layer.masksToBounds = true + txt.layer.borderWidth = 1.0 + if title != nil { + txt.placeholder = title! + } + contentView.addSubview(txt) + inputs.append(txt) + return txt + } + + open func addTextView()->UITextView { + // Update view height + appearance.setkWindowHeight(appearance.kWindowHeight + appearance.kTextViewdHeight) + // Add text view + let txt = UITextView() + // No placeholder with UITextView but you can use KMPlaceholderTextView library + txt.font = appearance.kTextFont + //txt.autocapitalizationType = UITextAutocapitalizationType.Words + //txt.clearButtonMode = UITextFieldViewMode.WhileEditing + txt.layer.masksToBounds = true + txt.layer.borderWidth = 1.0 + contentView.addSubview(txt) + input.append(txt) + return txt + } + + @discardableResult + open func addButton(_ title:String, backgroundColor:UIColor? = nil, textColor:UIColor? = nil, showDurationStatus:Bool=false, action:@escaping ()->Void)->SCLButton { + let btn = addButton(title, backgroundColor: backgroundColor, textColor: textColor, showDurationStatus: showDurationStatus) + btn.actionType = SCLActionType.closure + btn.action = action + btn.addTarget(self, action:#selector(SCLAlertView.buttonTapped(_:)), for:.touchUpInside) + btn.addTarget(self, action:#selector(SCLAlertView.buttonTapDown(_:)), for:[.touchDown, .touchDragEnter]) + btn.addTarget(self, action:#selector(SCLAlertView.buttonRelease(_:)), for:[.touchUpInside, .touchUpOutside, .touchCancel, .touchDragOutside] ) + return btn + } + + @discardableResult + open func addButton(_ title:String, backgroundColor:UIColor? = nil, textColor:UIColor? = nil, showDurationStatus:Bool = false, target:AnyObject, selector:Selector)->SCLButton { + let btn = addButton(title, backgroundColor: backgroundColor, textColor: textColor, showDurationStatus: showDurationStatus) + btn.actionType = SCLActionType.selector + btn.target = target + btn.selector = selector + btn.addTarget(self, action:#selector(SCLAlertView.buttonTapped(_:)), for:.touchUpInside) + btn.addTarget(self, action:#selector(SCLAlertView.buttonTapDown(_:)), for:[.touchDown, .touchDragEnter]) + btn.addTarget(self, action:#selector(SCLAlertView.buttonRelease(_:)), for:[.touchUpInside, .touchUpOutside, .touchCancel, .touchDragOutside] ) + return btn + } + + @discardableResult + fileprivate func addButton(_ title:String, backgroundColor:UIColor? = nil, textColor:UIColor? = nil, showDurationStatus:Bool=false)->SCLButton { + // Update view height + appearance.setkWindowHeight(appearance.kWindowHeight + appearance.kButtonHeight) + // Add button + let btn = SCLButton() + btn.layer.masksToBounds = true + btn.setTitle(title, for: UIControlState()) + btn.titleLabel?.font = appearance.kButtonFont + btn.customBackgroundColor = backgroundColor + btn.customTextColor = textColor + btn.initialTitle = title + btn.showDurationStatus = showDurationStatus + contentView.addSubview(btn) + buttons.append(btn) + return btn + } + + func buttonTapped(_ btn:SCLButton) { + if btn.actionType == SCLActionType.closure { + btn.action() + } else if btn.actionType == SCLActionType.selector { + let ctrl = UIControl() + ctrl.sendAction(btn.selector, to:btn.target, for:nil) + } else { + print("Unknow action type for button") + } + + if(self.view.alpha != 0.0 && appearance.shouldAutoDismiss){ hideView() } + } + + + func buttonTapDown(_ btn:SCLButton) { + var hue : CGFloat = 0 + var saturation : CGFloat = 0 + var brightness : CGFloat = 0 + var alpha : CGFloat = 0 + let pressBrightnessFactor = 0.85 + btn.backgroundColor?.getHue(&hue, saturation: &saturation, brightness: &brightness, alpha: &alpha) + brightness = brightness * CGFloat(pressBrightnessFactor) + btn.backgroundColor = UIColor(hue: hue, saturation: saturation, brightness: brightness, alpha: alpha) + } + + func buttonRelease(_ btn:SCLButton) { + btn.backgroundColor = btn.customBackgroundColor ?? viewColor + } + + var tmpContentViewFrameOrigin: CGPoint? + var tmpCircleViewFrameOrigin: CGPoint? + var keyboardHasBeenShown:Bool = false + + func keyboardWillShow(_ notification: Notification) { + keyboardHasBeenShown = true + + guard let userInfo = (notification as NSNotification).userInfo else {return} + guard let endKeyBoardFrame = (userInfo[UIKeyboardFrameEndUserInfoKey] as? NSValue)?.cgRectValue.minY else {return} + + if tmpContentViewFrameOrigin == nil { + tmpContentViewFrameOrigin = self.contentView.frame.origin + } + + if tmpCircleViewFrameOrigin == nil { + tmpCircleViewFrameOrigin = self.circleBG.frame.origin + } + + var newContentViewFrameY = self.contentView.frame.maxY - endKeyBoardFrame + if newContentViewFrameY < 0 { + newContentViewFrameY = 0 + } + let newBallViewFrameY = self.circleBG.frame.origin.y - newContentViewFrameY + self.contentView.frame.origin.y -= newContentViewFrameY + self.circleBG.frame.origin.y = newBallViewFrameY + } + + func keyboardWillHide(_ notification: Notification) { + if(keyboardHasBeenShown){//This could happen on the simulator (keyboard will be hidden) + if(self.tmpContentViewFrameOrigin != nil){ + self.contentView.frame.origin.y = self.tmpContentViewFrameOrigin!.y + self.tmpContentViewFrameOrigin = nil + } + if(self.tmpCircleViewFrameOrigin != nil){ + self.circleBG.frame.origin.y = self.tmpCircleViewFrameOrigin!.y + self.tmpCircleViewFrameOrigin = nil + } + + keyboardHasBeenShown = false + } + } + + //Dismiss keyboard when tapped outside textfield & close SCLAlertView when hideWhenBackgroundViewIsTapped + func tapped(_ gestureRecognizer: UITapGestureRecognizer) { + self.view.endEditing(true) + + if let tappedView = gestureRecognizer.view , tappedView.hitTest(gestureRecognizer.location(in: tappedView), with: nil) == baseView && appearance.hideWhenBackgroundViewIsTapped { + + hideView() + } + } + + // showCustom(view, title, subTitle, UIColor, UIImage) + open func showCustom(_ title: String, subTitle: String, color: UIColor, icon: UIImage, closeButtonTitle:String?=nil, duration:TimeInterval=0.0, colorStyle: UInt=SCLAlertViewStyle.success.defaultColorInt, colorTextButton: UInt=0xFFFFFF, circleIconImage: UIImage? = nil, animationStyle: SCLAnimationStyle = .topToBottom) -> SCLAlertViewResponder { + + + var red: CGFloat = 0, green: CGFloat = 0, blue: CGFloat = 0, alpha: CGFloat = 0 + + color.getRed(&red, green: &green, blue: &blue, alpha: &alpha) + + var colorAsUInt32 : UInt32 = 0 + colorAsUInt32 += UInt32(red * 255.0) << 16 + colorAsUInt32 += UInt32(green * 255.0) << 8 + colorAsUInt32 += UInt32(blue * 255.0) + + let colorAsUInt = UInt(colorAsUInt32) + + return showTitle(title, subTitle: subTitle, duration: duration, completeText:closeButtonTitle, style: .success, colorStyle: colorAsUInt, colorTextButton: colorTextButton, circleIconImage: icon, animationStyle: animationStyle) + } + + // showSuccess(view, title, subTitle) + @discardableResult + open func showSuccess(_ title: String, subTitle: String, closeButtonTitle:String?=nil, duration:TimeInterval=0.0, colorStyle: UInt=SCLAlertViewStyle.success.defaultColorInt, colorTextButton: UInt=0xFFFFFF, circleIconImage: UIImage? = nil, animationStyle: SCLAnimationStyle = .topToBottom) -> SCLAlertViewResponder { + return showTitle(title, subTitle: subTitle, duration: duration, completeText:closeButtonTitle, style: .success, colorStyle: colorStyle, colorTextButton: colorTextButton, circleIconImage: circleIconImage, animationStyle: animationStyle) + } + + // showError(view, title, subTitle) + @discardableResult + open func showError(_ title: String, subTitle: String, closeButtonTitle:String?=nil, duration:TimeInterval=0.0, colorStyle: UInt=SCLAlertViewStyle.error.defaultColorInt, colorTextButton: UInt=0xFFFFFF, circleIconImage: UIImage? = nil, animationStyle: SCLAnimationStyle = .topToBottom) -> SCLAlertViewResponder { + return showTitle(title, subTitle: subTitle, duration: duration, completeText:closeButtonTitle, style: .error, colorStyle: colorStyle, colorTextButton: colorTextButton, circleIconImage: circleIconImage, animationStyle: animationStyle) + } + + // showNotice(view, title, subTitle) + @discardableResult + open func showNotice(_ title: String, subTitle: String, closeButtonTitle:String?=nil, duration:TimeInterval=0.0, colorStyle: UInt=SCLAlertViewStyle.notice.defaultColorInt, colorTextButton: UInt=0xFFFFFF, circleIconImage: UIImage? = nil, animationStyle: SCLAnimationStyle = .topToBottom) -> SCLAlertViewResponder { + return showTitle(title, subTitle: subTitle, duration: duration, completeText:closeButtonTitle, style: .notice, colorStyle: colorStyle, colorTextButton: colorTextButton, circleIconImage: circleIconImage, animationStyle: animationStyle) + } + + // showWarning(view, title, subTitle) + @discardableResult + open func showWarning(_ title: String, subTitle: String, closeButtonTitle:String?=nil, duration:TimeInterval=0.0, colorStyle: UInt=SCLAlertViewStyle.warning.defaultColorInt, colorTextButton: UInt=0x000000, circleIconImage: UIImage? = nil, animationStyle: SCLAnimationStyle = .topToBottom) -> SCLAlertViewResponder { + return showTitle(title, subTitle: subTitle, duration: duration, completeText:closeButtonTitle, style: .warning, colorStyle: colorStyle, colorTextButton: colorTextButton, circleIconImage: circleIconImage, animationStyle: animationStyle) + } + + // showInfo(view, title, subTitle) + @discardableResult + open func showInfo(_ title: String, subTitle: String, closeButtonTitle:String?=nil, duration:TimeInterval=0.0, colorStyle: UInt=SCLAlertViewStyle.info.defaultColorInt, colorTextButton: UInt=0xFFFFFF, circleIconImage: UIImage? = nil, animationStyle: SCLAnimationStyle = .topToBottom) -> SCLAlertViewResponder { + return showTitle(title, subTitle: subTitle, duration: duration, completeText:closeButtonTitle, style: .info, colorStyle: colorStyle, colorTextButton: colorTextButton, circleIconImage: circleIconImage, animationStyle: animationStyle) + } + + // showWait(view, title, subTitle) + @discardableResult + open func showWait(_ title: String, subTitle: String, closeButtonTitle:String?=nil, duration:TimeInterval=0.0, colorStyle: UInt?=SCLAlertViewStyle.wait.defaultColorInt, colorTextButton: UInt=0xFFFFFF, circleIconImage: UIImage? = nil, animationStyle: SCLAnimationStyle = .topToBottom) -> SCLAlertViewResponder { + return showTitle(title, subTitle: subTitle, duration: duration, completeText:closeButtonTitle, style: .wait, colorStyle: colorStyle, colorTextButton: colorTextButton, circleIconImage: circleIconImage, animationStyle: animationStyle) + } + + @discardableResult + open func showEdit(_ title: String, subTitle: String, closeButtonTitle:String?=nil, duration:TimeInterval=0.0, colorStyle: UInt=SCLAlertViewStyle.edit.defaultColorInt, colorTextButton: UInt=0xFFFFFF, circleIconImage: UIImage? = nil, animationStyle: SCLAnimationStyle = .topToBottom) -> SCLAlertViewResponder { + return showTitle(title, subTitle: subTitle, duration: duration, completeText:closeButtonTitle, style: .edit, colorStyle: colorStyle, colorTextButton: colorTextButton, circleIconImage: circleIconImage, animationStyle: animationStyle) + } + + // showTitle(view, title, subTitle, style) + @discardableResult + open func showTitle(_ title: String, subTitle: String, style: SCLAlertViewStyle, closeButtonTitle:String?=nil, duration:TimeInterval=0.0, colorStyle: UInt?=0x000000, colorTextButton: UInt=0xFFFFFF, circleIconImage: UIImage? = nil, animationStyle: SCLAnimationStyle = .topToBottom) -> SCLAlertViewResponder { + + return showTitle(title, subTitle: subTitle, duration:duration, completeText:closeButtonTitle, style: style, colorStyle: colorStyle, colorTextButton: colorTextButton, circleIconImage: circleIconImage, animationStyle: animationStyle) + } + + // showTitle(view, title, subTitle, duration, style) + @discardableResult + open func showTitle(_ title: String, subTitle: String, duration: TimeInterval?, completeText: String?, style: SCLAlertViewStyle, colorStyle: UInt?=0x000000, colorTextButton: UInt?=0xFFFFFF, circleIconImage: UIImage? = nil, animationStyle: SCLAnimationStyle = .topToBottom) -> SCLAlertViewResponder { + selfReference = self + view.alpha = 0 + let rv = UIApplication.shared.keyWindow! as UIWindow + rv.addSubview(view) + view.frame = rv.bounds + baseView.frame = rv.bounds + + // Alert colour/icon + viewColor = UIColor() + var iconImage: UIImage? + let colorInt = colorStyle ?? style.defaultColorInt + viewColor = UIColorFromRGB(colorInt) + // Icon style + switch style { + case .success: + + iconImage = checkCircleIconImage(circleIconImage, defaultImage: SCLAlertViewStyleKit.imageOfCheckmark) + + case .error: + + iconImage = checkCircleIconImage(circleIconImage, defaultImage: SCLAlertViewStyleKit.imageOfCross) + + case .notice: + + iconImage = checkCircleIconImage(circleIconImage, defaultImage:SCLAlertViewStyleKit.imageOfNotice) + + case .warning: + + iconImage = checkCircleIconImage(circleIconImage, defaultImage:SCLAlertViewStyleKit.imageOfWarning) + + case .info: + + iconImage = checkCircleIconImage(circleIconImage, defaultImage:SCLAlertViewStyleKit.imageOfInfo) + + case .edit: + + iconImage = checkCircleIconImage(circleIconImage, defaultImage:SCLAlertViewStyleKit.imageOfEdit) + + case .wait: + iconImage = nil + } + + // Title + if !title.isEmpty { + self.labelTitle.text = title + } + + // Subtitle + if !subTitle.isEmpty { + viewText.text = subTitle + // Adjust text view size, if necessary + let str = subTitle as NSString + let attr = [NSFontAttributeName:viewText.font ?? UIFont()] + let sz = CGSize(width: appearance.kWindowWidth - 24, height:90) + let r = str.boundingRect(with: sz, options: NSStringDrawingOptions.usesLineFragmentOrigin, attributes:attr, context:nil) + let ht = ceil(r.size.height) + if ht < appearance.kTextHeight { + appearance.kWindowHeight -= (appearance.kTextHeight - ht) + appearance.setkTextHeight(ht) + } + } + + // Done button + if appearance.showCloseButton { + _ = addButton(completeText ?? "Done", target:self, selector:#selector(SCLAlertView.hideView)) + } + + //hidden/show circular view based on the ui option + circleView.isHidden = !appearance.showCircularIcon + circleBG.isHidden = !appearance.showCircularIcon + + // Alert view colour and images + circleView.backgroundColor = viewColor + // Spinner / icon + if style == .wait { + let indicator = UIActivityIndicatorView(activityIndicatorStyle: .whiteLarge) + indicator.startAnimating() + circleIconView = indicator + } + else { + if let iconTintColor = iconTintColor { + circleIconView = UIImageView(image: iconImage!.withRenderingMode(.alwaysTemplate)) + circleIconView?.tintColor = iconTintColor + } + else { + circleIconView = UIImageView(image: iconImage!) + } + } + circleView.addSubview(circleIconView!) + let x = (appearance.kCircleHeight - appearance.kCircleIconHeight) / 2 + circleIconView!.frame = CGRect( x: x, y: x, width: appearance.kCircleIconHeight, height: appearance.kCircleIconHeight) + circleIconView?.layer.cornerRadius = circleIconView!.bounds.height / 2 + circleIconView?.layer.masksToBounds = true + + for txt in inputs { + txt.layer.borderColor = viewColor.cgColor + } + + for txt in input { + txt.layer.borderColor = viewColor.cgColor + } + + for btn in buttons { + if let customBackgroundColor = btn.customBackgroundColor { + // Custom BackgroundColor set + btn.backgroundColor = customBackgroundColor + } else { + // Use default BackgroundColor derived from AlertStyle + btn.backgroundColor = viewColor + } + + if let customTextColor = btn.customTextColor { + // Custom TextColor set + btn.setTitleColor(customTextColor, for:UIControlState()) + } else { + // Use default BackgroundColor derived from AlertStyle + btn.setTitleColor(UIColorFromRGB(colorTextButton ?? 0xFFFFFF), for:UIControlState()) + } + } + + // Adding duration + if duration > 0 { + self.duration = duration + durationTimer?.invalidate() + durationTimer = Timer.scheduledTimer(timeInterval: self.duration, target: self, selector: #selector(SCLAlertView.hideView), userInfo: nil, repeats: false) + durationStatusTimer?.invalidate() + durationStatusTimer = Timer.scheduledTimer(timeInterval: 1.0, target: self, selector: #selector(SCLAlertView.updateDurationStatus), userInfo: nil, repeats: true) + } + + // Animate in the alert view + self.showAnimation(animationStyle) + + // Chainable objects + return SCLAlertViewResponder(alertview: self) + } + + // Show animation in the alert view + fileprivate func showAnimation(_ animationStyle: SCLAnimationStyle = .topToBottom, animationStartOffset: CGFloat = -400.0, boundingAnimationOffset: CGFloat = 15.0, animationDuration: TimeInterval = 0.2) { + + let rv = UIApplication.shared.keyWindow! as UIWindow + var animationStartOrigin = self.baseView.frame.origin + var animationCenter : CGPoint = rv.center + + switch animationStyle { + + case .noAnimation: + self.view.alpha = 1.0 + return; + + case .topToBottom: + animationStartOrigin = CGPoint(x: animationStartOrigin.x, y: self.baseView.frame.origin.y + animationStartOffset) + animationCenter = CGPoint(x: animationCenter.x, y: animationCenter.y + boundingAnimationOffset) + + case .bottomToTop: + animationStartOrigin = CGPoint(x: animationStartOrigin.x, y: self.baseView.frame.origin.y - animationStartOffset) + animationCenter = CGPoint(x: animationCenter.x, y: animationCenter.y - boundingAnimationOffset) + + case .leftToRight: + animationStartOrigin = CGPoint(x: self.baseView.frame.origin.x + animationStartOffset, y: animationStartOrigin.y) + animationCenter = CGPoint(x: animationCenter.x + boundingAnimationOffset, y: animationCenter.y) + + case .rightToLeft: + animationStartOrigin = CGPoint(x: self.baseView.frame.origin.x - animationStartOffset, y: animationStartOrigin.y) + animationCenter = CGPoint(x: animationCenter.x - boundingAnimationOffset, y: animationCenter.y) + } + + self.baseView.frame.origin = animationStartOrigin + UIView.animate(withDuration: animationDuration, animations: { + self.view.alpha = 1.0 + self.baseView.center = animationCenter + }, completion: { finished in + UIView.animate(withDuration: animationDuration, animations: { + self.view.alpha = 1.0 + self.baseView.center = rv.center + }) + }) + } + + open func updateDurationStatus() { + duration = duration.advanced(by: -1) + for btn in buttons.filter({$0.showDurationStatus}) { + let txt = "\(btn.initialTitle) (\(duration))" + btn.setTitle(txt, for: UIControlState()) + } + } + + // Close SCLAlertView + open func hideView() { + UIView.animate(withDuration: 0.2, animations: { + self.view.alpha = 0 + }, completion: { finished in + + //Stop durationTimer so alertView does not attempt to hide itself and fire it's dimiss block a second time when close button is tapped + self.durationTimer?.invalidate() + // Stop StatusTimer + self.durationStatusTimer?.invalidate() + + if(self.dismissBlock != nil) { + // Call completion handler when the alert is dismissed + self.dismissBlock!() + } + + // This is necessary for SCLAlertView to be de-initialized, preventing a strong reference cycle with the viewcontroller calling SCLAlertView. + for button in self.buttons { + button.action = nil + button.target = nil + button.selector = nil + } + + self.view.removeFromSuperview() + self.selfReference = nil + }) + } + + func checkCircleIconImage(_ circleIconImage: UIImage?, defaultImage: UIImage) -> UIImage { + if let image = circleIconImage { + return image + } else { + return defaultImage + } + } +} + +// Helper function to convert from RGB to UIColor +func UIColorFromRGB(_ rgbValue: UInt) -> UIColor { + return UIColor( + red: CGFloat((rgbValue & 0xFF0000) >> 16) / 255.0, + green: CGFloat((rgbValue & 0x00FF00) >> 8) / 255.0, + blue: CGFloat(rgbValue & 0x0000FF) / 255.0, + alpha: CGFloat(1.0) + ) +} + +// ------------------------------------ +// Icon drawing +// Code generated by PaintCode +// ------------------------------------ + +class SCLAlertViewStyleKit : NSObject { + + // Cache + struct Cache { + static var imageOfCheckmark: UIImage? + static var checkmarkTargets: [AnyObject]? + static var imageOfCross: UIImage? + static var crossTargets: [AnyObject]? + static var imageOfNotice: UIImage? + static var noticeTargets: [AnyObject]? + static var imageOfWarning: UIImage? + static var warningTargets: [AnyObject]? + static var imageOfInfo: UIImage? + static var infoTargets: [AnyObject]? + static var imageOfEdit: UIImage? + static var editTargets: [AnyObject]? + } + + // Initialization + /// swift 1.2 abolish func load + // override class func load() { + // } + + // Drawing Methods + class func drawCheckmark() { + // Checkmark Shape Drawing + let checkmarkShapePath = UIBezierPath() + checkmarkShapePath.move(to: CGPoint(x: 73.25, y: 14.05)) + checkmarkShapePath.addCurve(to: CGPoint(x: 64.51, y: 13.86), controlPoint1: CGPoint(x: 70.98, y: 11.44), controlPoint2: CGPoint(x: 66.78, y: 11.26)) + checkmarkShapePath.addLine(to: CGPoint(x: 27.46, y: 52)) + checkmarkShapePath.addLine(to: CGPoint(x: 15.75, y: 39.54)) + checkmarkShapePath.addCurve(to: CGPoint(x: 6.84, y: 39.54), controlPoint1: CGPoint(x: 13.48, y: 36.93), controlPoint2: CGPoint(x: 9.28, y: 36.93)) + checkmarkShapePath.addCurve(to: CGPoint(x: 6.84, y: 49.02), controlPoint1: CGPoint(x: 4.39, y: 42.14), controlPoint2: CGPoint(x: 4.39, y: 46.42)) + checkmarkShapePath.addLine(to: CGPoint(x: 22.91, y: 66.14)) + checkmarkShapePath.addCurve(to: CGPoint(x: 27.28, y: 68), controlPoint1: CGPoint(x: 24.14, y: 67.44), controlPoint2: CGPoint(x: 25.71, y: 68)) + checkmarkShapePath.addCurve(to: CGPoint(x: 31.65, y: 66.14), controlPoint1: CGPoint(x: 28.86, y: 68), controlPoint2: CGPoint(x: 30.43, y: 67.26)) + checkmarkShapePath.addLine(to: CGPoint(x: 73.08, y: 23.35)) + checkmarkShapePath.addCurve(to: CGPoint(x: 73.25, y: 14.05), controlPoint1: CGPoint(x: 75.52, y: 20.75), controlPoint2: CGPoint(x: 75.7, y: 16.65)) + checkmarkShapePath.close() + checkmarkShapePath.miterLimit = 4; + + UIColor.white.setFill() + checkmarkShapePath.fill() + } + + class func drawCross() { + // Cross Shape Drawing + let crossShapePath = UIBezierPath() + crossShapePath.move(to: CGPoint(x: 10, y: 70)) + crossShapePath.addLine(to: CGPoint(x: 70, y: 10)) + crossShapePath.move(to: CGPoint(x: 10, y: 10)) + crossShapePath.addLine(to: CGPoint(x: 70, y: 70)) + crossShapePath.lineCapStyle = CGLineCap.round; + crossShapePath.lineJoinStyle = CGLineJoin.round; + UIColor.white.setStroke() + crossShapePath.lineWidth = 14 + crossShapePath.stroke() + } + + class func drawNotice() { + // Notice Shape Drawing + let noticeShapePath = UIBezierPath() + noticeShapePath.move(to: CGPoint(x: 72, y: 48.54)) + noticeShapePath.addLine(to: CGPoint(x: 72, y: 39.9)) + noticeShapePath.addCurve(to: CGPoint(x: 66.38, y: 34.01), controlPoint1: CGPoint(x: 72, y: 36.76), controlPoint2: CGPoint(x: 69.48, y: 34.01)) + noticeShapePath.addCurve(to: CGPoint(x: 61.53, y: 35.97), controlPoint1: CGPoint(x: 64.82, y: 34.01), controlPoint2: CGPoint(x: 62.69, y: 34.8)) + noticeShapePath.addCurve(to: CGPoint(x: 60.36, y: 35.78), controlPoint1: CGPoint(x: 61.33, y: 35.97), controlPoint2: CGPoint(x: 62.3, y: 35.78)) + noticeShapePath.addLine(to: CGPoint(x: 60.36, y: 33.22)) + noticeShapePath.addCurve(to: CGPoint(x: 54.16, y: 26.16), controlPoint1: CGPoint(x: 60.36, y: 29.3), controlPoint2: CGPoint(x: 57.65, y: 26.16)) + noticeShapePath.addCurve(to: CGPoint(x: 48.73, y: 29.89), controlPoint1: CGPoint(x: 51.64, y: 26.16), controlPoint2: CGPoint(x: 50.67, y: 27.73)) + noticeShapePath.addLine(to: CGPoint(x: 48.73, y: 28.71)) + noticeShapePath.addCurve(to: CGPoint(x: 43.49, y: 21.64), controlPoint1: CGPoint(x: 48.73, y: 24.78), controlPoint2: CGPoint(x: 46.98, y: 21.64)) + noticeShapePath.addCurve(to: CGPoint(x: 39.03, y: 25.37), controlPoint1: CGPoint(x: 40.97, y: 21.64), controlPoint2: CGPoint(x: 39.03, y: 23.01)) + noticeShapePath.addLine(to: CGPoint(x: 39.03, y: 9.07)) + noticeShapePath.addCurve(to: CGPoint(x: 32.24, y: 2), controlPoint1: CGPoint(x: 39.03, y: 5.14), controlPoint2: CGPoint(x: 35.73, y: 2)) + noticeShapePath.addCurve(to: CGPoint(x: 25.45, y: 9.07), controlPoint1: CGPoint(x: 28.56, y: 2), controlPoint2: CGPoint(x: 25.45, y: 5.14)) + noticeShapePath.addLine(to: CGPoint(x: 25.45, y: 41.47)) + noticeShapePath.addCurve(to: CGPoint(x: 24.29, y: 43.44), controlPoint1: CGPoint(x: 25.45, y: 42.45), controlPoint2: CGPoint(x: 24.68, y: 43.04)) + noticeShapePath.addCurve(to: CGPoint(x: 9.55, y: 43.04), controlPoint1: CGPoint(x: 16.73, y: 40.88), controlPoint2: CGPoint(x: 11.88, y: 40.69)) + noticeShapePath.addCurve(to: CGPoint(x: 8, y: 46.58), controlPoint1: CGPoint(x: 8.58, y: 43.83), controlPoint2: CGPoint(x: 8, y: 45.2)) + noticeShapePath.addCurve(to: CGPoint(x: 14.4, y: 55.81), controlPoint1: CGPoint(x: 8.19, y: 50.31), controlPoint2: CGPoint(x: 12.07, y: 53.84)) + noticeShapePath.addLine(to: CGPoint(x: 27.2, y: 69.56)) + noticeShapePath.addCurve(to: CGPoint(x: 42.91, y: 77.8), controlPoint1: CGPoint(x: 30.5, y: 74.47), controlPoint2: CGPoint(x: 35.73, y: 77.21)) + noticeShapePath.addCurve(to: CGPoint(x: 43.88, y: 77.8), controlPoint1: CGPoint(x: 43.3, y: 77.8), controlPoint2: CGPoint(x: 43.68, y: 77.8)) + noticeShapePath.addCurve(to: CGPoint(x: 47.18, y: 78), controlPoint1: CGPoint(x: 45.04, y: 77.8), controlPoint2: CGPoint(x: 46.01, y: 78)) + noticeShapePath.addLine(to: CGPoint(x: 48.34, y: 78)) + noticeShapePath.addLine(to: CGPoint(x: 48.34, y: 78)) + noticeShapePath.addCurve(to: CGPoint(x: 71.61, y: 52.08), controlPoint1: CGPoint(x: 56.48, y: 78), controlPoint2: CGPoint(x: 69.87, y: 75.05)) + noticeShapePath.addCurve(to: CGPoint(x: 72, y: 48.54), controlPoint1: CGPoint(x: 71.81, y: 51.29), controlPoint2: CGPoint(x: 72, y: 49.72)) + noticeShapePath.close() + noticeShapePath.miterLimit = 4; + + UIColor.white.setFill() + noticeShapePath.fill() + } + + class func drawWarning() { + // Color Declarations + let greyColor = UIColor(red: 0.236, green: 0.236, blue: 0.236, alpha: 1.000) + + // Warning Group + // Warning Circle Drawing + let warningCirclePath = UIBezierPath() + warningCirclePath.move(to: CGPoint(x: 40.94, y: 63.39)) + warningCirclePath.addCurve(to: CGPoint(x: 36.03, y: 65.55), controlPoint1: CGPoint(x: 39.06, y: 63.39), controlPoint2: CGPoint(x: 37.36, y: 64.18)) + warningCirclePath.addCurve(to: CGPoint(x: 34.14, y: 70.45), controlPoint1: CGPoint(x: 34.9, y: 66.92), controlPoint2: CGPoint(x: 34.14, y: 68.49)) + warningCirclePath.addCurve(to: CGPoint(x: 36.22, y: 75.54), controlPoint1: CGPoint(x: 34.14, y: 72.41), controlPoint2: CGPoint(x: 34.9, y: 74.17)) + warningCirclePath.addCurve(to: CGPoint(x: 40.94, y: 77.5), controlPoint1: CGPoint(x: 37.54, y: 76.91), controlPoint2: CGPoint(x: 39.06, y: 77.5)) + warningCirclePath.addCurve(to: CGPoint(x: 45.86, y: 75.35), controlPoint1: CGPoint(x: 42.83, y: 77.5), controlPoint2: CGPoint(x: 44.53, y: 76.72)) + warningCirclePath.addCurve(to: CGPoint(x: 47.93, y: 70.45), controlPoint1: CGPoint(x: 47.18, y: 74.17), controlPoint2: CGPoint(x: 47.93, y: 72.41)) + warningCirclePath.addCurve(to: CGPoint(x: 45.86, y: 65.35), controlPoint1: CGPoint(x: 47.93, y: 68.49), controlPoint2: CGPoint(x: 47.18, y: 66.72)) + warningCirclePath.addCurve(to: CGPoint(x: 40.94, y: 63.39), controlPoint1: CGPoint(x: 44.53, y: 64.18), controlPoint2: CGPoint(x: 42.83, y: 63.39)) + warningCirclePath.close() + warningCirclePath.miterLimit = 4; + + greyColor.setFill() + warningCirclePath.fill() + + + // Warning Shape Drawing + let warningShapePath = UIBezierPath() + warningShapePath.move(to: CGPoint(x: 46.23, y: 4.26)) + warningShapePath.addCurve(to: CGPoint(x: 40.94, y: 2.5), controlPoint1: CGPoint(x: 44.91, y: 3.09), controlPoint2: CGPoint(x: 43.02, y: 2.5)) + warningShapePath.addCurve(to: CGPoint(x: 34.71, y: 4.26), controlPoint1: CGPoint(x: 38.68, y: 2.5), controlPoint2: CGPoint(x: 36.03, y: 3.09)) + warningShapePath.addCurve(to: CGPoint(x: 31.5, y: 8.77), controlPoint1: CGPoint(x: 33.01, y: 5.44), controlPoint2: CGPoint(x: 31.5, y: 7.01)) + warningShapePath.addLine(to: CGPoint(x: 31.5, y: 19.36)) + warningShapePath.addLine(to: CGPoint(x: 34.71, y: 54.44)) + warningShapePath.addCurve(to: CGPoint(x: 40.38, y: 58.16), controlPoint1: CGPoint(x: 34.9, y: 56.2), controlPoint2: CGPoint(x: 36.41, y: 58.16)) + warningShapePath.addCurve(to: CGPoint(x: 45.67, y: 54.44), controlPoint1: CGPoint(x: 44.34, y: 58.16), controlPoint2: CGPoint(x: 45.67, y: 56.01)) + warningShapePath.addLine(to: CGPoint(x: 48.5, y: 19.36)) + warningShapePath.addLine(to: CGPoint(x: 48.5, y: 8.77)) + warningShapePath.addCurve(to: CGPoint(x: 46.23, y: 4.26), controlPoint1: CGPoint(x: 48.5, y: 7.01), controlPoint2: CGPoint(x: 47.74, y: 5.44)) + warningShapePath.close() + warningShapePath.miterLimit = 4; + + greyColor.setFill() + warningShapePath.fill() + } + + class func drawInfo() { + // Color Declarations + let color0 = UIColor(red: 1.000, green: 1.000, blue: 1.000, alpha: 1.000) + + // Info Shape Drawing + let infoShapePath = UIBezierPath() + infoShapePath.move(to: CGPoint(x: 45.66, y: 15.96)) + infoShapePath.addCurve(to: CGPoint(x: 45.66, y: 5.22), controlPoint1: CGPoint(x: 48.78, y: 12.99), controlPoint2: CGPoint(x: 48.78, y: 8.19)) + infoShapePath.addCurve(to: CGPoint(x: 34.34, y: 5.22), controlPoint1: CGPoint(x: 42.53, y: 2.26), controlPoint2: CGPoint(x: 37.47, y: 2.26)) + infoShapePath.addCurve(to: CGPoint(x: 34.34, y: 15.96), controlPoint1: CGPoint(x: 31.22, y: 8.19), controlPoint2: CGPoint(x: 31.22, y: 12.99)) + infoShapePath.addCurve(to: CGPoint(x: 45.66, y: 15.96), controlPoint1: CGPoint(x: 37.47, y: 18.92), controlPoint2: CGPoint(x: 42.53, y: 18.92)) + infoShapePath.close() + infoShapePath.move(to: CGPoint(x: 48, y: 69.41)) + infoShapePath.addCurve(to: CGPoint(x: 40, y: 77), controlPoint1: CGPoint(x: 48, y: 73.58), controlPoint2: CGPoint(x: 44.4, y: 77)) + infoShapePath.addLine(to: CGPoint(x: 40, y: 77)) + infoShapePath.addCurve(to: CGPoint(x: 32, y: 69.41), controlPoint1: CGPoint(x: 35.6, y: 77), controlPoint2: CGPoint(x: 32, y: 73.58)) + infoShapePath.addLine(to: CGPoint(x: 32, y: 35.26)) + infoShapePath.addCurve(to: CGPoint(x: 40, y: 27.67), controlPoint1: CGPoint(x: 32, y: 31.08), controlPoint2: CGPoint(x: 35.6, y: 27.67)) + infoShapePath.addLine(to: CGPoint(x: 40, y: 27.67)) + infoShapePath.addCurve(to: CGPoint(x: 48, y: 35.26), controlPoint1: CGPoint(x: 44.4, y: 27.67), controlPoint2: CGPoint(x: 48, y: 31.08)) + infoShapePath.addLine(to: CGPoint(x: 48, y: 69.41)) + infoShapePath.close() + color0.setFill() + infoShapePath.fill() + } + + class func drawEdit() { + // Color Declarations + let color = UIColor(red:1.0, green:1.0, blue:1.0, alpha:1.0) + + // Edit shape Drawing + let editPathPath = UIBezierPath() + editPathPath.move(to: CGPoint(x: 71, y: 2.7)) + editPathPath.addCurve(to: CGPoint(x: 71.9, y: 15.2), controlPoint1: CGPoint(x: 74.7, y: 5.9), controlPoint2: CGPoint(x: 75.1, y: 11.6)) + editPathPath.addLine(to: CGPoint(x: 64.5, y: 23.7)) + editPathPath.addLine(to: CGPoint(x: 49.9, y: 11.1)) + editPathPath.addLine(to: CGPoint(x: 57.3, y: 2.6)) + editPathPath.addCurve(to: CGPoint(x: 69.7, y: 1.7), controlPoint1: CGPoint(x: 60.4, y: -1.1), controlPoint2: CGPoint(x: 66.1, y: -1.5)) + editPathPath.addLine(to: CGPoint(x: 71, y: 2.7)) + editPathPath.addLine(to: CGPoint(x: 71, y: 2.7)) + editPathPath.close() + editPathPath.move(to: CGPoint(x: 47.8, y: 13.5)) + editPathPath.addLine(to: CGPoint(x: 13.4, y: 53.1)) + editPathPath.addLine(to: CGPoint(x: 15.7, y: 55.1)) + editPathPath.addLine(to: CGPoint(x: 50.1, y: 15.5)) + editPathPath.addLine(to: CGPoint(x: 47.8, y: 13.5)) + editPathPath.addLine(to: CGPoint(x: 47.8, y: 13.5)) + editPathPath.close() + editPathPath.move(to: CGPoint(x: 17.7, y: 56.7)) + editPathPath.addLine(to: CGPoint(x: 23.8, y: 62.2)) + editPathPath.addLine(to: CGPoint(x: 58.2, y: 22.6)) + editPathPath.addLine(to: CGPoint(x: 52, y: 17.1)) + editPathPath.addLine(to: CGPoint(x: 17.7, y: 56.7)) + editPathPath.addLine(to: CGPoint(x: 17.7, y: 56.7)) + editPathPath.close() + editPathPath.move(to: CGPoint(x: 25.8, y: 63.8)) + editPathPath.addLine(to: CGPoint(x: 60.1, y: 24.2)) + editPathPath.addLine(to: CGPoint(x: 62.3, y: 26.1)) + editPathPath.addLine(to: CGPoint(x: 28.1, y: 65.7)) + editPathPath.addLine(to: CGPoint(x: 25.8, y: 63.8)) + editPathPath.addLine(to: CGPoint(x: 25.8, y: 63.8)) + editPathPath.close() + editPathPath.move(to: CGPoint(x: 25.9, y: 68.1)) + editPathPath.addLine(to: CGPoint(x: 4.2, y: 79.5)) + editPathPath.addLine(to: CGPoint(x: 11.3, y: 55.5)) + editPathPath.addLine(to: CGPoint(x: 25.9, y: 68.1)) + editPathPath.close() + editPathPath.miterLimit = 4; + editPathPath.usesEvenOddFillRule = true; + color.setFill() + editPathPath.fill() + } + + // Generated Images + class var imageOfCheckmark: UIImage { + if (Cache.imageOfCheckmark != nil) { + return Cache.imageOfCheckmark! + } + UIGraphicsBeginImageContextWithOptions(CGSize(width: 80, height: 80), false, 0) + SCLAlertViewStyleKit.drawCheckmark() + Cache.imageOfCheckmark = UIGraphicsGetImageFromCurrentImageContext() + UIGraphicsEndImageContext() + return Cache.imageOfCheckmark! + } + + class var imageOfCross: UIImage { + if (Cache.imageOfCross != nil) { + return Cache.imageOfCross! + } + UIGraphicsBeginImageContextWithOptions(CGSize(width: 80, height: 80), false, 0) + SCLAlertViewStyleKit.drawCross() + Cache.imageOfCross = UIGraphicsGetImageFromCurrentImageContext() + UIGraphicsEndImageContext() + return Cache.imageOfCross! + } + + class var imageOfNotice: UIImage { + if (Cache.imageOfNotice != nil) { + return Cache.imageOfNotice! + } + UIGraphicsBeginImageContextWithOptions(CGSize(width: 80, height: 80), false, 0) + SCLAlertViewStyleKit.drawNotice() + Cache.imageOfNotice = UIGraphicsGetImageFromCurrentImageContext() + UIGraphicsEndImageContext() + return Cache.imageOfNotice! + } + + class var imageOfWarning: UIImage { + if (Cache.imageOfWarning != nil) { + return Cache.imageOfWarning! + } + UIGraphicsBeginImageContextWithOptions(CGSize(width: 80, height: 80), false, 0) + SCLAlertViewStyleKit.drawWarning() + Cache.imageOfWarning = UIGraphicsGetImageFromCurrentImageContext() + UIGraphicsEndImageContext() + return Cache.imageOfWarning! + } + + class var imageOfInfo: UIImage { + if (Cache.imageOfInfo != nil) { + return Cache.imageOfInfo! + } + UIGraphicsBeginImageContextWithOptions(CGSize(width: 80, height: 80), false, 0) + SCLAlertViewStyleKit.drawInfo() + Cache.imageOfInfo = UIGraphicsGetImageFromCurrentImageContext() + UIGraphicsEndImageContext() + return Cache.imageOfInfo! + } + + class var imageOfEdit: UIImage { + if (Cache.imageOfEdit != nil) { + return Cache.imageOfEdit! + } + UIGraphicsBeginImageContextWithOptions(CGSize(width: 80, height: 80), false, 0) + SCLAlertViewStyleKit.drawEdit() + Cache.imageOfEdit = UIGraphicsGetImageFromCurrentImageContext() + UIGraphicsEndImageContext() + return Cache.imageOfEdit! + } +} diff --git a/GeneralUtils/GeneralUtils/libs/SCLAlertView/SCLExtensions.swift b/GeneralUtils/GeneralUtils/libs/SCLAlertView/SCLExtensions.swift new file mode 100644 index 0000000..58ebb95 --- /dev/null +++ b/GeneralUtils/GeneralUtils/libs/SCLAlertView/SCLExtensions.swift @@ -0,0 +1,41 @@ +// +// SCLExtensions.swift +// SCLAlertView +// +// Created by Christian Cabarrocas on 16/04/16. +// Copyright © 2016 Alexey Poimtsev. All rights reserved. +// + +import UIKit + +extension Int { + + func toUIColor() -> UIColor { + return UIColor( + red: CGFloat((self & 0xFF0000) >> 16) / 255.0, + green: CGFloat((self & 0x00FF00) >> 8) / 255.0, + blue: CGFloat(self & 0x0000FF) / 255.0, + alpha: CGFloat(1.0) + ) + } + + func toCGColor() -> CGColor { + return self.toUIColor().cgColor + } +} + +extension UInt { + + func toUIColor() -> UIColor { + return UIColor( + red: CGFloat((self & 0xFF0000) >> 16) / 255.0, + green: CGFloat((self & 0x00FF00) >> 8) / 255.0, + blue: CGFloat(self & 0x0000FF) / 255.0, + alpha: CGFloat(1.0) + ) + } + + func toCGColor() -> CGColor { + return self.toUIColor().cgColor + } +} diff --git a/GeneralUtils/GeneralUtils/libs/SwiftOverlays.swift b/GeneralUtils/GeneralUtils/libs/SwiftOverlays.swift new file mode 100644 index 0000000..e892b4b --- /dev/null +++ b/GeneralUtils/GeneralUtils/libs/SwiftOverlays.swift @@ -0,0 +1,560 @@ +// +// SwiftOverlays.swift +// SwiftTest +// +// Created by Peter Prokop on 15/10/14. +// Copyright (c) 2014 Peter Prokop. All rights reserved. +// + +import Foundation +import UIKit + + +// For convenience methods +public extension UIViewController { + + /** + Shows wait overlay with activity indicator, centered in the view controller's main view + + Do not use this method for **UITableViewController** or **UICollectionViewController** + + - returns: Created overlay + */ + @discardableResult + func showWaitOverlay(isBlockTouch: Bool = false) -> UIView { + if isBlockTouch { + let blocker = SwiftOverlays.addWindowBlocker(parent: self.view) + return SwiftOverlays.showCenteredWaitOverlay(blocker) + } + return SwiftOverlays.showCenteredWaitOverlay(self.view) + } + + /** + Shows wait overlay with activity indicator *and text*, centered in the view controller's main view + + Do not use this method for **UITableViewController** or **UICollectionViewController** + + - parameter text: Text to be shown on overlay + + - returns: Created overlay + */ + @discardableResult + func showWaitOverlayWithText(_ text: String, increaseW: Int = 0) -> UILabel { + return SwiftOverlays.showCenteredWaitOverlayWithText(self.view, text: text, increaseW: increaseW) + } + + /** + Shows *text-only* overlay, centered in the view controller's main view + + Do not use this method for **UITableViewController** or **UICollectionViewController** + + - parameter text: Text to be shown on overlay + + - returns: Created overlay + */ + @discardableResult + func showTextOverlay(_ text: String) -> UIView { + return SwiftOverlays.showTextOverlay(self.view, text: text) + } + + /** + Shows overlay with text and progress bar, centered in the view controller's main view + + Do not use this method for **UITableViewController** or **UICollectionViewController** + + - parameter text: Text to be shown on overlay + + - returns: Created overlay + */ + @discardableResult + func showProgressOverlay(_ text: String) -> UIView { + return SwiftOverlays.showProgressOverlay(self.view, text: text) + } + + /** + Shows overlay *with image and text*, centered in the view controller's main view + + Do not use this method for **UITableViewController** or **UICollectionViewController** + + - parameter image: Image to be added to overlay + - parameter text: Text to be shown on overlay + + - returns: Created overlay + */ + @discardableResult + func showImageAndTextOverlay(_ image: UIImage, text: String) -> UIView { + return SwiftOverlays.showImageAndTextOverlay(self.view, image: image, text: text) + } + + /** + Shows notification on top of the status bar, similar to native local or remote notifications + + - parameter notificationView: View that will be shown as notification + - parameter duration: Amount of time until notification disappears + - parameter animated: Should appearing be animated + */ + @discardableResult + class func showNotificationOnTopOfStatusBar(_ notificationView: UIView, duration: TimeInterval, animated: Bool = true) { + SwiftOverlays.showAnnoyingNotificationOnTopOfStatusBar(notificationView, duration: duration, animated: animated) + } + + /** + Removes all overlays from view controller's main view + */ + func removeAllOverlays() { + SwiftOverlays.removeAllOverlaysFromView(self.view) + } + + /** + Updates text on the current overlay. + Does nothing if no overlay is present. + + - parameter text: Text to set + */ + func updateOverlayText(_ text: String) { + SwiftOverlays.updateOverlayText(self.view, text: text) + } + + /** + Updates progress on the current overlay. + Does nothing if no overlay is present. + + - parameter progress: Progress to set 0.0 .. 1.0 + */ + func updateOverlayProgress(_ progress: Float) { + SwiftOverlays.updateOverlayProgress(self.view, progress: progress) + } +} + +open class SwiftOverlays: NSObject { + // You can customize these values + + // Some random number + static let containerViewTag = 456987123 + + static let cornerRadius = CGFloat(10) + static let padding = CGFloat(10) + + static let backgroundColor = UIColor(red: 0, green: 0, blue: 0, alpha: 0.7) + static let textColor = UIColor(red: 1, green: 1, blue: 1, alpha: 1) + static let font = UIFont.systemFont(ofSize: 14) + + // Annoying notifications on top of status bar + static let bannerDissapearAnimationDuration = 0.5 + + static var bannerWindow : UIWindow? + + open class Utils { + + /** + Adds autolayout constraints to innerView to center it in its superview and fix its size. + `innerView` should have a superview. + + - parameter innerView: View to set constraints on + */ + open static func centerViewInSuperview(_ view: UIView) { + assert(view.superview != nil, "`view` should have a superview") + + view.translatesAutoresizingMaskIntoConstraints = false + + let constraintH = NSLayoutConstraint(item: view, + attribute: NSLayoutAttribute.centerX, + relatedBy: NSLayoutRelation.equal, + toItem: view.superview, + attribute: NSLayoutAttribute.centerX, + multiplier: 1, + constant: 0) + let constraintV = NSLayoutConstraint(item: view, + attribute: NSLayoutAttribute.centerY, + relatedBy: NSLayoutRelation.equal, + toItem: view.superview, + attribute: NSLayoutAttribute.centerY, + multiplier: 1, + constant: 0) + let constraintWidth = NSLayoutConstraint(item: view, + attribute: NSLayoutAttribute.width, + relatedBy: NSLayoutRelation.equal, + toItem: nil, + attribute: NSLayoutAttribute.notAnAttribute, + multiplier: 1, + constant: view.frame.size.width) + let constraintHeight = NSLayoutConstraint(item: view, + attribute: NSLayoutAttribute.height, + relatedBy: NSLayoutRelation.equal, + toItem: nil, + attribute: NSLayoutAttribute.notAnAttribute, + multiplier: 1, + constant: view.frame.size.height) + view.superview!.addConstraints([constraintV, constraintH, constraintWidth, constraintHeight]) + } + } + + // MARK: - Public class methods - + + // MARK: Blocking + + /** + Shows *blocking* wait overlay with activity indicator, centered in the app's main window + + - returns: Created overlay + */ + @discardableResult + open class func showBlockingWaitOverlay() -> UIView { + let blocker = addMainWindowBlocker() + showCenteredWaitOverlay(blocker) + + return blocker + } + + /** + Shows wait overlay with activity indicator *and text*, centered in the app's main window + + - parameter text: Text to be shown on overlay + + - returns: Created overlay + */ + @discardableResult + open class func showBlockingWaitOverlayWithText(_ text: String) -> UILabel { + let blocker = addMainWindowBlocker() + return showCenteredWaitOverlayWithText(blocker, text: text, increaseW: 40) + +// return blocker + } + + /** + Shows *blocking* overlay *with image and text*,, centered in the app's main window + + - parameter image: Image to be added to overlay + - parameter text: Text to be shown on overlay + + - returns: Created overlay + */ + open class func showBlockingImageAndTextOverlay(_ image: UIImage, text: String) -> UIView { + let blocker = addMainWindowBlocker() + showImageAndTextOverlay(blocker, image: image, text: text) + + return blocker + } + + /** + Shows *text-only* overlay, centered in the app's main window + + - parameter text: Text to be shown on overlay + + - returns: Created overlay + */ + open class func showBlockingTextOverlay(_ text: String) -> UIView { + let blocker = addMainWindowBlocker() + showTextOverlay(blocker, text: text) + + return blocker + } + + /** + Removes all *blocking* overlays from application's main window + */ + open class func removeAllBlockingOverlays() { + let window = UIApplication.shared.delegate!.window!! + removeAllOverlaysFromView(window) + } + + // MARK: Non-blocking + @discardableResult + open class func showCenteredWaitOverlay(_ parentView: UIView) -> UIView { + let ai = UIActivityIndicatorView(activityIndicatorStyle: UIActivityIndicatorViewStyle.whiteLarge) + ai.startAnimating() + + let containerViewRect = CGRect(x: 0, + y: 0, + width: ai.frame.size.width * 2, + height: ai.frame.size.height * 2) + + let containerView = UIView(frame: containerViewRect) + + containerView.tag = containerViewTag + containerView.layer.cornerRadius = cornerRadius + containerView.backgroundColor = backgroundColor + containerView.center = CGPoint(x: parentView.bounds.size.width/2, + y: parentView.bounds.size.height/2); + + ai.center = CGPoint(x: containerView.bounds.size.width/2, + y: containerView.bounds.size.height/2); + + containerView.addSubview(ai) + + parentView.addSubview(containerView) + + Utils.centerViewInSuperview(containerView) + + return containerView + } + + @discardableResult + open class func showCenteredWaitOverlayWithText(_ parentView: UIView, text: String, increaseW: Int = 0) -> UILabel { + let ai = UIActivityIndicatorView(activityIndicatorStyle: UIActivityIndicatorViewStyle.white) + ai.startAnimating() + + return showGenericOverlay(parentView, text: text, accessoryView: ai, increaseW: increaseW) + } + + @discardableResult + open class func showImageAndTextOverlay(_ parentView: UIView, image: UIImage, text: String) -> UILabel { + let imageView = UIImageView(image: image) + + return showGenericOverlay(parentView, text: text, accessoryView: imageView) + } + + open class func showGenericOverlay(_ parentView: UIView, text: String, accessoryView: UIView, horizontalLayout: Bool = true, increaseW: Int = 0) -> UILabel { + let label = labelForText(text, increaseW: increaseW) + var actualSize = CGSize.zero + + if horizontalLayout { + actualSize = CGSize(width: accessoryView.frame.size.width + label.frame.size.width + padding * 3, + height: max(label.frame.size.height, accessoryView.frame.size.height) + padding * 2) + + label.frame = label.frame.offsetBy(dx: accessoryView.frame.size.width + padding * 2, dy: padding) + + accessoryView.frame = accessoryView.frame.offsetBy(dx: padding, dy: (actualSize.height - accessoryView.frame.size.height)/2) + } else { + actualSize = CGSize(width: max(accessoryView.frame.size.width, label.frame.size.width) + padding * 2, + height: label.frame.size.height + accessoryView.frame.size.height + padding * 3) + + label.frame = label.frame.offsetBy(dx: padding, dy: accessoryView.frame.size.height + padding * 2) + + accessoryView.frame = accessoryView.frame.offsetBy(dx: (actualSize.width - accessoryView.frame.size.width)/2, dy: padding) + } + + // Container view + let containerViewRect = CGRect(x: 0, + y: 0, + width: actualSize.width, + height: actualSize.height) + + let containerView = UIView(frame: containerViewRect) + + containerView.tag = containerViewTag + containerView.layer.cornerRadius = cornerRadius + containerView.backgroundColor = backgroundColor + containerView.center = CGPoint(x: parentView.bounds.size.width/2, + y: parentView.bounds.size.height/2) + + containerView.addSubview(accessoryView) + containerView.addSubview(label) + + parentView.addSubview(containerView) + + Utils.centerViewInSuperview(containerView) + + return label + } + + @discardableResult + open class func showTextOverlay(_ parentView: UIView, text: String) -> UIView { + let label = labelForText(text) + label.frame = label.frame.offsetBy(dx: padding, dy: padding) + + let actualSize = CGSize(width: label.frame.size.width + padding * 2, + height: label.frame.size.height + padding * 2) + + // Container view + let containerViewRect = CGRect(x: 0, + y: 0, + width: actualSize.width, + height: actualSize.height) + + let containerView = UIView(frame: containerViewRect) + + containerView.tag = containerViewTag + containerView.layer.cornerRadius = cornerRadius + containerView.backgroundColor = backgroundColor + containerView.center = CGPoint(x: parentView.bounds.size.width/2, + y: parentView.bounds.size.height/2); + + containerView.addSubview(label) + + parentView.addSubview(containerView) + + Utils.centerViewInSuperview(containerView) + + + return containerView + } + + open class func showProgressOverlay(_ parentView: UIView, text: String) -> UILabel { + let pv = UIProgressView(progressViewStyle: .default) + return showGenericOverlay(parentView, text: text, accessoryView: pv, horizontalLayout: false) + } + + open class func removeAllOverlaysFromView(_ parentView: UIView) { + var overlay: UIView? + + while true { + overlay = parentView.viewWithTag(containerViewTag) + if overlay == nil { + break + } + + overlay!.removeFromSuperview() + } + } + + open class func updateOverlayText(_ parentView: UIView, text: String) { + if let overlay = parentView.viewWithTag(containerViewTag) { + for subview in overlay.subviews { + if let label = subview as? UILabel { + label.text = text as String + break + } + } + } + } + + open class func updateOverlayProgress(_ parentView: UIView, progress: Float) { + if let overlay = parentView.viewWithTag(containerViewTag) { + for subview in overlay.subviews { + if let pv = subview as? UIProgressView { + pv.progress = progress + break + } + } + } + } + + // MARK: Status bar notification + + open class func showAnnoyingNotificationOnTopOfStatusBar(_ notificationView: UIView, duration: TimeInterval, animated: Bool = true) { + if bannerWindow == nil { + bannerWindow = UIWindow() + bannerWindow!.windowLevel = UIWindowLevelStatusBar + 1 + bannerWindow!.backgroundColor = UIColor.clear + } + + bannerWindow!.frame = CGRect(x: 0, y: 0, width: UIScreen.main.bounds.size.width, height: notificationView.frame.size.height) + bannerWindow!.isHidden = false + + let selector = #selector(closeAnnoyingNotificationOnTopOfStatusBar) + let gestureRecognizer = UITapGestureRecognizer(target: self, action: selector) + notificationView.addGestureRecognizer(gestureRecognizer) + + bannerWindow!.addSubview(notificationView) + + if animated { + let frame = notificationView.frame + let origin = CGPoint(x: 0, y: -frame.height) + notificationView.frame = CGRect(origin: origin, size: frame.size) + + // Show appearing animation, schedule calling closing selector after completed + UIView.animate(withDuration: bannerDissapearAnimationDuration, animations: { + let frame = notificationView.frame + notificationView.frame = frame.offsetBy(dx: 0, dy: frame.height) + }, completion: { (finished) in + self.perform(selector, with: notificationView, afterDelay: duration) + }) + } else { + // Schedule calling closing selector right away + self.perform(selector, with: notificationView, afterDelay: duration) + } + } + + open class func closeAnnoyingNotificationOnTopOfStatusBar(_ sender: AnyObject) { + NSObject.cancelPreviousPerformRequests(withTarget: self) + + var notificationView: UIView? + + if sender.isKind(of: UITapGestureRecognizer.self) { + notificationView = (sender as! UITapGestureRecognizer).view! + } else if sender.isKind(of: UIView.self) { + notificationView = (sender as! UIView) + } + + UIView.animate(withDuration: bannerDissapearAnimationDuration, + animations: { () -> Void in + if let frame = notificationView?.frame { + notificationView?.frame = frame.offsetBy(dx: 0, dy: -frame.size.height) + } + }, + completion: { (finished) -> Void in + notificationView?.removeFromSuperview() + + bannerWindow?.isHidden = true + } + ) + } + + // MARK: - Private class methods - + + fileprivate class func labelForText(_ text: String, increaseW: Int = 0) -> UILabel { + let textSize = text.size(attributes: [NSFontAttributeName: font]) + + let labelRect = CGRect(x: 0, + y: 0, + width: textSize.width + CGFloat(increaseW), + height: textSize.height) + + let label = UILabel(frame: labelRect) + label.font = font + label.textColor = textColor + label.text = text as String + label.numberOfLines = 0 + + return label; + } + + fileprivate class func addMainWindowBlocker() -> UIView { + let window = UIApplication.shared.delegate!.window!! + + let blocker = UIView(frame: window.bounds) + blocker.backgroundColor = backgroundColor + blocker.tag = containerViewTag + + blocker.translatesAutoresizingMaskIntoConstraints = false + + window.addSubview(blocker) + + let viewsDictionary = ["blocker": blocker] + + // Add constraints to handle orientation change + let constraintsV = NSLayoutConstraint.constraints(withVisualFormat: "V:|-0-[blocker]-0-|", + options: NSLayoutFormatOptions(rawValue: 0), + metrics: nil, + views: viewsDictionary) + + let constraintsH = NSLayoutConstraint.constraints(withVisualFormat: "|-0-[blocker]-0-|", + options: NSLayoutFormatOptions(rawValue: 0), + metrics: nil, + views: viewsDictionary) + + window.addConstraints(constraintsV + constraintsH) + + return blocker + } + + fileprivate class func addWindowBlocker(parent: UIView) -> UIView { + let window = parent + + let blocker = UIView(frame: window.bounds) + blocker.backgroundColor = backgroundColor + blocker.tag = containerViewTag + + blocker.translatesAutoresizingMaskIntoConstraints = false + + window.addSubview(blocker) + + let viewsDictionary = ["blocker": blocker] + + // Add constraints to handle orientation change + let constraintsV = NSLayoutConstraint.constraints(withVisualFormat: "V:|-0-[blocker]-0-|", + options: NSLayoutFormatOptions(rawValue: 0), + metrics: nil, + views: viewsDictionary) + + let constraintsH = NSLayoutConstraint.constraints(withVisualFormat: "|-0-[blocker]-0-|", + options: NSLayoutFormatOptions(rawValue: 0), + metrics: nil, + views: viewsDictionary) + + window.addConstraints(constraintsV + constraintsH) + + return blocker + } +} diff --git a/GeneralUtils/GeneralUtils/libs/SwiftyJSON.swift b/GeneralUtils/GeneralUtils/libs/SwiftyJSON.swift new file mode 100644 index 0000000..3cf9e00 --- /dev/null +++ b/GeneralUtils/GeneralUtils/libs/SwiftyJSON.swift @@ -0,0 +1,1344 @@ +// SwiftyJSON.swift +// +// Copyright (c) 2014 - 2016 Ruoyu Fu, Pinglin Tang +// +// Permission is hereby granted, free of charge, to any person obtaining a copy +// of this software and associated documentation files (the "Software"), to deal +// in the Software without restriction, including without limitation the rights +// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +// copies of the Software, and to permit persons to whom the Software is +// furnished to do so, subject to the following conditions: +// +// The above copyright notice and this permission notice shall be included in +// all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN +// THE SOFTWARE. + +import Foundation + +// MARK: - Error + +///Error domain +public let ErrorDomain: String = "SwiftyJSONErrorDomain" + +///Error code +public let ErrorUnsupportedType: Int = 999 +public let ErrorIndexOutOfBounds: Int = 900 +public let ErrorWrongType: Int = 901 +public let ErrorNotExist: Int = 500 +public let ErrorInvalidJSON: Int = 490 + +// MARK: - JSON Type + +/** + JSON's type definitions. + + See http://www.json.org + */ +public enum Type :Int{ + + case number + case string + case bool + case array + case dictionary + case null + case unknown +} + +// MARK: - JSON Base +public struct JSON { + + /** + Creates a JSON using the data. + + - parameter data: The NSData used to convert to json.Top level object in data is an NSArray or NSDictionary + - parameter opt: The JSON serialization reading options. `.AllowFragments` by default. + - parameter error: The NSErrorPointer used to return the error. `nil` by default. + + - returns: The created JSON + */ + public init(data:Data, options opt: JSONSerialization.ReadingOptions = .allowFragments, error: NSErrorPointer = nil) { + do { + let object: Any = try JSONSerialization.jsonObject(with: data, options: opt) + self.init(object) + } catch let aError as NSError { + if error != nil { + error?.pointee = aError + } + self.init(NSNull()) + } + } + + /** + Creates a JSON from JSON string + - parameter string: Normal json string like '{"a":"b"}' + + - returns: The created JSON + */ + public static func parse(_ string:String) -> JSON { + return string.data(using: String.Encoding.utf8) + .flatMap{ JSON(data: $0) } ?? JSON(NSNull()) + } + + /** + Creates a JSON using the object. + + - parameter object: The object must have the following properties: All objects are NSString/String, NSNumber/Int/Float/Double/Bool, NSArray/Array, NSDictionary/Dictionary, or NSNull; All dictionary keys are NSStrings/String; NSNumbers are not NaN or infinity. + + - returns: The created JSON + */ + public init(_ object: Any) { + self.object = object + } + + /** + Creates a JSON from a [JSON] + + - parameter jsonArray: A Swift array of JSON objects + + - returns: The created JSON + */ + public init(_ jsonArray:[JSON]) { + self.init(jsonArray.map { $0.object }) + } + + /** + Creates a JSON from a [String: JSON] + + - parameter jsonDictionary: A Swift dictionary of JSON objects + + - returns: The created JSON + */ + public init(_ jsonDictionary:[String: JSON]) { + var dictionary = [String: Any](minimumCapacity: jsonDictionary.count) + for (key, json) in jsonDictionary { + dictionary[key] = json.object + } + self.init(dictionary) + } + + /// Private object + fileprivate var rawArray: [Any] = [] + fileprivate var rawDictionary: [String : Any] = [:] + fileprivate var rawString: String = "" + fileprivate var rawNumber: NSNumber = 0 + fileprivate var rawNull: NSNull = NSNull() + fileprivate var rawBool: Bool = false + /// Private type + fileprivate var _type: Type = .null + /// prviate error + fileprivate var _error: NSError? = nil + + /// Object in JSON + public var object: Any { + get { + switch self.type { + case .array: + return self.rawArray + case .dictionary: + return self.rawDictionary + case .string: + return self.rawString + case .number: + return self.rawNumber + case .bool: + return self.rawBool + default: + return self.rawNull + } + } + set { + _error = nil + switch newValue { + case let number as NSNumber: + if number.isBool { + _type = .bool + self.rawBool = number.boolValue + } else { + _type = .number + self.rawNumber = number + } + case let string as String: + _type = .string + self.rawString = string + case _ as NSNull: + _type = .null + case let array as [JSON]: + _type = .array + self.rawArray = array.map { $0.object } + case let array as [Any]: + _type = .array + self.rawArray = array + case let dictionary as [String : Any]: + _type = .dictionary + self.rawDictionary = dictionary + default: + _type = .unknown + _error = NSError(domain: ErrorDomain, code: ErrorUnsupportedType, userInfo: [NSLocalizedDescriptionKey: "It is a unsupported type"]) + } + } + } + + /// JSON type + public var type: Type { get { return _type } } + + /// Error in JSON + public var error: NSError? { get { return self._error } } + + /// The static null JSON + @available(*, unavailable, renamed:"null") + public static var nullJSON: JSON { get { return null } } + public static var null: JSON { get { return JSON(NSNull()) } } +} + +public enum JSONIndex:Comparable +{ + case array(Int) + case dictionary(DictionaryIndex) + case null + + static public func ==(lhs: JSONIndex, rhs: JSONIndex) -> Bool + { + switch (lhs, rhs) + { + case (.array(let left), .array(let right)): + return left == right + case (.dictionary(let left), .dictionary(let right)): + return left == right + case (.null, .null): return true + default: + return false + } + } + + static public func <(lhs: JSONIndex, rhs: JSONIndex) -> Bool + { + switch (lhs, rhs) + { + case (.array(let left), .array(let right)): + return left < right + case (.dictionary(let left), .dictionary(let right)): + return left < right + default: + return false + } + } + +} + +public enum JSONRawIndex: Comparable +{ + case array(Int) + case dictionary(DictionaryIndex) + case null + + static public func ==(lhs: JSONRawIndex, rhs: JSONRawIndex) -> Bool + { + switch (lhs, rhs) + { + case (.array(let left), .array(let right)): + return left == right + case (.dictionary(let left), .dictionary(let right)): + return left == right + case (.null, .null): return true + default: + return false + } + } + + static public func <(lhs: JSONRawIndex, rhs: JSONRawIndex) -> Bool + { + switch (lhs, rhs) + { + case (.array(let left), .array(let right)): + return left < right + case (.dictionary(let left), .dictionary(let right)): + return left < right + default: + return false + } + } + + +} + +extension JSON: Collection +{ + + public typealias Index = JSONRawIndex + + public var startIndex: Index + { + switch type + { + case .array: + return .array(rawArray.startIndex) + case .dictionary: + return .dictionary(rawDictionary.startIndex) + default: + return .null + } + } + + public var endIndex: Index + { + switch type + { + case .array: + return .array(rawArray.endIndex) + case .dictionary: + return .dictionary(rawDictionary.endIndex) + default: + return .null + } + } + + public func index(after i: Index) -> Index + { + switch i + { + case .array(let idx): + return .array(rawArray.index(after: idx)) + case .dictionary(let idx): + return .dictionary(rawDictionary.index(after: idx)) + default: + return .null + } + + } + + public subscript (position: Index) -> (String, JSON) + { + switch position + { + case .array(let idx): + return (String(idx), JSON(self.rawArray[idx])) + case .dictionary(let idx): + let (key, value) = self.rawDictionary[idx] + return (key, JSON(value)) + default: + return ("", JSON.null) + } + } + + +} + +// MARK: - Subscript + +/** + * To mark both String and Int can be used in subscript. + */ +public enum JSONKey +{ + case index(Int) + case key(String) +} + +public protocol JSONSubscriptType { + var jsonKey:JSONKey { get } +} + +extension Int: JSONSubscriptType { + public var jsonKey:JSONKey { + return JSONKey.index(self) + } +} + +extension String: JSONSubscriptType { + public var jsonKey:JSONKey { + return JSONKey.key(self) + } +} + +extension JSON { + + /// If `type` is `.Array`, return json whose object is `array[index]`, otherwise return null json with error. + fileprivate subscript(index index: Int) -> JSON { + get { + if self.type != .array { + var r = JSON.null + r._error = self._error ?? NSError(domain: ErrorDomain, code: ErrorWrongType, userInfo: [NSLocalizedDescriptionKey: "Array[\(index)] failure, It is not an array"]) + return r + } else if index >= 0 && index < self.rawArray.count { + return JSON(self.rawArray[index]) + } else { + var r = JSON.null + r._error = NSError(domain: ErrorDomain, code:ErrorIndexOutOfBounds , userInfo: [NSLocalizedDescriptionKey: "Array[\(index)] is out of bounds"]) + return r + } + } + set { + if self.type == .array { + if self.rawArray.count > index && newValue.error == nil { + self.rawArray[index] = newValue.object + } + } + } + } + + /// If `type` is `.Dictionary`, return json whose object is `dictionary[key]` , otherwise return null json with error. + fileprivate subscript(key key: String) -> JSON { + get { + var r = JSON.null + if self.type == .dictionary { + if let o = self.rawDictionary[key] { + r = JSON(o) + } else { + r._error = NSError(domain: ErrorDomain, code: ErrorNotExist, userInfo: [NSLocalizedDescriptionKey: "Dictionary[\"\(key)\"] does not exist"]) + } + } else { + r._error = self._error ?? NSError(domain: ErrorDomain, code: ErrorWrongType, userInfo: [NSLocalizedDescriptionKey: "Dictionary[\"\(key)\"] failure, It is not an dictionary"]) + } + return r + } + set { + if self.type == .dictionary && newValue.error == nil { + self.rawDictionary[key] = newValue.object + } + } + } + + /// If `sub` is `Int`, return `subscript(index:)`; If `sub` is `String`, return `subscript(key:)`. + fileprivate subscript(sub sub: JSONSubscriptType) -> JSON { + get { + switch sub.jsonKey { + case .index(let index): return self[index: index] + case .key(let key): return self[key: key] + } + } + set { + switch sub.jsonKey { + case .index(let index): self[index: index] = newValue + case .key(let key): self[key: key] = newValue + } + } + } + + /** + Find a json in the complex data structures by using array of Int and/or String as path. + + - parameter path: The target json's path. Example: + + let json = JSON[data] + let path = [9,"list","person","name"] + let name = json[path] + + The same as: let name = json[9]["list"]["person"]["name"] + + - returns: Return a json found by the path or a null json with error + */ + public subscript(path: [JSONSubscriptType]) -> JSON { + get { + return path.reduce(self) { $0[sub: $1] } + } + set { + switch path.count { + case 0: + return + case 1: + self[sub:path[0]].object = newValue.object + default: + var aPath = path; aPath.remove(at: 0) + var nextJSON = self[sub: path[0]] + nextJSON[aPath] = newValue + self[sub: path[0]] = nextJSON + } + } + } + + /** + Find a json in the complex data structures by using array of Int and/or String as path. + + - parameter path: The target json's path. Example: + + let name = json[9,"list","person","name"] + + The same as: let name = json[9]["list"]["person"]["name"] + + - returns: Return a json found by the path or a null json with error + */ + public subscript(path: JSONSubscriptType...) -> JSON { + get { + return self[path] + } + set { + self[path] = newValue + } + } +} + +// MARK: - LiteralConvertible + +extension JSON: Swift.ExpressibleByStringLiteral { + + public init(stringLiteral value: StringLiteralType) { + self.init(value as Any) + } + + public init(extendedGraphemeClusterLiteral value: StringLiteralType) { + self.init(value as Any) + } + + public init(unicodeScalarLiteral value: StringLiteralType) { + self.init(value as Any) + } +} + +extension JSON: Swift.ExpressibleByIntegerLiteral { + + public init(integerLiteral value: IntegerLiteralType) { + self.init(value as Any) + } +} + +extension JSON: Swift.ExpressibleByBooleanLiteral { + + public init(booleanLiteral value: BooleanLiteralType) { + self.init(value as Any) + } +} + +extension JSON: Swift.ExpressibleByFloatLiteral { + + public init(floatLiteral value: FloatLiteralType) { + self.init(value as Any) + } +} + +extension JSON: Swift.ExpressibleByDictionaryLiteral { + public init(dictionaryLiteral elements: (String, Any)...) { + let array = elements + self.init(dictionaryLiteral: array) + } + + public init(dictionaryLiteral elements: [(String, Any)]) { + let jsonFromDictionaryLiteral: ([String : Any]) -> JSON = { dictionary in + let initializeElement = Array(dictionary.keys).flatMap { key -> (String, Any)? in + if let value = dictionary[key] { + return (key, value) + } + return nil + } + return JSON(dictionaryLiteral: initializeElement) + } + + var dict = [String : Any](minimumCapacity: elements.count) + + for element in elements { + let elementToSet: Any + if let json = element.1 as? JSON { + elementToSet = json.object + } else if let jsonArray = element.1 as? [JSON] { + elementToSet = JSON(jsonArray).object + } else if let dictionary = element.1 as? [String : Any] { + elementToSet = jsonFromDictionaryLiteral(dictionary).object + } else if let dictArray = element.1 as? [[String : Any]] { + let jsonArray = dictArray.map { jsonFromDictionaryLiteral($0) } + elementToSet = JSON(jsonArray).object + } else { + elementToSet = element.1 + } + dict[element.0] = elementToSet + } + + self.init(dict) + } +} + +extension JSON: Swift.ExpressibleByArrayLiteral { + + public init(arrayLiteral elements: Any...) { + self.init(elements as Any) + } +} + +extension JSON: Swift.ExpressibleByNilLiteral { + + @available(*, deprecated, message: "use JSON.null instead. Will be removed in future versions") + public init(nilLiteral: ()) { + self.init(NSNull() as Any) + } +} + +// MARK: - Raw + +extension JSON: Swift.RawRepresentable { + + public init?(rawValue: Any) { + if JSON(rawValue).type == .unknown { + return nil + } else { + self.init(rawValue) + } + } + + public var rawValue: Any { + return self.object + } + + public func rawData(options opt: JSONSerialization.WritingOptions = JSONSerialization.WritingOptions(rawValue: 0)) throws -> Data { + guard JSONSerialization.isValidJSONObject(self.object) else { + throw NSError(domain: ErrorDomain, code: ErrorInvalidJSON, userInfo: [NSLocalizedDescriptionKey: "JSON is invalid"]) + } + + return try JSONSerialization.data(withJSONObject: self.object, options: opt) + } + + public func rawString(_ encoding: String.Encoding = String.Encoding.utf8, options opt: JSONSerialization.WritingOptions = .prettyPrinted) -> String? { + switch self.type { + case .array, .dictionary: + do { + let data = try self.rawData(options: opt) + return String(data: data, encoding: encoding) + } catch _ { + return nil + } + case .string: + return self.rawString + case .number: + return self.rawNumber.stringValue + case .bool: + return self.rawBool.description + case .null: + return "null" + default: + return nil + } + } +} + +// MARK: - Printable, DebugPrintable + +extension JSON: Swift.CustomStringConvertible, Swift.CustomDebugStringConvertible { + + public var description: String { + if let string = self.rawString(options:.prettyPrinted) { + return string + } else { + return "unknown" + } + } + + public var debugDescription: String { + return description + } +} + +// MARK: - Array + +extension JSON { + + //Optional [JSON] + public var array: [JSON]? { + get { + if self.type == .array { + return self.rawArray.map{ JSON($0) } + } else { + return nil + } + } + } + + //Non-optional [JSON] + public var arrayValue: [JSON] { + get { + return self.array ?? [] + } + } + + //Optional [Any] + public var arrayObject: [Any]? { + get { + switch self.type { + case .array: + return self.rawArray + default: + return nil + } + } + set { + if let array = newValue { + self.object = array as Any + } else { + self.object = NSNull() + } + } + } +} + +// MARK: - Dictionary + +extension JSON { + + //Optional [String : JSON] + public var dictionary: [String : JSON]? { + if self.type == .dictionary { + var d = [String : JSON](minimumCapacity: rawDictionary.count) + for (key, value) in rawDictionary { + d[key] = JSON(value) + } + return d + } else { + return nil + } + } + + //Non-optional [String : JSON] + public var dictionaryValue: [String : JSON] { + return self.dictionary ?? [:] + } + + //Optional [String : Any] + + public var dictionaryObject: [String : Any]? { + get { + switch self.type { + case .dictionary: + return self.rawDictionary + default: + return nil + } + } + set { + if let v = newValue { + self.object = v as Any + } else { + self.object = NSNull() + } + } + } +} + +// MARK: - Bool + +extension JSON { // : Swift.Bool + + //Optional bool + public var bool: Bool? { + get { + switch self.type { + case .bool: + return self.rawBool + default: + return nil + } + } + set { + if let newValue = newValue { + self.object = newValue as Bool + } else { + self.object = NSNull() + } + } + } + + //Non-optional bool + public var boolValue: Bool { + get { + switch self.type { + case .bool: + return self.rawBool + case .number: + return self.rawNumber.boolValue + case .string: + return ["true", "y", "t"].contains() { (truthyString) in + return self.rawString.caseInsensitiveCompare(truthyString) == .orderedSame + } + default: + return false + } + } + set { + self.object = newValue + } + } +} + +// MARK: - String + +extension JSON { + + //Optional string + public var string: String? { + get { + switch self.type { + case .string: + return self.object as? String + default: + return nil + } + } + set { + if let newValue = newValue { + self.object = NSString(string:newValue) + } else { + self.object = NSNull() + } + } + } + + //Non-optional string + public var stringValue: String { + get { + switch self.type { + case .string: + return self.object as? String ?? "" + case .number: + return self.rawNumber.stringValue + case .bool: + return (self.object as? Bool).map { String($0) } ?? "" + default: + return "" + } + } + set { + self.object = NSString(string:newValue) + } + } +} + +// MARK: - Number +extension JSON { + + //Optional number + public var number: NSNumber? { + get { + switch self.type { + case .number: + return self.rawNumber + case .bool: + return NSNumber(value: self.rawBool ? 1 : 0) + default: + return nil + } + } + set { + self.object = newValue ?? NSNull() + } + } + + //Non-optional number + public var numberValue: NSNumber { + get { + switch self.type { + case .string: + let decimal = NSDecimalNumber(string: self.object as? String) + if decimal == NSDecimalNumber.notANumber { // indicates parse error + return NSDecimalNumber.zero + } + return decimal + case .number: + return self.object as? NSNumber ?? NSNumber(value: 0) + case .bool: + return NSNumber(value: self.rawBool ? 1 : 0) + default: + return NSNumber(value: 0.0) + } + } + set { + self.object = newValue + } + } +} + +//MARK: - Null +extension JSON { + + public var null: NSNull? { + get { + switch self.type { + case .null: + return self.rawNull + default: + return nil + } + } + set { + self.object = NSNull() + } + } + public func exists() -> Bool{ + if let errorValue = error, errorValue.code == ErrorNotExist || + errorValue.code == ErrorIndexOutOfBounds || + errorValue.code == ErrorWrongType { + return false + } + return true + } +} + +//MARK: - URL +extension JSON { + + //Optional URL + public var URL: URL? { + get { + switch self.type { + case .string: + if let encodedString_ = self.rawString.addingPercentEncoding(withAllowedCharacters: CharacterSet.urlQueryAllowed) { + // We have to use `Foundation.URL` otherwise it conflicts with the variable name. + return Foundation.URL(string: encodedString_) + } else { + return nil + } + default: + return nil + } + } + set { + self.object = newValue?.absoluteString ?? NSNull() + } + } +} + +// MARK: - Int, Double, Float, Int8, Int16, Int32, Int64 + +extension JSON { + + public var double: Double? { + get { + return self.number?.doubleValue + } + set { + if let newValue = newValue { + self.object = NSNumber(value: newValue) + } else { + self.object = NSNull() + } + } + } + + public var doubleValue: Double { + get { + return self.numberValue.doubleValue + } + set { + self.object = NSNumber(value: newValue) + } + } + + public var float: Float? { + get { + return self.number?.floatValue + } + set { + if let newValue = newValue { + self.object = NSNumber(value: newValue) + } else { + self.object = NSNull() + } + } + } + + public var floatValue: Float { + get { + return self.numberValue.floatValue + } + set { + self.object = NSNumber(value: newValue) + } + } + + public var int: Int? + { + get + { + return self.number?.intValue + } + set + { + if let newValue = newValue + { + self.object = NSNumber(value: newValue) + } else + { + self.object = NSNull() + } + } + } + + public var intValue: Int { + get { + return self.numberValue.intValue + } + set { + self.object = NSNumber(value: newValue) + } + } + + public var uInt: UInt? { + get { + return self.number?.uintValue + } + set { + if let newValue = newValue { + self.object = NSNumber(value: newValue) + } else { + self.object = NSNull() + } + } + } + + public var uIntValue: UInt { + get { + return self.numberValue.uintValue + } + set { + self.object = NSNumber(value: newValue) + } + } + + public var int8: Int8? { + get { + return self.number?.int8Value + } + set { + if let newValue = newValue { + self.object = NSNumber(value: newValue) + } else { + self.object = NSNull() + } + } + } + + public var int8Value: Int8 { + get { + return self.numberValue.int8Value + } + set { + self.object = NSNumber(value: newValue) + } + } + + public var uInt8: UInt8? { + get { + return self.number?.uint8Value + } + set { + if let newValue = newValue { + self.object = NSNumber(value: newValue) + } else { + self.object = NSNull() + } + } + } + + public var uInt8Value: UInt8 { + get { + return self.numberValue.uint8Value + } + set { + self.object = NSNumber(value: newValue) + } + } + + public var int16: Int16? { + get { + return self.number?.int16Value + } + set { + if let newValue = newValue { + self.object = NSNumber(value: newValue) + } else { + self.object = NSNull() + } + } + } + + public var int16Value: Int16 { + get { + return self.numberValue.int16Value + } + set { + self.object = NSNumber(value: newValue) + } + } + + public var uInt16: UInt16? { + get { + return self.number?.uint16Value + } + set { + if let newValue = newValue { + self.object = NSNumber(value: newValue) + } else { + self.object = NSNull() + } + } + } + + public var uInt16Value: UInt16 { + get { + return self.numberValue.uint16Value + } + set { + self.object = NSNumber(value: newValue) + } + } + + public var int32: Int32? { + get { + return self.number?.int32Value + } + set { + if let newValue = newValue { + self.object = NSNumber(value: newValue) + } else { + self.object = NSNull() + } + } + } + + public var int32Value: Int32 { + get { + return self.numberValue.int32Value + } + set { + self.object = NSNumber(value: newValue) + } + } + + public var uInt32: UInt32? { + get { + return self.number?.uint32Value + } + set { + if let newValue = newValue { + self.object = NSNumber(value: newValue) + } else { + self.object = NSNull() + } + } + } + + public var uInt32Value: UInt32 { + get { + return self.numberValue.uint32Value + } + set { + self.object = NSNumber(value: newValue) + } + } + + public var int64: Int64? { + get { + return self.number?.int64Value + } + set { + if let newValue = newValue { + self.object = NSNumber(value: newValue) + } else { + self.object = NSNull() + } + } + } + + public var int64Value: Int64 { + get { + return self.numberValue.int64Value + } + set { + self.object = NSNumber(value: newValue) + } + } + + public var uInt64: UInt64? { + get { + return self.number?.uint64Value + } + set { + if let newValue = newValue { + self.object = NSNumber(value: newValue) + } else { + self.object = NSNull() + } + } + } + + public var uInt64Value: UInt64 { + get { + return self.numberValue.uint64Value + } + set { + self.object = NSNumber(value: newValue) + } + } +} + +//MARK: - Comparable +extension JSON : Swift.Comparable {} + +public func ==(lhs: JSON, rhs: JSON) -> Bool { + + switch (lhs.type, rhs.type) { + case (.number, .number): + return lhs.rawNumber == rhs.rawNumber + case (.string, .string): + return lhs.rawString == rhs.rawString + case (.bool, .bool): + return lhs.rawBool == rhs.rawBool + case (.array, .array): + return lhs.rawArray as NSArray == rhs.rawArray as NSArray + case (.dictionary, .dictionary): + return lhs.rawDictionary as NSDictionary == rhs.rawDictionary as NSDictionary + case (.null, .null): + return true + default: + return false + } +} + +public func <=(lhs: JSON, rhs: JSON) -> Bool { + + switch (lhs.type, rhs.type) { + case (.number, .number): + return lhs.rawNumber <= rhs.rawNumber + case (.string, .string): + return lhs.rawString <= rhs.rawString + case (.bool, .bool): + return lhs.rawBool == rhs.rawBool + case (.array, .array): + return lhs.rawArray as NSArray == rhs.rawArray as NSArray + case (.dictionary, .dictionary): + return lhs.rawDictionary as NSDictionary == rhs.rawDictionary as NSDictionary + case (.null, .null): + return true + default: + return false + } +} + +public func >=(lhs: JSON, rhs: JSON) -> Bool { + + switch (lhs.type, rhs.type) { + case (.number, .number): + return lhs.rawNumber >= rhs.rawNumber + case (.string, .string): + return lhs.rawString >= rhs.rawString + case (.bool, .bool): + return lhs.rawBool == rhs.rawBool + case (.array, .array): + return lhs.rawArray as NSArray == rhs.rawArray as NSArray + case (.dictionary, .dictionary): + return lhs.rawDictionary as NSDictionary == rhs.rawDictionary as NSDictionary + case (.null, .null): + return true + default: + return false + } +} + +public func >(lhs: JSON, rhs: JSON) -> Bool { + + switch (lhs.type, rhs.type) { + case (.number, .number): + return lhs.rawNumber > rhs.rawNumber + case (.string, .string): + return lhs.rawString > rhs.rawString + default: + return false + } +} + +public func <(lhs: JSON, rhs: JSON) -> Bool { + + switch (lhs.type, rhs.type) { + case (.number, .number): + return lhs.rawNumber < rhs.rawNumber + case (.string, .string): + return lhs.rawString < rhs.rawString + default: + return false + } +} + +private let trueNumber = NSNumber(value: true) +private let falseNumber = NSNumber(value: false) +private let trueObjCType = String(cString: trueNumber.objCType) +private let falseObjCType = String(cString: falseNumber.objCType) + +// MARK: - NSNumber: Comparable + +extension NSNumber { + var isBool:Bool { + get { + let objCType = String(cString: self.objCType) + if (self.compare(trueNumber) == .orderedSame && objCType == trueObjCType) || (self.compare(falseNumber) == .orderedSame && objCType == falseObjCType){ + return true + } else { + return false + } + } + } +} + +func ==(lhs: NSNumber, rhs: NSNumber) -> Bool { + switch (lhs.isBool, rhs.isBool) { + case (false, true): + return false + case (true, false): + return false + default: + return lhs.compare(rhs) == .orderedSame + } +} + +func !=(lhs: NSNumber, rhs: NSNumber) -> Bool { + return !(lhs == rhs) +} + +func <(lhs: NSNumber, rhs: NSNumber) -> Bool { + + switch (lhs.isBool, rhs.isBool) { + case (false, true): + return false + case (true, false): + return false + default: + return lhs.compare(rhs) == .orderedAscending + } +} + +func >(lhs: NSNumber, rhs: NSNumber) -> Bool { + + switch (lhs.isBool, rhs.isBool) { + case (false, true): + return false + case (true, false): + return false + default: + return lhs.compare(rhs) == ComparisonResult.orderedDescending + } +} + +func <=(lhs: NSNumber, rhs: NSNumber) -> Bool { + + switch (lhs.isBool, rhs.isBool) { + case (false, true): + return false + case (true, false): + return false + default: + return lhs.compare(rhs) != .orderedDescending + } +} + +func >=(lhs: NSNumber, rhs: NSNumber) -> Bool { + + switch (lhs.isBool, rhs.isBool) { + case (false, true): + return false + case (true, false): + return false + default: + return lhs.compare(rhs) != .orderedAscending + } +} diff --git a/GeneralUtils/GeneralUtils/libs/Toaster/Toast.swift b/GeneralUtils/GeneralUtils/libs/Toaster/Toast.swift new file mode 100644 index 0000000..ce76021 --- /dev/null +++ b/GeneralUtils/GeneralUtils/libs/Toaster/Toast.swift @@ -0,0 +1,169 @@ +/* + * Toast.swift + * + * DO WHAT THE FUCK YOU WANT TO PUBLIC LICENSE + * Version 2, December 2004 + * + * Copyright (C) 2013-2015 Su Yeol Jeon + * + * Everyone is permitted to copy and distribute verbatim or modified + * copies of this license document, and changing it is allowed as long + * as the name is changed. + * + * DO WHAT THE FUCK YOU WANT TO PUBLIC LICENSE + * TERMS AND CONDITIONS FOR COPYING, DISTRIBUTION AND MODIFICATION + * + * 0. You just DO WHAT THE FUCK YOU WANT TO. + * + */ + +import UIKit + +public struct Delay { + public static let short: TimeInterval = 2.0 + public static let long: TimeInterval = 3.5 +} + +open class Toast: Operation { + + // MARK: Properties + + public var text: String? { + get { return self.view.text } + set { self.view.text = newValue } + } + + public var delay: TimeInterval + public var duration: TimeInterval + + private var _executing = false + override open var isExecuting: Bool { + get { + return self._executing + } + set { + self.willChangeValue(forKey: "isExecuting") + self._executing = newValue + self.didChangeValue(forKey: "isExecuting") + } + } + + private var _finished = false + override open var isFinished: Bool { + get { + return self._finished + } + set { + self.willChangeValue(forKey: "isFinished") + self._finished = newValue + self.didChangeValue(forKey: "isFinished") + } + } + + + // MARK: UI + + public var view: ToastView = ToastView() + + + // MARK: Initializing + + public init(text: String?, delay: TimeInterval = 0, duration: TimeInterval = Delay.short) { + self.delay = delay + self.duration = duration + super.init() + self.text = text + } + + + // MARK: Factory (Deprecated) + + @available(*, deprecated, message: "Use 'init(text:)' instead.") + public class func makeText(_ text: String) -> Toast { + return Toast(text: text) + } + + @available(*, deprecated, message: "Use 'init(text:duration:)' instead.") + public class func makeText(_ text: String, duration: TimeInterval) -> Toast { + return Toast(text: text, duration: duration) + } + + @available(*, deprecated, message: "Use 'init(text:delay:duration:)' instead.") + public class func makeText(_ text: String?, delay: TimeInterval, duration: TimeInterval) -> Toast { + return Toast(text: text, delay: delay, duration: duration) + } + + + // MARK: Showing + + public func show() { + ToastCenter.default.add(self) + } + + + // MARK: Cancelling + + open override func cancel() { + super.cancel() + self.finish() + self.view.removeFromSuperview() + } + + + // MARK: Operation Subclassing + + override open func start() { + guard Thread.isMainThread else { + DispatchQueue.main.async { [weak self] in + self?.start() + } + return + } + super.start() + } + + override open func main() { + self.isExecuting = true + + DispatchQueue.main.async { + self.view.setNeedsLayout() + self.view.alpha = 0 + ToastWindow.shared.addSubview(self.view) + + UIView.animate( + withDuration: 0.5, + delay: self.delay, + options: .beginFromCurrentState, + animations: { + self.view.alpha = 1 + }, + completion: { completed in + UIView.animate( + withDuration: self.duration, + animations: { + self.view.alpha = 1.0001 + }, + completion: { completed in + self.finish() + UIView.animate( + withDuration: 0.5, + animations: { + self.view.alpha = 0 + }, + completion: { completed in + self.view.removeFromSuperview() + } + ) + } + ) + } + ) + } + } + + open func finish() { + self.isExecuting = false + self.isFinished = true + } + +} diff --git a/GeneralUtils/GeneralUtils/libs/Toaster/ToastCenter.swift b/GeneralUtils/GeneralUtils/libs/Toaster/ToastCenter.swift new file mode 100644 index 0000000..62ee55d --- /dev/null +++ b/GeneralUtils/GeneralUtils/libs/Toaster/ToastCenter.swift @@ -0,0 +1,75 @@ +/* + * ToastCenter.swift + * + * DO WHAT THE FUCK YOU WANT TO PUBLIC LICENSE + * Version 2, December 2004 + * + * Copyright (C) 2013-2015 Su Yeol Jeon + * + * Everyone is permitted to copy and distribute verbatim or modified + * copies of this license document, and changing it is allowed as long + * as the name is changed. + * + * DO WHAT THE FUCK YOU WANT TO PUBLIC LICENSE + * TERMS AND CONDITIONS FOR COPYING, DISTRIBUTION AND MODIFICATION + * + * 0. You just DO WHAT THE FUCK YOU WANT TO. + * + */ + +import UIKit + +open class ToastCenter { + + // MARK: Properties + + private let queue: OperationQueue = { + let queue = OperationQueue() + queue.maxConcurrentOperationCount = 1 + return queue + }() + + open var currentToast: Toast? { + return self.queue.operations.first as? Toast + } + + open static let `default` = ToastCenter() + + + // MARK: Initializing + + init() { + NotificationCenter.default.addObserver( + self, + selector: #selector(self.deviceOrientationDidChange), + name: .UIDeviceOrientationDidChange, + object: nil + ) + } + + + // MARK: Adding Toasts + + open func add(_ toast: Toast) { + self.queue.addOperation(toast) + } + + + // MARK: Cancelling Toasts + + open func cancelAll() { + for toast in self.queue.operations { + toast.cancel() + } + } + + + // MARK: Notifications + + dynamic func deviceOrientationDidChange() { + if let lastToast = self.queue.operations.first as? Toast { + lastToast.view.setNeedsLayout() + } + } + +} diff --git a/GeneralUtils/GeneralUtils/libs/Toaster/ToastView.swift b/GeneralUtils/GeneralUtils/libs/Toaster/ToastView.swift new file mode 100644 index 0000000..5ce04e0 --- /dev/null +++ b/GeneralUtils/GeneralUtils/libs/Toaster/ToastView.swift @@ -0,0 +1,187 @@ +/* + * ToastView.swift + * + * DO WHAT THE FUCK YOU WANT TO PUBLIC LICENSE + * Version 2, December 2004 + * + * Copyright (C) 2013-2015 Su Yeol Jeon + * + * Everyone is permitted to copy and distribute verbatim or modified + * copies of this license document, and changing it is allowed as long + * as the name is changed. + * + * DO WHAT THE FUCK YOU WANT TO PUBLIC LICENSE + * TERMS AND CONDITIONS FOR COPYING, DISTRIBUTION AND MODIFICATION + * + * 0. You just DO WHAT THE FUCK YOU WANT TO. + * + */ + +import UIKit + +open class ToastView: UIView { + + // MARK: Properties + + open var text: String? { + get { return self.textLabel.text } + set { self.textLabel.text = newValue } + } + + + // MARK: Appearance + + /// The background view's color. + override open dynamic var backgroundColor: UIColor? { + get { return self.backgroundView.backgroundColor } + set { self.backgroundView.backgroundColor = newValue } + } + + /// The background view's corner radius. + open dynamic var cornerRadius: CGFloat { + get { return self.backgroundView.layer.cornerRadius } + set { self.backgroundView.layer.cornerRadius = newValue } + } + + /// The inset of the text label. + open dynamic var textInsets = UIEdgeInsets(top: 6, left: 10, bottom: 6, right: 10) + + /// The color of the text label's text. + open dynamic var textColor: UIColor? { + get { return self.textLabel.textColor } + set { self.textLabel.textColor = newValue } + } + + /// The font of the text label. + open dynamic var font: UIFont? { + get { return self.textLabel.font } + set { self.textLabel.font = newValue } + } + + /// The bottom offset from the screen's bottom in portrait mode. + open dynamic var bottomOffsetPortrait: CGFloat = { + switch UIDevice.current.userInterfaceIdiom { + case .unspecified: return 30 + case .phone: return 30 + case .pad: return 60 + case .tv: return 90 + case .carPlay: return 30 + } + }() + + /// The bottom offset from the screen's bottom in landscape mode. + open dynamic var bottomOffsetLandscape: CGFloat = { + switch UIDevice.current.userInterfaceIdiom { + case .unspecified: return 20 + case .phone: return 20 + case .pad: return 40 + case .tv: return 60 + case .carPlay: return 20 + } + }() + + + // MARK: UI + + private let backgroundView: UIView = { + let `self` = UIView() + self.backgroundColor = UIColor(white: 0, alpha: 0.7) + self.layer.cornerRadius = 5 + self.clipsToBounds = true + return self + }() + private let textLabel: UILabel = { + let `self` = UILabel() + self.textColor = .white + self.backgroundColor = .clear + self.font = { + switch UIDevice.current.userInterfaceIdiom { + case .unspecified: return .systemFont(ofSize: 12) + case .phone: return .systemFont(ofSize: 12) + case .pad: return .systemFont(ofSize: 16) + case .tv: return .systemFont(ofSize: 20) + case .carPlay: return .systemFont(ofSize: 12) + } + }() + self.numberOfLines = 0 + self.textAlignment = .center + return self + }() + + + // MARK: Initializing + + public init() { + super.init(frame: .zero) + self.isUserInteractionEnabled = false + self.addSubview(self.backgroundView) + self.addSubview(self.textLabel) + } + + required convenience public init?(coder aDecoder: NSCoder) { + self.init() + } + + + // MARK: Layout + + override open func layoutSubviews() { + super.layoutSubviews() + let containerSize = ToastWindow.shared.frame.size + let constraintSize = CGSize( + width: containerSize.width * (280.0 / 320.0), + height: CGFloat.greatestFiniteMagnitude + ) + let textLabelSize = self.textLabel.sizeThatFits(constraintSize) + self.textLabel.frame = CGRect( + x: self.textInsets.left, + y: self.textInsets.top, + width: textLabelSize.width, + height: textLabelSize.height + ) + self.backgroundView.frame = CGRect( + x: 0, + y: 0, + width: self.textLabel.frame.size.width + self.textInsets.left + self.textInsets.right, + height: self.textLabel.frame.size.height + self.textInsets.top + self.textInsets.bottom + ) + + var x: CGFloat + var y: CGFloat + var width: CGFloat + var height: CGFloat + + let orientation = UIApplication.shared.statusBarOrientation + if orientation.isPortrait || !ToastWindow.shared.shouldRotateManually { + width = containerSize.width + height = containerSize.height + y = self.bottomOffsetPortrait + } else { + width = containerSize.height + height = containerSize.width + y = self.bottomOffsetLandscape + } + + let backgroundViewSize = self.backgroundView.frame.size + x = (width - backgroundViewSize.width) * 0.5 + y = height - (backgroundViewSize.height + y) + self.frame = CGRect( + x: x, + y: y, + width: backgroundViewSize.width, + height: backgroundViewSize.height + ) + } + + override open func hitTest(_ point: CGPoint, with event: UIEvent!) -> UIView? { + if let superview = self.superview { + let pointInWindow = self.convert(point, to: superview) + let contains = self.frame.contains(pointInWindow) + if contains && self.isUserInteractionEnabled { + return self + } + } + return nil + } + +} diff --git a/GeneralUtils/GeneralUtils/libs/Toaster/ToastWindow.swift b/GeneralUtils/GeneralUtils/libs/Toaster/ToastWindow.swift new file mode 100644 index 0000000..1052984 --- /dev/null +++ b/GeneralUtils/GeneralUtils/libs/Toaster/ToastWindow.swift @@ -0,0 +1,154 @@ +/* + * ToastView.swift + * + * DO WHAT THE FUCK YOU WANT TO PUBLIC LICENSE + * Version 2, December 2004 + * + * Copyright (C) 2013-2015 Su Yeol Jeon + * + * Everyone is permitted to copy and distribute verbatim or modified + * copies of this license document, and changing it is allowed as long + * as the name is changed. + * + * DO WHAT THE FUCK YOU WANT TO PUBLIC LICENSE + * TERMS AND CONDITIONS FOR COPYING, DISTRIBUTION AND MODIFICATION + * + * 0. You just DO WHAT THE FUCK YOU WANT TO. + * + */ + +import UIKit + +open class ToastWindow: UIWindow { + + open static let shared = ToastWindow(frame: UIScreen.main.bounds) + + /// Will not return `rootViewController` while this value is `true`. Or the rotation will be fucked in iOS 9. + var isStatusBarOrientationChanging = false + + /// Don't rotate manually if the application: + /// + /// - is running on iPad + /// - is running on iOS 9 + /// - supports all orientations + /// - doesn't require full screen + /// - has launch storyboard + /// + var shouldRotateManually: Bool { + let iPad = UIDevice.current.userInterfaceIdiom == .pad + let application = UIApplication.shared + let window = application.delegate?.window ?? nil + let supportsAllOrientations = application.supportedInterfaceOrientations(for: window) == .all + + let info = Bundle.main.infoDictionary + let requiresFullScreen = (info?["UIRequiresFullScreen"] as? NSNumber)?.boolValue == true + let hasLaunchStoryboard = info?["UILaunchStoryboardName"] != nil + + if #available(iOS 9, *), iPad && supportsAllOrientations && !requiresFullScreen && hasLaunchStoryboard { + return false + } + return true + } + + override open var rootViewController: UIViewController? { + get { + guard !self.isStatusBarOrientationChanging else { return nil } + return UIApplication.shared.windows.first?.rootViewController + } + set { /* Do nothing */ } + } + + public override init(frame: CGRect) { + super.init(frame: frame) + self.isUserInteractionEnabled = false + self.windowLevel = CGFloat.greatestFiniteMagnitude + self.backgroundColor = .clear + self.isHidden = false + self.handleRotate(UIApplication.shared.statusBarOrientation) + + NotificationCenter.default.addObserver( + self, + selector: #selector(self.bringWindowToTop), + name: .UIWindowDidBecomeVisible, + object: nil + ) + NotificationCenter.default.addObserver( + self, + selector: #selector(self.statusBarOrientationWillChange), + name: .UIApplicationWillChangeStatusBarOrientation, + object: nil + ) + NotificationCenter.default.addObserver( + self, + selector: #selector(self.statusBarOrientationDidChange), + name: .UIApplicationDidChangeStatusBarOrientation, + object: nil + ) + NotificationCenter.default.addObserver( + self, + selector: #selector(self.applicationDidBecomeActive), + name: .UIApplicationDidBecomeActive, + object: nil + ) + } + + required public init?(coder aDecoder: NSCoder) { + fatalError("init(coder:) has not been implemented") + } + + /// Bring ToastWindow to top when another window is being shown. + func bringWindowToTop(_ notification: Notification) { + if !(notification.object is ToastWindow) { + ToastWindow.shared.isHidden = true + ToastWindow.shared.isHidden = false + } + } + + dynamic func statusBarOrientationWillChange() { + self.isStatusBarOrientationChanging = true + } + + dynamic func statusBarOrientationDidChange() { + let orientation = UIApplication.shared.statusBarOrientation + self.handleRotate(orientation) + self.isStatusBarOrientationChanging = false + } + + func applicationDidBecomeActive() { + let orientation = UIApplication.shared.statusBarOrientation + self.handleRotate(orientation) + } + + func handleRotate(_ orientation: UIInterfaceOrientation) { + let angle = self.angleForOrientation(orientation) + if self.shouldRotateManually { + self.transform = CGAffineTransform(rotationAngle: CGFloat(angle)) + } + + if let window = UIApplication.shared.windows.first { + if orientation.isPortrait || !self.shouldRotateManually { + self.frame.size.width = window.bounds.size.width + self.frame.size.height = window.bounds.size.height + } else { + self.frame.size.width = window.bounds.size.height + self.frame.size.height = window.bounds.size.width + } + } + + self.frame.origin = .zero + + DispatchQueue.main.async { + ToastCenter.default.currentToast?.view.setNeedsLayout() + } + } + + func angleForOrientation(_ orientation: UIInterfaceOrientation) -> Double { + switch orientation { + case .landscapeLeft: return -M_PI_2 + case .landscapeRight: return M_PI_2 + case .portraitUpsideDown: return M_PI + default: return 0 + } + } + +} diff --git a/GeneralUtils/GeneralUtils/libs/Toaster/Toaster.h b/GeneralUtils/GeneralUtils/libs/Toaster/Toaster.h new file mode 100644 index 0000000..977b478 --- /dev/null +++ b/GeneralUtils/GeneralUtils/libs/Toaster/Toaster.h @@ -0,0 +1,21 @@ +/* + * DO WHAT THE FUCK YOU WANT TO PUBLIC LICENSE + * Version 2, December 2004 + * + * Copyright (C) 2013-2015 Suyeol Jeon + * + * Everyone is permitted to copy and distribute verbatim or modified + * copies of this license document, and changing it is allowed as long + * as the name is changed. + * + * DO WHAT THE FUCK YOU WANT TO PUBLIC LICENSE + * TERMS AND CONDITIONS FOR COPYING, DISTRIBUTION AND MODIFICATION + * + * 0. You just DO WHAT THE FUCK YOU WANT TO. + * + */ + +#import + +FOUNDATION_EXPORT double ToasterVersionNumber; +FOUNDATION_EXPORT const unsigned char ToasterVersionString[]; diff --git a/GeneralUtils/GeneralUtils/models/Session.swift b/GeneralUtils/GeneralUtils/models/Session.swift new file mode 100644 index 0000000..df9edaa --- /dev/null +++ b/GeneralUtils/GeneralUtils/models/Session.swift @@ -0,0 +1,28 @@ + +import Foundation + +public class Session{ + public var type: SessionType? + public var title: String? + public var otherData: Any? + + public init(title: String?) { + self.title = title + } + + public init(type: SessionType, title: String?) { + self.type = type + self.title = title + } + + public init(otherData: Any, title: String?) { + self.otherData = otherData + self.title = title + } +} + +public enum SessionType{ + case LoadMore +} + + diff --git a/GeneralUtils/GeneralUtils/ui/DrawerController/AnimatedMenuButton.swift b/GeneralUtils/GeneralUtils/ui/DrawerController/AnimatedMenuButton.swift new file mode 100644 index 0000000..e2d2663 --- /dev/null +++ b/GeneralUtils/GeneralUtils/ui/DrawerController/AnimatedMenuButton.swift @@ -0,0 +1,139 @@ +// Copyright (c) 2014 evolved.io (http://evolved.io) +// +// Permission is hereby granted, free of charge, to any person obtaining a copy +// of this software and associated documentation files (the "Software"), to deal +// in the Software without restriction, including without limitation the rights +// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +// copies of the Software, and to permit persons to whom the Software is +// furnished to do so, subject to the following conditions: +// +// The above copyright notice and this permission notice shall be included in +// all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN +// THE SOFTWARE. + +import Foundation +import QuartzCore +import UIKit + +open class AnimatedMenuButton : UIButton { + + let top: CAShapeLayer = CAShapeLayer() + let middle: CAShapeLayer = CAShapeLayer() + let bottom: CAShapeLayer = CAShapeLayer() + let strokeColor: UIColor + + // MARK: - Constants + + let animationDuration: CFTimeInterval = 8.0 + + let shortStroke: CGPath = { + let path = CGMutablePath() + path.move(to: CGPoint(x: 2, y: 2)) + path.addLine(to: CGPoint(x: 30 - 2 * 2, y: 2)) + return path + }() + + // MARK: - Initializers + + required public init?(coder aDecoder: NSCoder) { + self.strokeColor = UIColor.gray + super.init(coder: aDecoder) + } + + override convenience init(frame: CGRect) { + self.init(frame: frame, strokeColor: UIColor.gray) + } + + init(frame: CGRect, strokeColor: UIColor) { + self.strokeColor = strokeColor + super.init(frame: frame) + + self.top.path = shortStroke; + self.middle.path = shortStroke; + self.bottom.path = shortStroke; + + for layer in [ self.top, self.middle, self.bottom ] { + layer.fillColor = nil + layer.strokeColor = self.strokeColor.cgColor + layer.lineWidth = 4 + layer.miterLimit = 2 + layer.lineCap = kCALineCapRound + layer.masksToBounds = true + + if let path = layer.path, let strokingPath = CGPath(__byStroking: path, transform: nil, lineWidth: 4, lineCap: .round, lineJoin: .miter, miterLimit: 4) { + layer.bounds = strokingPath.boundingBoxOfPath + } + + layer.actions = [ + "opacity": NSNull(), + "transform": NSNull() + ] + + self.layer.addSublayer(layer) + } + + self.top.anchorPoint = CGPoint(x: 1, y: 0.5) + self.top.position = CGPoint(x: 30 - 1, y: 5) + self.middle.position = CGPoint(x: 15, y: 15) + + self.bottom.anchorPoint = CGPoint(x: 1, y: 0.5) + self.bottom.position = CGPoint(x: 30 - 1, y: 25) + } + + // MARK: - Animations + + open func animate(withPercentVisible percentVisible: CGFloat, drawerSide: DrawerSide) { + + if drawerSide == DrawerSide.left { + self.top.anchorPoint = CGPoint(x: 1, y: 0.5) + self.top.position = CGPoint(x: 30 - 1, y: 5) + self.middle.position = CGPoint(x: 15, y: 15) + + self.bottom.anchorPoint = CGPoint(x: 1, y: 0.5) + self.bottom.position = CGPoint(x: 30 - 1, y: 25) + } else if drawerSide == DrawerSide.right { + self.top.anchorPoint = CGPoint(x: 0, y: 0.5) + self.top.position = CGPoint(x: 1, y: 5) + self.middle.position = CGPoint(x: 15, y: 15) + + self.bottom.anchorPoint = CGPoint(x: 0, y: 0.5) + self.bottom.position = CGPoint(x: 1, y: 25) + } + + let middleTransform = CABasicAnimation(keyPath: "opacity") + middleTransform.duration = animationDuration + + let topTransform = CABasicAnimation(keyPath: "transform") + topTransform.timingFunction = CAMediaTimingFunction(controlPoints: 0.5, -0.8, 0.5, 1.85) + topTransform.duration = animationDuration + topTransform.fillMode = kCAFillModeBackwards + + let bottomTransform = topTransform.copy() as! CABasicAnimation + + middleTransform.toValue = 1 - percentVisible + + let translation = CATransform3DMakeTranslation(-4 * percentVisible, 0, 0) + + let sideInverter: CGFloat = drawerSide == DrawerSide.left ? -1 : 1 + topTransform.toValue = NSValue(caTransform3D: CATransform3DRotate(translation, 1.0 * sideInverter * ((CGFloat)(45.0 * M_PI / 180.0) * percentVisible), 0, 0, 1)) + bottomTransform.toValue = NSValue(caTransform3D: CATransform3DRotate(translation, (-1.0 * sideInverter * (CGFloat)(45.0 * M_PI / 180.0) * percentVisible), 0, 0, 1)) + + topTransform.beginTime = CACurrentMediaTime() + bottomTransform.beginTime = CACurrentMediaTime() + + self.top.add(topTransform, forKey: topTransform.keyPath) + self.middle.add(middleTransform, forKey: middleTransform.keyPath) + self.bottom.add(bottomTransform, forKey: bottomTransform.keyPath) + + self.top.setValue(topTransform.toValue, forKey: topTransform.keyPath!) + self.middle.setValue(middleTransform.toValue, forKey: middleTransform.keyPath!) + self.bottom.setValue(bottomTransform.toValue, forKey: bottomTransform.keyPath!) + } +} diff --git a/GeneralUtils/GeneralUtils/ui/DrawerController/DrawerBarButtonItem.swift b/GeneralUtils/GeneralUtils/ui/DrawerController/DrawerBarButtonItem.swift new file mode 100644 index 0000000..3315c21 --- /dev/null +++ b/GeneralUtils/GeneralUtils/ui/DrawerController/DrawerBarButtonItem.swift @@ -0,0 +1,61 @@ +// Copyright (c) 2014 evolved.io (http://evolved.io) +// +// Permission is hereby granted, free of charge, to any person obtaining a copy +// of this software and associated documentation files (the "Software"), to deal +// in the Software without restriction, including without limitation the rights +// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +// copies of the Software, and to permit persons to whom the Software is +// furnished to do so, subject to the following conditions: +// +// The above copyright notice and this permission notice shall be included in +// all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN +// THE SOFTWARE. + +import UIKit +import Foundation + +open class DrawerBarButtonItem: UIBarButtonItem { + + var menuButton: AnimatedMenuButton + + // MARK: - Initializers + + public override init() { + self.menuButton = AnimatedMenuButton(frame: CGRect(x: 0, y: 0, width: 30, height: 30)) + super.init() + self.customView = self.menuButton + } + + public convenience init(target: AnyObject?, action: Selector) { + self.init(target: target, action: action, menuIconColor: UIColor.gray) + } + + public convenience init(target: AnyObject?, action: Selector, menuIconColor: UIColor) { + let menuButton = AnimatedMenuButton(frame: CGRect(x: 0, y: 0, width: 30, height: 30), strokeColor: menuIconColor) + menuButton.addTarget(target, action: action, for: UIControlEvents.touchUpInside) + self.init(customView: menuButton) + + self.menuButton = menuButton + } + + public required init?(coder aDecoder: NSCoder) { + self.menuButton = AnimatedMenuButton(frame: CGRect(x: 0, y: 0, width: 30, height: 30)) + super.init(coder: aDecoder) + self.customView = self.menuButton + } + + // MARK: - Animations + + open func animate(withPercentVisible percentVisible: CGFloat, drawerSide: DrawerSide) { + if let btn = self.customView as? AnimatedMenuButton { + btn.animate(withPercentVisible: percentVisible, drawerSide: drawerSide) + } + } +} diff --git a/GeneralUtils/GeneralUtils/ui/DrawerController/DrawerController.h b/GeneralUtils/GeneralUtils/ui/DrawerController/DrawerController.h new file mode 100644 index 0000000..5b1cd8b --- /dev/null +++ b/GeneralUtils/GeneralUtils/ui/DrawerController/DrawerController.h @@ -0,0 +1,19 @@ +// +// DrawerController.h +// DrawerController +// +// Created by alex on 2015-05-09. +// Copyright (c) 2015 evolved.io. All rights reserved. +// + +#import + +//! Project version number for DrawerController. +FOUNDATION_EXPORT double DrawerControllerVersionNumber; + +//! Project version string for DrawerController. +FOUNDATION_EXPORT const unsigned char DrawerControllerVersionString[]; + +// In this header, you should import all the public headers of your framework using statements like #import + + diff --git a/GeneralUtils/GeneralUtils/ui/DrawerController/DrawerController.swift b/GeneralUtils/GeneralUtils/ui/DrawerController/DrawerController.swift new file mode 100644 index 0000000..8afe865 --- /dev/null +++ b/GeneralUtils/GeneralUtils/ui/DrawerController/DrawerController.swift @@ -0,0 +1,1546 @@ +// Copyright (c) 2014 evolved.io (http://evolved.io) +// +// Permission is hereby granted, free of charge, to any person obtaining a copy +// of this software and associated documentation files (the "Software"), to deal +// in the Software without restriction, including without limitation the rights +// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +// copies of the Software, and to permit persons to whom the Software is +// furnished to do so, subject to the following conditions: +// +// The above copyright notice and this permission notice shall be included in +// all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN +// THE SOFTWARE. + +import UIKit + +public extension UIViewController { + var evo_drawerController: DrawerController? { + var parentViewController = self.parent + + while parentViewController != nil { + if parentViewController!.isKind(of: DrawerController.self) { + return parentViewController as? DrawerController + } + + parentViewController = parentViewController!.parent + } + + return nil + } + + var evo_visibleDrawerFrame: CGRect { + if let drawerController = self.evo_drawerController { + if drawerController.leftDrawerViewController != nil { + if self == drawerController.leftDrawerViewController || self.navigationController == drawerController.leftDrawerViewController { + var rect = drawerController.view.bounds + rect.size.width = drawerController.maximumLeftDrawerWidth + return rect + } + } + + if drawerController.rightDrawerViewController != nil { + if self == drawerController.rightDrawerViewController || self.navigationController == drawerController.rightDrawerViewController { + var rect = drawerController.view.bounds + rect.size.width = drawerController.maximumRightDrawerWidth + rect.origin.x = drawerController.view.bounds.width - rect.size.width + return rect + } + } + } + + return CGRect.null + } +} + +private func bounceKeyFrameAnimation(forDistance distance: CGFloat, on view: UIView) -> CAKeyframeAnimation { + let factors: [CGFloat] = [0, 32, 60, 83, 100, 114, 124, 128, 128, 124, 114, 100, 83, 60, 32, 0, 24, 42, 54, 62, 64, 62, 54, 42, 24, 0, 18, 28, 32, 28, 18, 0] + + let values = factors.map({ x in + NSNumber(value: Float(x / 128 * distance + view.bounds.midX) as Float) + }) + + let animation = CAKeyframeAnimation(keyPath: "position.x") + animation.repeatCount = 1 + animation.duration = 0.8 + animation.fillMode = kCAFillModeForwards + animation.values = values + animation.isRemovedOnCompletion = true + animation.autoreverses = false + + return animation +} + +public enum DrawerSide: Int { + case none + case left + case right +} + +public struct OpenDrawerGestureMode: OptionSet { + public let rawValue: UInt + public init(rawValue: UInt) { self.rawValue = rawValue } + + public static let panningNavigationBar = OpenDrawerGestureMode(rawValue: 0b0001) + public static let panningCenterView = OpenDrawerGestureMode(rawValue: 0b0010) + public static let bezelPanningCenterView = OpenDrawerGestureMode(rawValue: 0b0100) + public static let custom = OpenDrawerGestureMode(rawValue: 0b1000) + public static let all: OpenDrawerGestureMode = [panningNavigationBar, panningCenterView, bezelPanningCenterView, custom] +} + +public struct CloseDrawerGestureMode: OptionSet { + public let rawValue: UInt + public init(rawValue: UInt) { self.rawValue = rawValue } + + public static let panningNavigationBar = CloseDrawerGestureMode(rawValue: 0b0000001) + public static let panningCenterView = CloseDrawerGestureMode(rawValue: 0b0000010) + public static let bezelPanningCenterView = CloseDrawerGestureMode(rawValue: 0b0000100) + public static let tapNavigationBar = CloseDrawerGestureMode(rawValue: 0b0001000) + public static let tapCenterView = CloseDrawerGestureMode(rawValue: 0b0010000) + public static let panningDrawerView = CloseDrawerGestureMode(rawValue: 0b0100000) + public static let custom = CloseDrawerGestureMode(rawValue: 0b1000000) + public static let all: CloseDrawerGestureMode = [panningNavigationBar, panningCenterView, bezelPanningCenterView, tapNavigationBar, tapCenterView, panningDrawerView, custom] +} + +public enum DrawerOpenCenterInteractionMode: Int { + case none + case full + case navigationBarOnly +} + +private let DrawerDefaultWidth: CGFloat = 280.0 +private let DrawerDefaultAnimationVelocity: CGFloat = 840.0 + +private let DrawerDefaultFullAnimationDelay: TimeInterval = 0.10 + +private let DrawerDefaultBounceDistance: CGFloat = 50.0 + +private let DrawerMinimumAnimationDuration: CGFloat = 0.15 +private let DrawerDefaultDampingFactor: CGFloat = 1.0 +private let DrawerDefaultShadowRadius: CGFloat = 10.0 +private let DrawerDefaultShadowOpacity: Float = 0.8 + +private let DrawerPanVelocityXAnimationThreshold: CGFloat = 200.0 + +/** The amount of overshoot that is panned linearly. The remaining percentage nonlinearly asymptotes to the max percentage. */ +private let DrawerOvershootLinearRangePercentage: CGFloat = 0.75 + +/** The percent of the possible overshoot width to use as the actual overshoot percentage. */ +private let DrawerOvershootPercentage: CGFloat = 0.1 + +private let DrawerBezelRange: CGFloat = 20.0 + +private let DrawerLeftDrawerKey = "DrawerLeftDrawer" +private let DrawerRightDrawerKey = "DrawerRightDrawer" +private let DrawerCenterKey = "DrawerCenter" +private let DrawerOpenSideKey = "DrawerOpenSide" + +public typealias DrawerGestureShouldRecognizeTouchBlock = (DrawerController, UIGestureRecognizer, UITouch) -> Bool +public typealias DrawerGestureCompletionBlock = (DrawerController, UIGestureRecognizer) -> Void +public typealias DrawerControllerDrawerVisualStateBlock = (DrawerController, DrawerSide, CGFloat) -> Void + +private class DrawerCenterContainerView: UIView { + fileprivate var openSide: DrawerSide = .none + var centerInteractionMode: DrawerOpenCenterInteractionMode = .none + + fileprivate override func hitTest(_ point: CGPoint, with event: UIEvent?) -> UIView? { + var hitView = super.hitTest(point, with: event) + + if hitView != nil && self.openSide != .none { + if self.centerInteractionMode == .none { + hitView = nil + } else if let navBar = self.navigationBarContained(withinSubviewsOf: self) { + let navBarFrame = navBar.convert(navBar.bounds, to: self) + + if self.centerInteractionMode == .navigationBarOnly && navBarFrame.contains(point) == false { + hitView = nil + } + } + } + + return hitView + } + + fileprivate func navigationBarContained(withinSubviewsOf view: UIView) -> UINavigationBar? { + var navBar: UINavigationBar? + + for subview in view.subviews as [UIView] { + if view.isKind(of: UINavigationBar.self) { + navBar = view as? UINavigationBar + break + } else { + navBar = self.navigationBarContained(withinSubviewsOf: subview) + if navBar != nil { + break + } + } + } + + return navBar + } +} + +open class DrawerController: UIViewController, UIGestureRecognizerDelegate { + fileprivate var _centerViewController: UIViewController? + fileprivate var _leftDrawerViewController: UIViewController? + fileprivate var _rightDrawerViewController: UIViewController? + fileprivate var _maximumLeftDrawerWidth = DrawerDefaultWidth + fileprivate var _maximumRightDrawerWidth = DrawerDefaultWidth + + /** + The center view controller. + + This can only be set via the init methods, as well as the `setNewCenterViewController:...` methods. The size of this view controller will automatically be set to the size of the drawer container view controller, and it's position is modified from within this class. Do not modify the frame externally. + */ + open var centerViewController: UIViewController? { + get { + return self._centerViewController + } + + set { + self.setCenter(newValue, animated: false) + } + } + + /** + The left drawer view controller. + + The size of this view controller is managed within this class, and is automatically set to the appropriate size based on the `maximumLeftDrawerWidth`. Do not modify the frame externally. + */ + open var leftDrawerViewController: UIViewController? { + get { + return self._leftDrawerViewController + } + + set { + self.setDrawer(newValue, for: .left) + } + } + + /** + The right drawer view controller. + + The size of this view controller is managed within this class, and is automatically set to the appropriate size based on the `maximumRightDrawerWidth`. Do not modify the frame externally. + */ + open var rightDrawerViewController: UIViewController? { + get { + return self._rightDrawerViewController + } + + set { + self.setDrawer(newValue, for: .right) + } + } + + /** + The maximum width of the `leftDrawerViewController`. + + By default, this is set to 280. If the `leftDrawerViewController` is nil, this property will return 0.0; + */ + open var maximumLeftDrawerWidth: CGFloat { + get { + if self.leftDrawerViewController != nil { + return self._maximumLeftDrawerWidth + } else { + return 0.0 + } + } + + set { + self.setMaximumLeftDrawerWidth(newValue, animated: false, completion: nil) + } + } + + /** + The maximum width of the `rightDrawerViewController`. + + By default, this is set to 280. If the `rightDrawerViewController` is nil, this property will return 0.0; + + */ + open var maximumRightDrawerWidth: CGFloat { + get { + if self.rightDrawerViewController != nil { + return self._maximumRightDrawerWidth + } else { + return 0.0 + } + } + + set { + self.setMaximumRightDrawerWidth(newValue, animated: false, completion: nil) + } + } + + /** + The visible width of the `leftDrawerViewController`. + + Note this value can be greater than `maximumLeftDrawerWidth` during the full close animation when setting a new center view controller; + */ + open var visibleLeftDrawerWidth: CGFloat { + get { + return max(0.0, self.centerContainerView.frame.minX) + } + } + + /** + The visible width of the `rightDrawerViewController`. + + Note this value can be greater than `maximumRightDrawerWidth` during the full close animation when setting a new center view controller; + */ + open var visibleRightDrawerWidth: CGFloat { + get { + if self.centerContainerView.frame.minX < 0 { + return self.childControllerContainerView.bounds.width - self.centerContainerView.frame.maxX + } else { + return 0.0 + } + } + } + + /** + A boolean that determines whether or not the panning gesture will "hard-stop" at the maximum width for a given drawer side. + + By default, this value is set to YES. Enabling `shouldStretchDrawer` will give the pan a gradual asymptotic stopping point much like `UIScrollView` behaves. Note that if this value is set to YES, the `drawerVisualStateBlock` can be passed a `percentVisible` greater than 1.0, so be sure to handle that case appropriately. + */ + open var shouldStretchDrawer = true + open var drawerDampingFactor = DrawerDefaultDampingFactor + open var shadowRadius = DrawerDefaultShadowRadius + open var shadowOpacity = DrawerDefaultShadowOpacity + open var bezelRange = DrawerBezelRange + + /** + The flag determining if a shadow should be drawn off of `centerViewController` when a drawer is open. + + By default, this is set to YES. + */ + open var showsShadows: Bool = true { + didSet { + self.updateShadowForCenterView() + } + } + + open var animationVelocity = DrawerDefaultAnimationVelocity + fileprivate var animatingDrawer: Bool = false { + didSet { + self.view.isUserInteractionEnabled = !self.animatingDrawer + } + } + + fileprivate lazy var childControllerContainerView: UIView = { + let childContainerViewFrame = self.view.bounds + let childControllerContainerView = UIView(frame: childContainerViewFrame) + childControllerContainerView.backgroundColor = UIColor.clear + childControllerContainerView.autoresizingMask = [.flexibleHeight, .flexibleWidth] + self.view.addSubview(childControllerContainerView) + + return childControllerContainerView + }() + + fileprivate lazy var centerContainerView: DrawerCenterContainerView = { + let centerFrame = self.childControllerContainerView.bounds + + let centerContainerView = DrawerCenterContainerView(frame: centerFrame) + centerContainerView.autoresizingMask = [.flexibleWidth, .flexibleHeight] + centerContainerView.backgroundColor = UIColor.clear + centerContainerView.openSide = self.openSide + centerContainerView.centerInteractionMode = self.centerHiddenInteractionMode + self.childControllerContainerView.addSubview(centerContainerView) + + return centerContainerView + }() + + /** + The current open side of the drawer. + + Note this value will change as soon as a pan gesture opens a drawer, or when a open/close animation is finished. + */ + open fileprivate(set) var openSide: DrawerSide = .none { + didSet { + self.centerContainerView.openSide = self.openSide + if self.openSide == .none { + self.leftDrawerViewController?.view.isHidden = true + self.rightDrawerViewController?.view.isHidden = true + } + + self.setNeedsStatusBarAppearanceUpdate() + } + } + + fileprivate var startingPanRect: CGRect = CGRect.null + + /** + Sets a callback to be called when a gesture has been completed. + + This block is called when a gesture action has been completed. You can query the `openSide` of the `drawerController` to determine what the new state of the drawer is. + + - parameter gestureCompletionBlock: A block object to be called that allows the implementer be notified when a gesture action has been completed. + */ + open var gestureCompletionBlock: DrawerGestureCompletionBlock? + + /** + Sets a callback to be called when a drawer visual state needs to be updated. + + This block is responsible for updating the drawer's view state, and the drawer controller will handle animating to that state from the current state. This block will be called when the drawer is opened or closed, as well when the user is panning the drawer. This block is not responsible for doing animations directly, but instead just updating the state of the properies (such as alpha, anchor point, transform, etc). Note that if `shouldStretchDrawer` is set to YES, it is possible for `percentVisible` to be greater than 1.0. If `shouldStretchDrawer` is set to NO, `percentVisible` will never be greater than 1.0. + + Note that when the drawer is finished opening or closing, the side drawer controller view will be reset with the following properies: + + - alpha: 1.0 + - transform: CATransform3DIdentity + - anchorPoint: (0.5,0.5) + + - parameter drawerVisualStateBlock: A block object to be called that allows the implementer to update visual state properties on the drawer. `percentVisible` represents the amount of the drawer space that is current visible, with drawer space being defined as the edge of the screen to the maxmimum drawer width. Note that you do have access to the drawerController, which will allow you to update things like the anchor point of the side drawer layer. + */ + open var drawerVisualStateBlock: DrawerControllerDrawerVisualStateBlock? + + /** + Sets a callback to be called to determine if a UIGestureRecognizer should recieve the given UITouch. + + This block provides a way to allow a gesture to be recognized with custom logic. For example, you may have a certain part of your view that should accept a pan gesture recognizer to open the drawer, but not another a part. If you return YES, the gesture is recognized and the appropriate action is taken. This provides similar support to how Facebook allows you to pan on the background view of the main table view, but not the content itself. You can inspect the `openSide` property of the `drawerController` to determine the current state of the drawer, and apply the appropriate logic within your block. + + Note that either `openDrawerGestureModeMask` must contain `OpenDrawerGestureModeCustom`, or `closeDrawerGestureModeMask` must contain `CloseDrawerGestureModeCustom` for this block to be consulted. + + - parameter gestureShouldRecognizeTouchBlock: A block object to be called to determine if the given `touch` should be recognized by the given gesture. + */ + open var gestureShouldRecognizeTouchBlock: DrawerGestureShouldRecognizeTouchBlock? + + /** + How a user is allowed to open a drawer using gestures. + + By default, this is set to `OpenDrawerGestureModeNone`. Note these gestures may affect user interaction with the `centerViewController`, so be sure to use appropriately. + */ + open var openDrawerGestureModeMask: OpenDrawerGestureMode = [] + + /** + How a user is allowed to close a drawer. + + By default, this is set to `CloseDrawerGestureModeNone`. Note these gestures may affect user interaction with the `centerViewController`, so be sure to use appropriately. + */ + open var closeDrawerGestureModeMask: CloseDrawerGestureMode = [] + + /** + The value determining if the user can interact with the `centerViewController` when a side drawer is open. + + By default, it is `DrawerOpenCenterInteractionModeNavigationBarOnly`, meaning that the user can only interact with the buttons on the `UINavigationBar`, if the center view controller is a `UINavigationController`. Otherwise, the user cannot interact with any other center view controller elements. + */ + open var centerHiddenInteractionMode: DrawerOpenCenterInteractionMode = .navigationBarOnly { + didSet { + self.centerContainerView.centerInteractionMode = self.centerHiddenInteractionMode + } + } + + // MARK: - Initializers + + public required init?(coder aDecoder: NSCoder) { + super.init(coder: aDecoder) + } + + override init(nibName nibNameOrNil: String?, bundle nibBundleOrNil: Bundle?) { + super.init(nibName: nibNameOrNil, bundle: nibBundleOrNil) + } + + /** + Creates and initializes an `DrawerController` object with the specified center view controller, left drawer view controller, and right drawer view controller. + + - parameter centerViewController: The center view controller. This argument must not be `nil`. + - parameter leftDrawerViewController: The left drawer view controller. + - parameter rightDrawerViewController: The right drawer controller. + + - returns: The newly-initialized drawer container view controller. + */ + public init(centerViewController: UIViewController, leftDrawerViewController: UIViewController?, rightDrawerViewController: UIViewController?) { + super.init(nibName: nil, bundle: nil) + + self.centerViewController = centerViewController + self.leftDrawerViewController = leftDrawerViewController + self.rightDrawerViewController = rightDrawerViewController + } + + /** + Creates and initializes an `DrawerController` object with the specified center view controller, left drawer view controller. + + - parameter centerViewController: The center view controller. This argument must not be `nil`. + - parameter leftDrawerViewController: The left drawer view controller. + + - returns: The newly-initialized drawer container view controller. + */ + public convenience init(centerViewController: UIViewController, leftDrawerViewController: UIViewController?) { + self.init(centerViewController: centerViewController, leftDrawerViewController: leftDrawerViewController, rightDrawerViewController: nil) + } + + /** + Creates and initializes an `DrawerController` object with the specified center view controller, right drawer view controller. + + - parameter centerViewController: The center view controller. This argument must not be `nil`. + - parameter rightDrawerViewController: The right drawer controller. + + - returns: The newly-initialized drawer container view controller. + */ + public convenience init(centerViewController: UIViewController, rightDrawerViewController: UIViewController?) { + self.init(centerViewController: centerViewController, leftDrawerViewController: nil, rightDrawerViewController: rightDrawerViewController) + } + + // MARK: - State Restoration + + open override func encodeRestorableState(with coder: NSCoder) { + super.encodeRestorableState(with: coder) + + if let leftDrawerViewController = self.leftDrawerViewController { + coder.encode(leftDrawerViewController, forKey: DrawerLeftDrawerKey) + } + + if let rightDrawerViewController = self.rightDrawerViewController { + coder.encode(rightDrawerViewController, forKey: DrawerRightDrawerKey) + } + + if let centerViewController = self.centerViewController { + coder.encode(centerViewController, forKey: DrawerCenterKey) + } + + coder.encode(self.openSide.rawValue, forKey: DrawerOpenSideKey) + } + + open override func decodeRestorableState(with coder: NSCoder) { + super.decodeRestorableState(with: coder) + + if let leftDrawerViewController: AnyObject = coder.decodeObject(forKey: DrawerLeftDrawerKey) as AnyObject? { + self.leftDrawerViewController = leftDrawerViewController as? UIViewController + } + + if let rightDrawerViewController: AnyObject = coder.decodeObject(forKey: DrawerRightDrawerKey) as AnyObject? { + self.rightDrawerViewController = rightDrawerViewController as? UIViewController + } + + if let centerViewController: AnyObject = coder.decodeObject(forKey: DrawerCenterKey) as AnyObject? { + self.centerViewController = centerViewController as? UIViewController + } + + if let openSide = DrawerSide(rawValue: coder.decodeInteger(forKey: DrawerOpenSideKey)) { + self.openSide = openSide + } + } + + // MARK: - UIViewController Containment + + override open var childViewControllerForStatusBarHidden : UIViewController? { + return self.childViewController(for: self.openSide) + } + + override open var childViewControllerForStatusBarStyle : UIViewController? { + return self.childViewController(for: self.openSide) + } + + // MARK: - Animation helpers + + fileprivate func finishAnimationForPanGesture(withXVelocity xVelocity: CGFloat, completion: ((Bool) -> Void)?) { + var currentOriginX = self.centerContainerView.frame.minX + let animationVelocity = max(abs(xVelocity), DrawerPanVelocityXAnimationThreshold * 2) + + if self.openSide == .left { + let midPoint = self.maximumLeftDrawerWidth / 2.0 + + if xVelocity > DrawerPanVelocityXAnimationThreshold { + self.openDrawerSide(.left, animated: true, velocity: animationVelocity, animationOptions: [], completion: completion) + } else if xVelocity < -DrawerPanVelocityXAnimationThreshold { + self.closeDrawer(animated: true, velocity: animationVelocity, animationOptions: [], completion: completion) + } else if currentOriginX < midPoint { + self.closeDrawer(animated: true, completion: completion) + } else { + self.openDrawerSide(.left, animated: true, completion: completion) + } + } else if self.openSide == .right { + currentOriginX = self.centerContainerView.frame.maxX + let midPoint = (self.childControllerContainerView.bounds.width - self.maximumRightDrawerWidth) + (self.maximumRightDrawerWidth / 2.0) + + if xVelocity > DrawerPanVelocityXAnimationThreshold { + self.closeDrawer(animated: true, velocity: animationVelocity, animationOptions: [], completion: completion) + } else if xVelocity < -DrawerPanVelocityXAnimationThreshold { + self.openDrawerSide(.right, animated: true, velocity: animationVelocity, animationOptions: [], completion: completion) + } else if currentOriginX > midPoint { + self.closeDrawer(animated: true, completion: completion) + } else { + self.openDrawerSide(.right, animated: true, completion: completion) + } + } else { + completion?(false) + } + } + + fileprivate func updateDrawerVisualState(for drawerSide: DrawerSide, percentVisible: CGFloat) { + if let drawerVisualState = self.drawerVisualStateBlock { + drawerVisualState(self, drawerSide, percentVisible) + } else if self.shouldStretchDrawer { + self.applyOvershootScaleTransform(for: drawerSide, percentVisible: percentVisible) + } + } + + fileprivate func applyOvershootScaleTransform(for drawerSide: DrawerSide, percentVisible: CGFloat) { + if percentVisible >= 1.0 { + var transform = CATransform3DIdentity + + if let sideDrawerViewController = self.sideDrawerViewController(for: drawerSide) { + if drawerSide == .left { + transform = CATransform3DMakeScale(percentVisible, 1.0, 1.0) + transform = CATransform3DTranslate(transform, self._maximumLeftDrawerWidth * (percentVisible - 1.0) / 2, 0, 0) + } else if drawerSide == .right { + transform = CATransform3DMakeScale(percentVisible, 1.0, 1.0) + transform = CATransform3DTranslate(transform, -self._maximumRightDrawerWidth * (percentVisible - 1.0) / 2, 0, 0) + } + + sideDrawerViewController.view.layer.transform = transform + } + } + } + + fileprivate func resetDrawerVisualState(for drawerSide: DrawerSide) { + if let sideDrawerViewController = self.sideDrawerViewController(for: drawerSide) { + sideDrawerViewController.view.layer.anchorPoint = CGPoint(x: 0.5, y: 0.5) + sideDrawerViewController.view.layer.transform = CATransform3DIdentity + sideDrawerViewController.view.alpha = 1.0 + } + } + + fileprivate func roundedOriginX(forDrawerConstraints originX: CGFloat) -> CGFloat { + if originX < -self.maximumRightDrawerWidth { + if self.shouldStretchDrawer && self.rightDrawerViewController != nil { + let maxOvershoot: CGFloat = (self.centerContainerView.frame.width - self.maximumRightDrawerWidth) * DrawerOvershootPercentage + return self.originX(forDrawerOriginX: originX, andTargetOriginOffset: -self.maximumRightDrawerWidth, maxOvershoot: maxOvershoot) + } else { + return -self.maximumRightDrawerWidth + } + } else if originX > self.maximumLeftDrawerWidth { + if self.shouldStretchDrawer && self.leftDrawerViewController != nil { + let maxOvershoot = (self.centerContainerView.frame.width - self.maximumLeftDrawerWidth) * DrawerOvershootPercentage; + return self.originX(forDrawerOriginX: originX, andTargetOriginOffset: self.maximumLeftDrawerWidth, maxOvershoot: maxOvershoot) + } else { + return self.maximumLeftDrawerWidth + } + } + + return originX + } + + fileprivate func originX(forDrawerOriginX originX: CGFloat, andTargetOriginOffset targetOffset: CGFloat, maxOvershoot: CGFloat) -> CGFloat { + let delta: CGFloat = abs(originX - targetOffset) + let maxLinearPercentage = DrawerOvershootLinearRangePercentage + let nonLinearRange = maxOvershoot * maxLinearPercentage + let nonLinearScalingDelta = delta - nonLinearRange + let overshoot = nonLinearRange + nonLinearScalingDelta * nonLinearRange / sqrt(pow(nonLinearScalingDelta, 2.0) + 15000) + + if delta < nonLinearRange { + return originX + } else if targetOffset < 0 { + return targetOffset - round(overshoot) + } else { + return targetOffset + round(overshoot) + } + } + + // MARK: - Helpers + + fileprivate func setupGestureRecognizers() { + let pan = UIPanGestureRecognizer(target: self, action: #selector(panGestureCallback(_:))) + pan.delegate = self + self.view.addGestureRecognizer(pan) + + let tap = UITapGestureRecognizer(target: self, action: #selector(tapGestureCallback(_:))) + tap.delegate = self + self.view.addGestureRecognizer(tap) + } + + fileprivate func childViewController(for drawerSide: DrawerSide) -> UIViewController? { + var childViewController: UIViewController? + + switch drawerSide { + case .left: + childViewController = self.leftDrawerViewController + case .right: + childViewController = self.rightDrawerViewController + case .none: + childViewController = self.centerViewController + } + + return childViewController + } + + fileprivate func sideDrawerViewController(for drawerSide: DrawerSide) -> UIViewController? { + var sideDrawerViewController: UIViewController? + + if drawerSide != .none { + sideDrawerViewController = self.childViewController(for: drawerSide) + } + + return sideDrawerViewController + } + + fileprivate func prepareToPresentDrawer(for drawer: DrawerSide, animated: Bool) { + var drawerToHide: DrawerSide = .none + + if drawer == .left { + drawerToHide = .right + } else if drawer == .right { + drawerToHide = .left + } + + if let sideDrawerViewControllerToHide = self.sideDrawerViewController(for: drawerToHide) { + self.childControllerContainerView.sendSubview(toBack: sideDrawerViewControllerToHide.view) + sideDrawerViewControllerToHide.view.isHidden = true + } + + if let sideDrawerViewControllerToPresent = self.sideDrawerViewController(for: drawer) { + sideDrawerViewControllerToPresent.view.isHidden = false + self.resetDrawerVisualState(for: drawer) + sideDrawerViewControllerToPresent.view.frame = sideDrawerViewControllerToPresent.evo_visibleDrawerFrame + self.updateDrawerVisualState(for: drawer, percentVisible: 0.0) + sideDrawerViewControllerToPresent.beginAppearanceTransition(true, animated: animated) + } + } + + fileprivate func updateShadowForCenterView() { + if self.showsShadows { + self.centerContainerView.layer.masksToBounds = false + self.centerContainerView.layer.shadowRadius = shadowRadius + self.centerContainerView.layer.shadowOpacity = shadowOpacity + + /** In the event this gets called a lot, we won't update the shadowPath + unless it needs to be updated (like during rotation) */ + if let shadowPath = centerContainerView.layer.shadowPath { + let currentPath = shadowPath.boundingBoxOfPath + + if currentPath.equalTo(centerContainerView.bounds) == false { + centerContainerView.layer.shadowPath = UIBezierPath(rect: centerContainerView.bounds).cgPath + } + } else { + self.centerContainerView.layer.shadowPath = UIBezierPath(rect: self.centerContainerView.bounds).cgPath + } + } else if self.centerContainerView.layer.shadowPath != nil { + self.centerContainerView.layer.shadowRadius = 0.0 + self.centerContainerView.layer.shadowOpacity = 0.0 + self.centerContainerView.layer.shadowPath = nil + self.centerContainerView.layer.masksToBounds = true + } + } + + fileprivate func animationDuration(forAnimationDistance distance: CGFloat) -> TimeInterval { + return TimeInterval(max(distance / self.animationVelocity, DrawerMinimumAnimationDuration)) + } + + // MARK: - Size Methods + + /** + Sets the maximum width of the left drawer view controller. + + If the drawer is open, and `animated` is YES, it will animate the drawer frame as well as adjust the center view controller. If the drawer is not open, this change will take place immediately. + + - parameter width: The new width of left drawer view controller. This must be greater than zero. + - parameter animated: Determines whether the drawer should be adjusted with an animation. + - parameter completion: The block called when the animation is finished. + + */ + open func setMaximumLeftDrawerWidth(_ width: CGFloat, animated: Bool, completion: ((Bool) -> Void)?) { + self.setMaximumDrawerWidth(width, forSide: .left, animated: animated, completion: completion) + } + + /** + Sets the maximum width of the right drawer view controller. + + If the drawer is open, and `animated` is YES, it will animate the drawer frame as well as adjust the center view controller. If the drawer is not open, this change will take place immediately. + + - parameter width: The new width of right drawer view controller. This must be greater than zero. + - parameter animated: Determines whether the drawer should be adjusted with an animation. + - parameter completion: The block called when the animation is finished. + + */ + open func setMaximumRightDrawerWidth(_ width: CGFloat, animated: Bool, completion: ((Bool) -> Void)?) { + self.setMaximumDrawerWidth(width, forSide: .right, animated: animated, completion: completion) + } + + fileprivate func setMaximumDrawerWidth(_ width: CGFloat, forSide drawerSide: DrawerSide, animated: Bool, completion: ((Bool) -> Void)?) { + assert({ () -> Bool in + return width > 0 + }(), "width must be greater than 0") + + assert({ () -> Bool in + return drawerSide != .none + }(), "drawerSide cannot be .None") + + if let sideDrawerViewController = self.sideDrawerViewController(for: drawerSide) { + var oldWidth: CGFloat = 0.0 + var drawerSideOriginCorrection: NSInteger = 1 + + if drawerSide == .left { + oldWidth = self._maximumLeftDrawerWidth + self._maximumLeftDrawerWidth = width + } else if (drawerSide == .right) { + oldWidth = self._maximumRightDrawerWidth + self._maximumRightDrawerWidth = width + drawerSideOriginCorrection = -1 + } + + let distance: CGFloat = abs(width - oldWidth) + let duration: TimeInterval = animated ? self.animationDuration(forAnimationDistance: distance) : 0.0 + + if self.openSide == drawerSide { + var newCenterRect = self.centerContainerView.frame + newCenterRect.origin.x = CGFloat(drawerSideOriginCorrection) * width + + UIView.animate(withDuration: duration, delay: 0.0, usingSpringWithDamping: self.drawerDampingFactor, initialSpringVelocity: self.animationVelocity / distance, options: [], animations: { () -> Void in + self.centerContainerView.frame = newCenterRect + sideDrawerViewController.view.frame = sideDrawerViewController.evo_visibleDrawerFrame + }, completion: { (finished) -> Void in + completion?(finished) + return + }) + } else { + sideDrawerViewController.view.frame = sideDrawerViewController.evo_visibleDrawerFrame + completion?(true) + } + } + } + + // MARK: - Setters + + fileprivate func setRightDrawer(_ rightDrawerViewController: UIViewController?) { + self.setDrawer(rightDrawerViewController, for: .right) + } + + fileprivate func setLeftDrawer(_ leftDrawerViewController: UIViewController?) { + self.setDrawer(leftDrawerViewController, for: .left) + } + + fileprivate func setDrawer(_ viewController: UIViewController?, for drawerSide: DrawerSide) { + assert({ () -> Bool in + return drawerSide != .none + }(), "drawerSide cannot be .None") + + let currentSideViewController = self.sideDrawerViewController(for: drawerSide) + + if currentSideViewController == viewController { + return + } + + if currentSideViewController != nil { + currentSideViewController!.beginAppearanceTransition(false, animated: false) + currentSideViewController!.view.removeFromSuperview() + currentSideViewController!.endAppearanceTransition() + currentSideViewController!.willMove(toParentViewController: nil) + currentSideViewController!.removeFromParentViewController() + } + + var autoResizingMask = UIViewAutoresizing() + + if drawerSide == .left { + self._leftDrawerViewController = viewController + autoResizingMask = [.flexibleRightMargin, .flexibleHeight] + } else if drawerSide == .right { + self._rightDrawerViewController = viewController + autoResizingMask = [.flexibleLeftMargin, .flexibleHeight] + } + + if viewController != nil { + self.addChildViewController(viewController!) + + if (self.openSide == drawerSide) && (self.childControllerContainerView.subviews as NSArray).contains(self.centerContainerView) { + self.childControllerContainerView.insertSubview(viewController!.view, belowSubview: self.centerContainerView) + viewController!.beginAppearanceTransition(true, animated: false) + viewController!.endAppearanceTransition() + } else { + self.childControllerContainerView.addSubview(viewController!.view) + self.childControllerContainerView.sendSubview(toBack: viewController!.view) + viewController!.view.isHidden = true + } + + viewController!.didMove(toParentViewController: self) + viewController!.view.autoresizingMask = autoResizingMask + viewController!.view.frame = viewController!.evo_visibleDrawerFrame + } + } + + // MARK: - Updating the Center View Controller + + fileprivate func setCenter(_ centerViewController: UIViewController?, animated: Bool) { + if self._centerViewController == centerViewController { + return + } + + if let oldCenterViewController = self._centerViewController { + oldCenterViewController.willMove(toParentViewController: nil) + + if animated == false { + oldCenterViewController.beginAppearanceTransition(false, animated: false) + } + + oldCenterViewController.removeFromParentViewController() + oldCenterViewController.view.removeFromSuperview() + + if animated == false { + oldCenterViewController.endAppearanceTransition() + } + } + + self._centerViewController = centerViewController + + if self._centerViewController != nil { + self.addChildViewController(self._centerViewController!) + self._centerViewController!.view.frame = self.childControllerContainerView.bounds + self.centerContainerView.addSubview(self._centerViewController!.view) + self.childControllerContainerView.bringSubview(toFront: self.centerContainerView) + self._centerViewController!.view.autoresizingMask = [.flexibleWidth, .flexibleHeight] + self.updateShadowForCenterView() + + if animated == false { + // If drawer is offscreen, then viewWillAppear: will take care of this + if self.view.window != nil { + self._centerViewController!.beginAppearanceTransition(true, animated: false) + self._centerViewController!.endAppearanceTransition() + } + + self._centerViewController!.didMove(toParentViewController: self) + } + } + } + + /** + Sets the new `centerViewController`. + + This sets the view controller and will automatically adjust the frame based on the current state of the drawer controller. If `closeAnimated` is YES, it will immediately change the center view controller, and close the drawer from its current position. + + - parameter centerViewController: The new `centerViewController`. + - parameter closeAnimated: Determines whether the drawer should be closed with an animation. + - parameter completion: The block called when the animation is finsihed. + + */ + open func setCenter(_ newCenterViewController: UIViewController, withCloseAnimation animated: Bool, completion: ((Bool) -> Void)?) { + var animated = animated + + if self.openSide == .none { + // If a side drawer isn't open, there is nothing to animate + animated = false + } + + let forwardAppearanceMethodsToCenterViewController = (self.centerViewController! == newCenterViewController) == false + self.setCenter(newCenterViewController, animated: animated) + + if animated { + self.updateDrawerVisualState(for: self.openSide, percentVisible: 1.0) + + if forwardAppearanceMethodsToCenterViewController { + self.centerViewController!.beginAppearanceTransition(true, animated: animated) + } + + self.closeDrawer(animated: animated, completion: { (finished) in + if forwardAppearanceMethodsToCenterViewController { + self.centerViewController!.endAppearanceTransition() + self.centerViewController!.didMove(toParentViewController: self) + } + + completion?(finished) + }) + } else { + completion?(true) + } + } + + /** + Sets the new `centerViewController`. + + This sets the view controller and will automatically adjust the frame based on the current state of the drawer controller. If `closeFullAnimated` is YES, the current center view controller will animate off the screen, the new center view controller will then be set, followed by the drawer closing across the full width of the screen. + + - parameter newCenterViewController: The new `centerViewController`. + - parameter fullCloseAnimated: Determines whether the drawer should be closed with an animation. + - parameter completion: The block called when the animation is finsihed. + + */ + open func setCenter(_ newCenterViewController: UIViewController, withFullCloseAnimation animated: Bool, completion: ((Bool) -> Void)?) { + if self.openSide != .none && animated { + let forwardAppearanceMethodsToCenterViewController = (self.centerViewController! == newCenterViewController) == false + let sideDrawerViewController = self.sideDrawerViewController(for: self.openSide) + + var targetClosePoint: CGFloat = 0.0 + + if self.openSide == .right { + targetClosePoint = -self.childControllerContainerView.bounds.width + } else if self.openSide == .left { + targetClosePoint = self.childControllerContainerView.bounds.width + } + + let distance: CGFloat = abs(self.centerContainerView.frame.origin.x - targetClosePoint) + let firstDuration = self.animationDuration(forAnimationDistance: distance) + + var newCenterRect = self.centerContainerView.frame + + self.animatingDrawer = animated + + let oldCenterViewController = self.centerViewController + + if forwardAppearanceMethodsToCenterViewController { + oldCenterViewController?.beginAppearanceTransition(false, animated: animated) + } + + newCenterRect.origin.x = targetClosePoint + + UIView.animate(withDuration: firstDuration, delay: 0.0, usingSpringWithDamping: self.drawerDampingFactor, initialSpringVelocity: distance / self.animationVelocity, options: [], animations: { () -> Void in + self.centerContainerView.frame = newCenterRect + sideDrawerViewController?.view.frame = self.childControllerContainerView.bounds + }, completion: { (finished) -> Void in + let oldCenterRect = self.centerContainerView.frame + self.setCenter(newCenterViewController, animated: animated) + self.centerContainerView.frame = oldCenterRect + self.updateDrawerVisualState(for: self.openSide, percentVisible: 1.0) + + if forwardAppearanceMethodsToCenterViewController { + oldCenterViewController?.endAppearanceTransition() + self.centerViewController?.beginAppearanceTransition(true, animated: animated) + } + + sideDrawerViewController?.beginAppearanceTransition(false, animated: animated) + + UIView.animate(withDuration: self.animationDuration(forAnimationDistance: self.childControllerContainerView.bounds.width), delay: DrawerDefaultFullAnimationDelay, usingSpringWithDamping: self.drawerDampingFactor, initialSpringVelocity: self.childControllerContainerView.bounds.width / self.animationVelocity, options: [], animations: { () -> Void in + self.centerContainerView.frame = self.childControllerContainerView.bounds + self.updateDrawerVisualState(for: self.openSide, percentVisible: 0.0) + }, completion: { (finished) -> Void in + if forwardAppearanceMethodsToCenterViewController { + self.centerViewController?.endAppearanceTransition() + self.centerViewController?.didMove(toParentViewController: self) + } + + sideDrawerViewController?.endAppearanceTransition() + self.resetDrawerVisualState(for: self.openSide) + + if sideDrawerViewController != nil { + sideDrawerViewController!.view.frame = sideDrawerViewController!.evo_visibleDrawerFrame + } + + self.openSide = .none + self.animatingDrawer = false + + completion?(finished) + }) + }) + } else { + self.setCenter(newCenterViewController, animated: animated) + + if self.openSide != .none { + self.closeDrawer(animated: animated, completion: completion) + } else if completion != nil { + completion!(true) + } + } + } + + // MARK: - Bounce Methods + + /** + Bounce preview for the specified `drawerSide` a distance of 40 points. + + - parameter drawerSide: The drawer to preview. This value cannot be `DrawerSideNone`. + - parameter completion: The block called when the animation is finsihed. + + */ + open func bouncePreview(for drawerSide: DrawerSide, completion: ((Bool) -> Void)?) { + assert({ () -> Bool in + return drawerSide != .none + }(), "drawerSide cannot be .None") + + self.bouncePreview(for: drawerSide, distance: DrawerDefaultBounceDistance, completion: nil) + } + + /** + Bounce preview for the specified `drawerSide`. + + - parameter drawerSide: The drawer side to preview. This value cannot be `DrawerSideNone`. + - parameter distance: The distance to bounce. + - parameter completion: The block called when the animation is finsihed. + + */ + open func bouncePreview(for drawerSide: DrawerSide, distance: CGFloat, completion: ((Bool) -> Void)?) { + assert({ () -> Bool in + return drawerSide != .none + }(), "drawerSide cannot be .None") + + let sideDrawerViewController = self.sideDrawerViewController(for: drawerSide) + + if sideDrawerViewController == nil || self.openSide != .none { + completion?(false) + return + } else { + self.prepareToPresentDrawer(for: drawerSide, animated: true) + + self.updateDrawerVisualState(for: drawerSide, percentVisible: 1.0) + + CATransaction.begin() + CATransaction.setCompletionBlock { + sideDrawerViewController!.endAppearanceTransition() + sideDrawerViewController!.beginAppearanceTransition(false, animated: false) + sideDrawerViewController!.endAppearanceTransition() + + completion?(true) + } + + let modifier: CGFloat = (drawerSide == .left) ? 1.0 : -1.0 + let animation = bounceKeyFrameAnimation(forDistance: distance * modifier, on: self.centerContainerView) + self.centerContainerView.layer.add(animation, forKey: "bouncing") + + CATransaction.commit() + } + } + + // MARK: - Gesture Handlers + + func tapGestureCallback(_ tapGesture: UITapGestureRecognizer) { + if self.openSide != .none && self.animatingDrawer == false { + self.closeDrawer(animated: true, completion: { (finished) in + if self.gestureCompletionBlock != nil { + self.gestureCompletionBlock!(self, tapGesture) + } + }) + } + } + + func panGestureCallback(_ panGesture: UIPanGestureRecognizer) { + switch panGesture.state { + case .began: + if self.animatingDrawer { + panGesture.isEnabled = false + } else { + self.startingPanRect = self.centerContainerView.frame + } + case .changed: + self.view.isUserInteractionEnabled = false + var newFrame = self.startingPanRect + let translatedPoint = panGesture.translation(in: self.centerContainerView) + newFrame.origin.x = self.roundedOriginX(forDrawerConstraints: self.startingPanRect.minX + translatedPoint.x) + newFrame = newFrame.integral + let xOffset = newFrame.origin.x + + var visibleSide: DrawerSide = .none + var percentVisible: CGFloat = 0.0 + + if xOffset > 0 { + visibleSide = .left + percentVisible = xOffset / self.maximumLeftDrawerWidth + } else if xOffset < 0 { + visibleSide = .right + percentVisible = abs(xOffset) / self.maximumRightDrawerWidth + } + + if let visibleSideDrawerViewController = self.sideDrawerViewController(for: visibleSide) { + if self.openSide != visibleSide { + // Handle disappearing the visible drawer + if let sideDrawerViewController = self.sideDrawerViewController(for: self.openSide) { + sideDrawerViewController.beginAppearanceTransition(false, animated: false) + sideDrawerViewController.endAppearanceTransition() + } + + // Drawer is about to become visible + self.prepareToPresentDrawer(for: visibleSide, animated: false) + visibleSideDrawerViewController.endAppearanceTransition() + self.openSide = visibleSide + } else if visibleSide == .none { + self.openSide = .none + } + + self.updateDrawerVisualState(for: visibleSide, percentVisible: percentVisible) + self.centerContainerView.frame.origin.x = newFrame.origin.x + } + case .ended, .cancelled: + self.startingPanRect = CGRect.null + let velocity = panGesture.velocity(in: self.childControllerContainerView) + self.finishAnimationForPanGesture(withXVelocity: velocity.x) { finished in + if self.gestureCompletionBlock != nil { + self.gestureCompletionBlock!(self, panGesture) + } + } + panGesture.isEnabled = true + self.view.isUserInteractionEnabled = true + default: + break + } + } + + // MARK: - Open / Close Methods + + // DrawerSide enum is not exported to Objective-C, so use these two methods instead + open func toggleLeftDrawerSide(animated: Bool, completion: ((Bool) -> Void)?) { + self.toggleDrawerSide(.left, animated: animated, completion: completion) + } + + open func toggleRightDrawerSide(animated: Bool, completion: ((Bool) -> Void)?) { + self.toggleDrawerSide(.right, animated: animated, completion: completion) + } + + /** + Toggles the drawer open/closed based on the `drawer` passed in. + + Note that if you attempt to toggle a drawer closed while the other is open, nothing will happen. For example, if you pass in DrawerSideLeft, but the right drawer is open, nothing will happen. In addition, the completion block will be called with the finished flag set to NO. + + - parameter drawerSide: The `DrawerSide` to toggle. This value cannot be `DrawerSideNone`. + - parameter animated: Determines whether the `drawer` should be toggle animated. + - parameter completion: The block that is called when the toggle is complete, or if no toggle took place at all. + + */ + open func toggleDrawerSide(_ drawerSide: DrawerSide, animated: Bool, completion: ((Bool) -> Void)?) { + assert({ () -> Bool in + return drawerSide != .none + }(), "drawerSide cannot be .None") + + if self.openSide == DrawerSide.none { + self.openDrawerSide(drawerSide, animated: animated, completion: completion) + } else { + if (drawerSide == DrawerSide.left && self.openSide == DrawerSide.left) || (drawerSide == DrawerSide.right && self.openSide == DrawerSide.right) { + self.closeDrawer(animated: animated, completion: completion) + } else if completion != nil { + completion!(false) + } + } + } + + /** + Opens the `drawer` passed in. + + - parameter drawerSide: The `DrawerSide` to open. This value cannot be `DrawerSideNone`. + - parameter animated: Determines whether the `drawer` should be open animated. + - parameter completion: The block that is called when the toggle is open. + + */ + open func openDrawerSide(_ drawerSide: DrawerSide, animated: Bool, completion: ((Bool) -> Void)?) { + assert({ () -> Bool in + return drawerSide != .none + }(), "drawerSide cannot be .None") + + self.openDrawerSide(drawerSide, animated: animated, velocity: self.animationVelocity, animationOptions: [], completion: completion) + } + + fileprivate func openDrawerSide(_ drawerSide: DrawerSide, animated: Bool, velocity: CGFloat, animationOptions options: UIViewAnimationOptions, completion: ((Bool) -> Void)?) { + assert({ () -> Bool in + return drawerSide != .none + }(), "drawerSide cannot be .None") + + if self.animatingDrawer { + completion?(false) + } else { + self.animatingDrawer = animated + let sideDrawerViewController = self.sideDrawerViewController(for: drawerSide) + + if self.openSide != drawerSide { + self.prepareToPresentDrawer(for: drawerSide, animated: animated) + } + + if sideDrawerViewController != nil { + var newFrame: CGRect + let oldFrame = self.centerContainerView.frame + + if drawerSide == .left { + newFrame = self.centerContainerView.frame + newFrame.origin.x = self._maximumLeftDrawerWidth + } else { + newFrame = self.centerContainerView.frame + newFrame.origin.x = 0 - self._maximumRightDrawerWidth + } + + let distance = abs(oldFrame.minX - newFrame.origin.x) + let duration: TimeInterval = animated ? TimeInterval(max(distance / abs(velocity), DrawerMinimumAnimationDuration)) : 0.0 + + UIView.animate(withDuration: duration, delay: 0.0, usingSpringWithDamping: self.drawerDampingFactor, initialSpringVelocity: velocity / distance, options: options, animations: { () -> Void in + self.setNeedsStatusBarAppearanceUpdate() + self.centerContainerView.frame = newFrame + self.updateDrawerVisualState(for: drawerSide, percentVisible: 1.0) + }, completion: { (finished) -> Void in + if drawerSide != self.openSide { + sideDrawerViewController!.endAppearanceTransition() + } + + self.openSide = drawerSide + + self.resetDrawerVisualState(for: drawerSide) + self.animatingDrawer = false + + completion?(finished) + }) + } + } + } + + /** + Closes the open drawer. + + - parameter animated: Determines whether the drawer side should be closed animated + - parameter completion: The block that is called when the close is complete + + */ + open func closeDrawer(animated: Bool, completion: ((Bool) -> Void)?) { + self.closeDrawer(animated: animated, velocity: self.animationVelocity, animationOptions: [], completion: completion) + } + + fileprivate func closeDrawer(animated: Bool, velocity: CGFloat, animationOptions options: UIViewAnimationOptions, completion: ((Bool) -> Void)?) { + if self.animatingDrawer { + completion?(false) + } else { + self.animatingDrawer = animated + let newFrame = self.childControllerContainerView.bounds + + let distance = abs(self.centerContainerView.frame.minX) + let duration: TimeInterval = animated ? TimeInterval(max(distance / abs(velocity), DrawerMinimumAnimationDuration)) : 0.0 + + let leftDrawerVisible = self.centerContainerView.frame.minX > 0 + let rightDrawerVisible = self.centerContainerView.frame.minX < 0 + + var visibleSide: DrawerSide = .none + var percentVisible: CGFloat = 0.0 + + if leftDrawerVisible { + let visibleDrawerPoint = self.centerContainerView.frame.minX + percentVisible = max(0.0, visibleDrawerPoint / self._maximumLeftDrawerWidth) + visibleSide = .left + } else if rightDrawerVisible { + let visibleDrawerPoints = self.centerContainerView.frame.width - self.centerContainerView.frame.maxX + percentVisible = max(0.0, visibleDrawerPoints / self._maximumRightDrawerWidth) + visibleSide = .right + } + + let sideDrawerViewController = self.sideDrawerViewController(for: visibleSide) + + self.updateDrawerVisualState(for: visibleSide, percentVisible: percentVisible) + sideDrawerViewController?.beginAppearanceTransition(false, animated: animated) + + UIView.animate(withDuration: duration, delay: 0.0, usingSpringWithDamping: self.drawerDampingFactor, initialSpringVelocity: velocity / distance, options: options, animations: { () -> Void in + self.setNeedsStatusBarAppearanceUpdate() + self.centerContainerView.frame = newFrame + self.updateDrawerVisualState(for: visibleSide, percentVisible: 0.0) + }, completion: { (finished) -> Void in + sideDrawerViewController?.endAppearanceTransition() + self.openSide = .none + self.resetDrawerVisualState(for: visibleSide) + self.animatingDrawer = false + completion?(finished) + }) + } + } + + // MARK: - UIViewController + + open override func viewDidLoad() { + super.viewDidLoad() + + self.view.backgroundColor = UIColor.black + + self.setupGestureRecognizers() + } + + open override func viewWillAppear(_ animated: Bool) { + super.viewWillAppear(animated) + self.centerViewController?.beginAppearanceTransition(true, animated: animated) + + if self.openSide == .left { + self.leftDrawerViewController?.beginAppearanceTransition(true, animated: animated) + } else if self.openSide == .right { + self.rightDrawerViewController?.beginAppearanceTransition(true, animated: animated) + } + } + + open override func viewDidAppear(_ animated: Bool) { + super.viewDidAppear(animated) + + self.updateShadowForCenterView() + self.centerViewController?.endAppearanceTransition() + + if self.openSide == .left { + self.leftDrawerViewController?.endAppearanceTransition() + } else if self.openSide == .right { + self.rightDrawerViewController?.endAppearanceTransition() + } + } + + open override func viewWillDisappear(_ animated: Bool) { + super.viewWillDisappear(animated) + self.centerViewController?.beginAppearanceTransition(false, animated: animated) + + if self.openSide == .left { + self.leftDrawerViewController?.beginAppearanceTransition(false, animated: animated) + } else if self.openSide == .right { + self.rightDrawerViewController?.beginAppearanceTransition(false, animated: animated) + } + } + + open override func viewDidDisappear(_ animated: Bool) { + super.viewDidDisappear(animated) + self.centerViewController?.endAppearanceTransition() + + if self.openSide == .left { + self.leftDrawerViewController?.endAppearanceTransition() + } else if self.openSide == .right { + self.rightDrawerViewController?.endAppearanceTransition() + } + } + + open override var shouldAutomaticallyForwardAppearanceMethods : Bool { + return false + } + + // MARK: - Rotation + + open override func viewWillTransition(to size: CGSize, with coordinator: UIViewControllerTransitionCoordinator) { + super.viewWillTransition(to: size, with: coordinator) + + //If a rotation begins, we are going to cancel the current gesture and reset transform and anchor points so everything works correctly + var gestureInProgress = false + + for gesture in self.view.gestureRecognizers! as [UIGestureRecognizer] { + if gesture.state == .changed { + gesture.isEnabled = false + gesture.isEnabled = true + gestureInProgress = true + } + + if gestureInProgress { + self.resetDrawerVisualState(for: self.openSide) + } + } + + coordinator.animate(alongsideTransition: { (context) -> Void in + //We need to support the shadow path rotation animation + //Inspired from here: http://blog.radi.ws/post/8348898129/calayers-shadowpath-and-uiview-autoresizing + if self.showsShadows { + let oldShadowPath = self.centerContainerView.layer.shadowPath + + self.updateShadowForCenterView() + + if oldShadowPath != nil { + let transition = CABasicAnimation(keyPath: "shadowPath") + transition.fromValue = oldShadowPath + transition.timingFunction = CAMediaTimingFunction(name: kCAMediaTimingFunctionEaseInEaseOut) + transition.duration = context.transitionDuration + self.centerContainerView.layer.add(transition, forKey: "transition") + } + } + }, completion:nil) + } + + // MARK: - UIGestureRecognizerDelegate + + open func gestureRecognizer(_ gestureRecognizer: UIGestureRecognizer, shouldReceive touch: UITouch) -> Bool { + if self.openSide == .none { + let possibleOpenGestureModes = self.possibleOpenGestureModes(for: gestureRecognizer, with: touch) + + return !self.openDrawerGestureModeMask.intersection(possibleOpenGestureModes).isEmpty + } else { + let possibleCloseGestureModes = self.possibleCloseGestureModes(for: gestureRecognizer, with: touch) + + return !self.closeDrawerGestureModeMask.intersection(possibleCloseGestureModes).isEmpty + } + } + + // MARK: - Gesture Recognizer Delegate Helpers + + func possibleCloseGestureModes(for gestureRecognizer: UIGestureRecognizer, with touch: UITouch) -> CloseDrawerGestureMode { + let point = touch.location(in: self.childControllerContainerView) + var possibleCloseGestureModes: CloseDrawerGestureMode = [] + + if gestureRecognizer.isKind(of: UITapGestureRecognizer.self) { + if self.isPointContained(withinNavigationRect: point) { + possibleCloseGestureModes.insert(.tapNavigationBar) + } + + if self.isPointContained(withinCenterViewContentRect: point) { + possibleCloseGestureModes.insert(.tapCenterView) + } + } else if gestureRecognizer.isKind(of: UIPanGestureRecognizer.self) { + if self.isPointContained(withinNavigationRect: point) { + possibleCloseGestureModes.insert(.panningNavigationBar) + } + + if self.isPointContained(withinCenterViewContentRect: point) { + possibleCloseGestureModes.insert(.panningCenterView) + } + + if self.isPointContained(withinRightBezelRect: point) && self.openSide == .left { + possibleCloseGestureModes.insert(.bezelPanningCenterView) + } + + if self.isPointContained(withinLeftBezelRect: point) && self.openSide == .right { + possibleCloseGestureModes.insert(.bezelPanningCenterView) + } + + if self.isPointContained(withinCenterViewContentRect: point) == false && self.isPointContained(withinNavigationRect: point) == false { + possibleCloseGestureModes.insert(.panningDrawerView) + } + } + + if self.closeDrawerGestureModeMask.contains(.custom) && self.gestureShouldRecognizeTouchBlock != nil { + if self.gestureShouldRecognizeTouchBlock!(self, gestureRecognizer, touch) { + possibleCloseGestureModes.insert(.custom) + } + } + + return possibleCloseGestureModes + } + + func possibleOpenGestureModes(for gestureRecognizer: UIGestureRecognizer, with touch: UITouch) -> OpenDrawerGestureMode { + let point = touch.location(in: self.childControllerContainerView) + var possibleOpenGestureModes: OpenDrawerGestureMode = [] + + if gestureRecognizer.isKind(of: UIPanGestureRecognizer.self) { + if self.isPointContained(withinNavigationRect: point) { + possibleOpenGestureModes.insert(.panningNavigationBar) + } + + if self.isPointContained(withinCenterViewContentRect: point) { + possibleOpenGestureModes.insert(.panningCenterView) + } + + if self.isPointContained(withinLeftBezelRect: point) && self.leftDrawerViewController != nil { + possibleOpenGestureModes.insert(.bezelPanningCenterView) + } + + if self.isPointContained(withinRightBezelRect: point) && self.rightDrawerViewController != nil { + possibleOpenGestureModes.insert(.bezelPanningCenterView) + } + } + + if self.openDrawerGestureModeMask.contains(.custom) && self.gestureShouldRecognizeTouchBlock != nil { + if self.gestureShouldRecognizeTouchBlock!(self, gestureRecognizer, touch) { + possibleOpenGestureModes.insert(.custom) + } + } + + return possibleOpenGestureModes + } + + func isPointContained(withinNavigationRect point: CGPoint) -> Bool { + var navigationBarRect = CGRect.null + + if let centerViewController = self.centerViewController { + if centerViewController.isKind(of: UINavigationController.self) { + let navBar = (self.centerViewController as! UINavigationController).navigationBar + navigationBarRect = navBar.convert(navBar.bounds, to: self.childControllerContainerView) + navigationBarRect = navigationBarRect.intersection(self.childControllerContainerView.bounds) + } + } + + return navigationBarRect.contains(point) + } + + func isPointContained(withinCenterViewContentRect point: CGPoint) -> Bool { + var centerViewContentRect = self.centerContainerView.frame + centerViewContentRect = centerViewContentRect.intersection(self.childControllerContainerView.bounds) + + return centerViewContentRect.contains(point) && self.isPointContained(withinNavigationRect: point) == false + } + + func isPointContained(withinLeftBezelRect point: CGPoint) -> Bool { + let (leftBezelRect, _) = childControllerContainerView.bounds.divided(atDistance: bezelRange, from: .minXEdge) + + return leftBezelRect.contains(point) && self.isPointContained(withinCenterViewContentRect: point) + } + + func isPointContained(withinRightBezelRect point: CGPoint) -> Bool { + let (rightBezelRect, _) = childControllerContainerView.bounds.divided(atDistance: bezelRange, from: .maxXEdge) + + return rightBezelRect.contains(point) && self.isPointContained(withinCenterViewContentRect: point) + } +} diff --git a/GeneralUtils/GeneralUtils/ui/DrawerController/DrawerVisualState.swift b/GeneralUtils/GeneralUtils/ui/DrawerController/DrawerVisualState.swift new file mode 100644 index 0000000..2a36450 --- /dev/null +++ b/GeneralUtils/GeneralUtils/ui/DrawerController/DrawerVisualState.swift @@ -0,0 +1,193 @@ +// Copyright (c) 2014 evolved.io (http://evolved.io) +// +// Permission is hereby granted, free of charge, to any person obtaining a copy +// of this software and associated documentation files (the "Software"), to deal +// in the Software without restriction, including without limitation the rights +// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +// copies of the Software, and to permit persons to whom the Software is +// furnished to do so, subject to the following conditions: +// +// The above copyright notice and this permission notice shall be included in +// all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN +// THE SOFTWARE. + +import UIKit +import QuartzCore + +public struct DrawerVisualState { + + /** + Creates a slide and scale visual state block that gives an experience similar to Mailbox.app. It scales from 90% to 100%, and translates 50 pixels in the x direction. In addition, it also sets alpha from 0.0 to 1.0. + + - returns: The visual state block. + */ + public static var slideAndScaleVisualStateBlock: DrawerControllerDrawerVisualStateBlock { + let visualStateBlock: DrawerControllerDrawerVisualStateBlock = { (drawerController, drawerSide, percentVisible) -> Void in + let minScale: CGFloat = 0.9 + let scale: CGFloat = minScale + (percentVisible * (1.0-minScale)) + let scaleTransform = CATransform3DMakeScale(scale, scale, scale) + + let maxDistance: CGFloat = 50 + let distance: CGFloat = maxDistance * percentVisible + var translateTransform = CATransform3DIdentity + var sideDrawerViewController: UIViewController? + + if drawerSide == DrawerSide.left { + sideDrawerViewController = drawerController.leftDrawerViewController + translateTransform = CATransform3DMakeTranslation((maxDistance - distance), 0, 0) + } else if drawerSide == DrawerSide.right { + sideDrawerViewController = drawerController.rightDrawerViewController + translateTransform = CATransform3DMakeTranslation(-(maxDistance-distance), 0.0, 0.0) + } + + sideDrawerViewController?.view.layer.transform = CATransform3DConcat(scaleTransform, translateTransform) + sideDrawerViewController?.view.alpha = percentVisible + } + + return visualStateBlock + } + + /** + Creates a slide visual state block that gives the user an experience that slides at the same speed of the center view controller during animation. This is equal to calling `parallaxVisualStateBlockWithParallaxFactor:` with a parallax factor of 1.0. + + - returns: The visual state block. + */ + public static var slideVisualStateBlock: DrawerControllerDrawerVisualStateBlock { + return self.parallaxVisualStateBlock(parallaxFactor: 1.0) + } + + /** + Creates a swinging door visual state block that gives the user an experience that animates the drawer in along the hinge. + + - returns: The visual state block. + */ + public static var swingingDoorVisualStateBlock: DrawerControllerDrawerVisualStateBlock { + let visualStateBlock: DrawerControllerDrawerVisualStateBlock = { (drawerController, drawerSide, percentVisible) -> Void in + + var sideDrawerViewController: UIViewController? + var anchorPoint: CGPoint + var maxDrawerWidth: CGFloat = 0.0 + var xOffset: CGFloat + var angle: CGFloat = 0.0 + + if drawerSide == .left { + sideDrawerViewController = drawerController.leftDrawerViewController + anchorPoint = CGPoint(x: 1.0, y: 0.5) + maxDrawerWidth = max(drawerController.maximumLeftDrawerWidth, drawerController.visibleLeftDrawerWidth) + xOffset = -(maxDrawerWidth / 2) + maxDrawerWidth * percentVisible + angle = -CGFloat(M_PI_2) + percentVisible * CGFloat(M_PI_2) + } else { + sideDrawerViewController = drawerController.rightDrawerViewController + anchorPoint = CGPoint(x: 0.0, y: 0.5) + maxDrawerWidth = max(drawerController.maximumRightDrawerWidth, drawerController.visibleRightDrawerWidth) + xOffset = (maxDrawerWidth / 2) - maxDrawerWidth * percentVisible + angle = CGFloat(M_PI_2) - percentVisible * CGFloat(M_PI_2) + } + + sideDrawerViewController?.view.layer.anchorPoint = anchorPoint + sideDrawerViewController?.view.layer.shouldRasterize = true + sideDrawerViewController?.view.layer.rasterizationScale = UIScreen.main.scale + + var swingingDoorTransform: CATransform3D = CATransform3DIdentity + + if percentVisible <= 1.0 { + var identity: CATransform3D = CATransform3DIdentity + identity.m34 = -1.0 / 1000.0 + let rotateTransform: CATransform3D = CATransform3DRotate(identity, angle, + 0.0, 1.0, 0.0) + let translateTransform: CATransform3D = CATransform3DMakeTranslation(xOffset, 0.0, 0.0) + let concatTransform = CATransform3DConcat(rotateTransform, translateTransform) + + swingingDoorTransform = concatTransform + } else { + var overshootTransform = CATransform3DMakeScale(percentVisible, 1.0, 1.0) + var scalingModifier: CGFloat = 1.0 + + if (drawerSide == .right) { + scalingModifier = -1.0 + } + + overshootTransform = CATransform3DTranslate(overshootTransform, scalingModifier * maxDrawerWidth / 2, 0.0, 0.0) + swingingDoorTransform = overshootTransform + } + + sideDrawerViewController?.view.layer.transform = swingingDoorTransform + } + + return visualStateBlock + } + + /** + Creates a parallax experience that slides the side drawer view controller at a different rate than the center view controller during animation. For every parallaxFactor of points moved by the center view controller, the side drawer view controller will move 1 point. Passing in 1.0 is the equivalent of a applying a sliding animation, while passing in MAX_FLOAT is the equivalent of having no animation at all. + + - parameter parallaxFactor: The amount of parallax applied to the side drawer conroller. This value must be greater than 1.0. The closer the value is to 1.0, the faster the side drawer view controller will be parallaxing. + + - returns: The visual state block. + */ + public static func parallaxVisualStateBlock(parallaxFactor: CGFloat) -> DrawerControllerDrawerVisualStateBlock { + let visualStateBlock: DrawerControllerDrawerVisualStateBlock = { (drawerController, drawerSide, percentVisible) -> Void in + + assert({ () -> Bool in + return parallaxFactor >= 1.0 + }(), "parallaxFactor must be >= 1.0") + + var transform: CATransform3D = CATransform3DIdentity + var sideDrawerViewController: UIViewController? + + if (drawerSide == .left) { + sideDrawerViewController = drawerController.leftDrawerViewController + let distance: CGFloat = max(drawerController.maximumLeftDrawerWidth, drawerController.visibleLeftDrawerWidth) + + if (percentVisible <= 1.0) { + transform = CATransform3DMakeTranslation((-distance) / parallaxFactor + (distance * percentVisible / parallaxFactor), 0.0, 0.0) + } else { + transform = CATransform3DMakeScale(percentVisible, 1.0, 1.0) + transform = CATransform3DTranslate(transform, drawerController.maximumLeftDrawerWidth * (percentVisible - 1.0) / 2, 0.0, 0.0) + } + } else if (drawerSide == .right) { + sideDrawerViewController = drawerController.rightDrawerViewController + let distance: CGFloat = max(drawerController.maximumRightDrawerWidth, drawerController.visibleRightDrawerWidth) + + if (percentVisible <= 1.0) { + transform = CATransform3DMakeTranslation((distance) / parallaxFactor - (distance * percentVisible / parallaxFactor), 0.0, 0.0) + } else { + transform = CATransform3DMakeScale(percentVisible, 1.0, 1.0) + transform = CATransform3DTranslate(transform, -drawerController.maximumRightDrawerWidth * (percentVisible - 1.0) / 2, 0.0, 0.0) + } + } + + sideDrawerViewController?.view.layer.transform = transform + } + + return visualStateBlock + } + + public static var animatedHamburgerButtonVisualStateBlock: DrawerControllerDrawerVisualStateBlock { + let visualStateBlock: DrawerControllerDrawerVisualStateBlock = { (drawerController, drawerSide, percentVisible) -> Void in + + var hamburgerItem: DrawerBarButtonItem? + if let navController = drawerController.centerViewController as? UINavigationController { + if (drawerSide == .left) { + if let item = navController.topViewController!.navigationItem.leftBarButtonItem as? DrawerBarButtonItem { + hamburgerItem = item + } + } else if (drawerSide == .right) { + if let item = navController.topViewController!.navigationItem.rightBarButtonItem as? DrawerBarButtonItem { + hamburgerItem = item + } + } + } + + hamburgerItem?.animate(withPercentVisible: percentVisible, drawerSide: drawerSide) + } + + return visualStateBlock + } +} diff --git a/GeneralUtils/GeneralUtils/ui/DrawerController/DrawerVisualStateManager.swift b/GeneralUtils/GeneralUtils/ui/DrawerController/DrawerVisualStateManager.swift new file mode 100644 index 0000000..0a2c645 --- /dev/null +++ b/GeneralUtils/GeneralUtils/ui/DrawerController/DrawerVisualStateManager.swift @@ -0,0 +1,96 @@ +// Copyright (c) 2014 evolved.io (http://evolved.io) +// +// Permission is hereby granted, free of charge, to any person obtaining a copy +// of this software and associated documentation files (the "Software"), to deal +// in the Software without restriction, including without limitation the rights +// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +// copies of the Software, and to permit persons to whom the Software is +// furnished to do so, subject to the following conditions: +// +// The above copyright notice and this permission notice shall be included in +// all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN +// THE SOFTWARE. + +import UIKit + +enum DrawerAnimationType: Int { + case none + case slide + case slideAndScale + case swingingDoor + case parallax + case animatedBarButton +} + +public class DrawerVisualStateManager: NSObject { + var leftDrawerAnimationType: DrawerAnimationType = .parallax + var rightDrawerAnimationType: DrawerAnimationType = .parallax + + public class var sharedManager: DrawerVisualStateManager { + struct Static { + static let instance: DrawerVisualStateManager = DrawerVisualStateManager() + } + + return Static.instance + } + + public func drawerVisualStateBlock(for drawerSide: DrawerSide) -> DrawerControllerDrawerVisualStateBlock? { + var animationType: DrawerAnimationType + + if drawerSide == DrawerSide.left { + animationType = self.leftDrawerAnimationType + } else { + animationType = self.rightDrawerAnimationType + } + + var visualStateBlock: DrawerControllerDrawerVisualStateBlock? + + switch animationType { + case .slide: + visualStateBlock = DrawerVisualState.slideVisualStateBlock + case .slideAndScale: + visualStateBlock = DrawerVisualState.slideAndScaleVisualStateBlock + case .parallax: + visualStateBlock = DrawerVisualState.parallaxVisualStateBlock(parallaxFactor: 2.0) + case .swingingDoor: + visualStateBlock = DrawerVisualState.swingingDoorVisualStateBlock + case .animatedBarButton: + visualStateBlock = DrawerVisualState.animatedHamburgerButtonVisualStateBlock + default: + visualStateBlock = { drawerController, drawerSide, percentVisible in + var sideDrawerViewController: UIViewController? + var transform = CATransform3DIdentity + var maxDrawerWidth: CGFloat = 0.0 + + if drawerSide == .left { + sideDrawerViewController = drawerController.leftDrawerViewController + maxDrawerWidth = drawerController.maximumLeftDrawerWidth + } else if drawerSide == .right { + sideDrawerViewController = drawerController.rightDrawerViewController + maxDrawerWidth = drawerController.maximumRightDrawerWidth + } + + if percentVisible > 1.0 { + transform = CATransform3DMakeScale(percentVisible, 1.0, 1.0) + + if drawerSide == .left { + transform = CATransform3DTranslate(transform, maxDrawerWidth * (percentVisible - 1.0) / 2, 0.0, 0.0) + } else if drawerSide == .right { + transform = CATransform3DTranslate(transform, -maxDrawerWidth * (percentVisible - 1.0) / 2, 0.0, 0.0) + } + } + + sideDrawerViewController?.view.layer.transform = transform + } + } + + return visualStateBlock + } +} diff --git a/GeneralUtils/GeneralUtils/ui/GeneralMenuController.swift b/GeneralUtils/GeneralUtils/ui/GeneralMenuController.swift new file mode 100644 index 0000000..5b4fb25 --- /dev/null +++ b/GeneralUtils/GeneralUtils/ui/GeneralMenuController.swift @@ -0,0 +1,34 @@ +/** + - Can override + + func getTopBar() -> ViewTopBar { + return nil + } + + func btnMenuClick(view: UIView) { + if let drawerController = AppDelegate.getAppDelegate().drawerController { + if drawerController.openSide == DrawerSide.left { + drawerController.closeDrawer(animated: true, completion: nil) + } else { + drawerController.openDrawerSide(DrawerSide.left, animated: true, completion: nil) + } + } + } + */ + +import Foundation +import UIKit + +open class GeneralMenuController: UIViewController { + open func getTopBar() -> ViewTopBar! { + return nil + } + + open override func viewDidLoad() { + super.viewDidLoad() + getTopBar().leftButtonClick = btnMenuClick + } + + open func btnMenuClick(view: UIView) { + } +} diff --git a/GeneralUtils/GeneralUtils/ui/IContainerController.swift b/GeneralUtils/GeneralUtils/ui/IContainerController.swift new file mode 100644 index 0000000..8b78f56 --- /dev/null +++ b/GeneralUtils/GeneralUtils/ui/IContainerController.swift @@ -0,0 +1,77 @@ +import UIKit +import Foundation + +public protocol IContainerController: class { + func getContainerview() -> UIView + var currentViewController: UIViewController? { get set } + +} + +public extension IContainerController { + @discardableResult public func changeCurrentController(_ newViewController: UIViewController) -> UIViewController? { + var vc = self as? UIViewController + if vc == nil { + vc = getContainerview().parentViewController + } + guard let vcParent = vc else { return nil } + + newViewController.view.translatesAutoresizingMaskIntoConstraints = false + vcParent.addChildViewController(newViewController) + + if let oldViewController = self.currentViewController { + addSubview(newViewController.view, toView: self.getContainerview()) + oldViewController.willMove(toParentViewController: nil) + newViewController.view.alpha = 0 + newViewController.view.layoutIfNeeded() + UIView.animate(withDuration: 0.5, animations: { + newViewController.view.alpha = 1 + oldViewController.view.alpha = 0 + }, completion: { finished in + oldViewController.view.removeFromSuperview() + oldViewController.removeFromParentViewController() + newViewController.didMove(toParentViewController: vcParent) + }) + } else { + getContainerview().removeAllChild() + addSubview(newViewController.view, toView: self.getContainerview()) + } + currentViewController = newViewController + return newViewController + } + + public func changeCurrentView(view: UIView) { + view.translatesAutoresizingMaskIntoConstraints = false + let container = getContainerview() + if container.subviews.count == 0 { + addSubview(view, toView: container) + } else if container.subviews.count == 1 { + let oldView = container.subviews[0] + addSubview(view, toView: container) + view.alpha = 0 + view.layoutIfNeeded() + UIView.animate(withDuration: 0.5, animations: { + view.alpha = 1 + oldView.alpha = 0 + }, completion: { finished in + self.currentViewController?.removeFromParentViewController() + self.currentViewController = nil + oldView.removeFromSuperview() + }) + } else { + container.removeAllChild() + addSubview(view, toView: container) + } + } + + fileprivate func addSubview(_ subView: UIView, toView parentView: UIView) { + parentView.addSubview(subView) + + var viewBindingsDict = [String: AnyObject]() + viewBindingsDict["subView"] = subView + parentView.addConstraints(NSLayoutConstraint.constraints(withVisualFormat: "H:|[subView]|", + options: [], metrics: nil, views: viewBindingsDict)) + parentView.addConstraints(NSLayoutConstraint.constraints(withVisualFormat: "V:|[subView]|", + options: [], metrics: nil, views: viewBindingsDict)) + } + +} diff --git a/GeneralUtils/GeneralUtils/ui/PresentationDialog/AnimatedControllerFromBottom.swift b/GeneralUtils/GeneralUtils/ui/PresentationDialog/AnimatedControllerFromBottom.swift new file mode 100644 index 0000000..4916d59 --- /dev/null +++ b/GeneralUtils/GeneralUtils/ui/PresentationDialog/AnimatedControllerFromBottom.swift @@ -0,0 +1,75 @@ + +import UIKit + +public class AnimatedControllerFromBottom: NSObject, UIViewControllerAnimatedTransitioning { + + public var isPresentation: Bool = false + + public func transitionDuration(using transitionContext: UIViewControllerContextTransitioning?) -> TimeInterval { + return 0.25 + } + + public func animateTransition(using transitionContext: UIViewControllerContextTransitioning) { + let fromVC = transitionContext.viewController(forKey: UITransitionContextViewControllerKey.from) + let toVC = transitionContext.viewController(forKey: UITransitionContextViewControllerKey.to) + let fromView = fromVC?.view + let toView = toVC?.view + let containerView = transitionContext.containerView + let animationDuration = self.transitionDuration(using: transitionContext) + + // Animate in, out From right + // if isPresentation { + // containerView!.addSubview(toView!) + // } + // + // let animatingVC = isPresentation ? toVC : fromVC + // let animatingView = animatingVC?.view + // + // let finalFrameForVC = transitionContext.finalFrameForViewController(animatingVC!) + // var initialFrameForVC = finalFrameForVC + // initialFrameForVC.origin.x += initialFrameForVC.size.width; + // + // let initialFrame = isPresentation ? initialFrameForVC : finalFrameForVC + // let finalFrame = isPresentation ? finalFrameForVC : initialFrameForVC + // + // animatingView?.frame = initialFrame + // + // UIView.animateWithDuration(transitionDuration(transitionContext), delay: 0, usingSpringWithDamping: 300.0, initialSpringVelocity: 5.0, options: UIViewAnimationOptions.AllowUserInteraction, animations: { + // animatingView?.frame = finalFrame + // }, completion: { (value: Bool) in + // if !self.isPresentation { + // fromView?.removeFromSuperview() + // } + // transitionContext.completeTransition(true) + // }) + +// let offScreenRight = CGAffineTransformMakeTranslation(container.frame.width, 0) +// let offScreenLeft = CGAffineTransformMakeTranslation(-container.frame.width, 0) + + let offScreenBottom = CGAffineTransform(translationX: 0, y: (toView?.frame.height)!) + if self.isPresentation { + toView!.transform = offScreenBottom + toView!.layer.shadowColor = UIColor.black.cgColor + toView!.layer.shadowOffset = CGSize(width: 0.0, height: 2.0) + toView!.layer.shadowOpacity = 0.3 + toView!.layer.cornerRadius = 4.0 + toView!.clipsToBounds = true + + containerView.addSubview(toVC!.view) + + UIView.animate(withDuration: animationDuration, animations: { () -> Void in + toView!.transform = CGAffineTransform.identity + }, completion: { (finished) -> Void in + transitionContext.completeTransition(finished) + }) + } else { + UIView.animate(withDuration: animationDuration, animations: { () -> Void in + fromView!.alpha = 0.0 + fromView!.transform = offScreenBottom + }, completion: { (finished) -> Void in + fromView?.removeFromSuperview() + transitionContext.completeTransition(!transitionContext.transitionWasCancelled) + }) + } + } +} diff --git a/GeneralUtils/GeneralUtils/ui/PresentationDialog/AnimatedTransitioning.swift b/GeneralUtils/GeneralUtils/ui/PresentationDialog/AnimatedTransitioning.swift new file mode 100644 index 0000000..109b815 --- /dev/null +++ b/GeneralUtils/GeneralUtils/ui/PresentationDialog/AnimatedTransitioning.swift @@ -0,0 +1,80 @@ +// +// AnimatedTransitioning.swift +// SaveGifMoment +// +// Created by Philip Tran on 5/10/16. +// Copyright © 2016 Spirotity. All rights reserved. +// + +import UIKit + +public class AnimatedTransitioning: NSObject, UIViewControllerAnimatedTransitioning { + + public var isPresentation: Bool = false + + public func transitionDuration(using transitionContext: UIViewControllerContextTransitioning?) -> TimeInterval { + return 0.25 + } + + public func animateTransition(using transitionContext: UIViewControllerContextTransitioning) { + let fromVC = transitionContext.viewController(forKey: UITransitionContextViewControllerKey.from) + let toVC = transitionContext.viewController(forKey: UITransitionContextViewControllerKey.to) + let fromView = fromVC?.view + let toView = toVC?.view + let containerView = transitionContext.containerView + let animationDuration = self.transitionDuration(using: transitionContext) + +// Animate in, out From right +// if isPresentation { +// containerView!.addSubview(toView!) +// } +// +// let animatingVC = isPresentation ? toVC : fromVC +// let animatingView = animatingVC?.view +// +// let finalFrameForVC = transitionContext.finalFrameForViewController(animatingVC!) +// var initialFrameForVC = finalFrameForVC +// initialFrameForVC.origin.x += initialFrameForVC.size.width; +// +// let initialFrame = isPresentation ? initialFrameForVC : finalFrameForVC +// let finalFrame = isPresentation ? finalFrameForVC : initialFrameForVC +// +// animatingView?.frame = initialFrame +// +// UIView.animateWithDuration(transitionDuration(transitionContext), delay: 0, usingSpringWithDamping: 300.0, initialSpringVelocity: 5.0, options: UIViewAnimationOptions.AllowUserInteraction, animations: { +// animatingView?.frame = finalFrame +// }, completion: { (value: Bool) in +// if !self.isPresentation { +// fromView?.removeFromSuperview() +// } +// transitionContext.completeTransition(true) +// }) + + if self.isPresentation { + let toViewController = transitionContext.viewController(forKey: UITransitionContextViewControllerKey.to) as UIViewController? + + toView!.transform = CGAffineTransform(scaleX: 0.1, y: 0.1) + toView!.layer.shadowColor = UIColor.black.cgColor + toView!.layer.shadowOffset = CGSize(width: 0.0, height: 2.0) + toView!.layer.shadowOpacity = 0.3 + toView!.layer.cornerRadius = 4.0 + toView!.clipsToBounds = true + + containerView.addSubview(toViewController!.view) + + UIView.animate(withDuration: animationDuration, animations: { () -> Void in + toViewController!.view.transform = CGAffineTransform.identity + }, completion: { (finished) -> Void in + transitionContext.completeTransition(finished) + }) + } else { + UIView.animate(withDuration: animationDuration, animations: { () -> Void in + fromView!.alpha = 0.0 + fromView!.transform = CGAffineTransform(scaleX: 0.1, y: 0.1) + }, completion: { (finished) -> Void in + fromView?.removeFromSuperview() + transitionContext.completeTransition(!transitionContext.transitionWasCancelled) + }) + } + } +} diff --git a/GeneralUtils/GeneralUtils/ui/PresentationDialog/BaseUIPresentationController.swift b/GeneralUtils/GeneralUtils/ui/PresentationDialog/BaseUIPresentationController.swift new file mode 100644 index 0000000..887c547 --- /dev/null +++ b/GeneralUtils/GeneralUtils/ui/PresentationDialog/BaseUIPresentationController.swift @@ -0,0 +1,114 @@ +/** + Một dạng ViewControler mà show như dialog + + - + + */ + +import UIKit + +public class BaseUIPresentationController: UIPresentationController { + public var chromeView: UIView = UIView() + public var isDismisWhenTapOutSide = true + + public override init(presentedViewController: UIViewController, presenting presentingViewController: UIViewController?) { + super.init(presentedViewController: presentedViewController, presenting: presentingViewController) + chromeView.backgroundColor = UIColor(white: 0.0, alpha: 0.4) + chromeView.alpha = 0.0 + + let tap = UITapGestureRecognizer(target: self, action: #selector(BaseUIPresentationController.chromeViewTapped(_:))) + chromeView.addGestureRecognizer(tap) + } + + public func chromeViewTapped(_ gesture: UIGestureRecognizer) { + if isDismisWhenTapOutSide { + if (gesture.state == UIGestureRecognizerState.ended) { + presentingViewController.dismiss(animated: true, completion: nil) + } + } + } + + /** + function xác định vị trí của cái ViewControler sẽ show ra + */ + public override var frameOfPresentedViewInContainerView: CGRect { + var presentedViewFrame = CGRect.zero + let containerBounds = containerView!.bounds + presentedViewFrame.size = size(forChildContentContainer: presentedViewController, withParentContainerSize: containerBounds.size) + switch (self.presentedViewController as! BaseViewControllerShowTransculent).align() { + case Align.bottom: + presentedViewFrame.origin.x = (containerBounds.size.width - presentedViewFrame.size.width) / 2 + presentedViewFrame.origin.y = containerBounds.size.height - presentedViewFrame.size.height + 4 + break + default: + presentedViewFrame.origin.x = (containerBounds.size.width - presentedViewFrame.size.width) / 2 + presentedViewFrame.origin.y = (containerBounds.size.height - presentedViewFrame.size.height) / 2 + break + } + + return presentedViewFrame + +// let result = containerView!.bounds.insetBy(dx: 40, dy: 90) +// result. = 200 +// return result + } + + public override func size(forChildContentContainer container: UIContentContainer, withParentContainerSize parentSize: CGSize) -> CGSize { + let controler = self.presentedViewController as! BaseViewControllerShowTransculent + if controler.isFullWidth() { + return CGSize(width: CGFloat(parentSize.width), height: controler.getHeightContent()) + } + if controler.isCustomWidth() { + return CGSize(width: controler.getWidthContent(), height: controler.getHeightContent()) + } + + var width = floorf(Float(parentSize.width / 1.3)) + if width > 500 { + width = 500 + } + return CGSize(width: CGFloat(width), height: controler.getHeightContent()) + } + + public override func presentationTransitionWillBegin() { + chromeView.frame = self.containerView!.bounds + chromeView.alpha = 0.0 + containerView!.insertSubview(chromeView, at: 0) + let coordinator = presentedViewController.transitionCoordinator + if (coordinator != nil) { + coordinator!.animate(alongsideTransition: { + (context: UIViewControllerTransitionCoordinatorContext!) -> Void in + self.chromeView.alpha = 1.0 + }, completion: nil) + } else { + chromeView.alpha = 1.0 + } + } + + public override func dismissalTransitionWillBegin() { + let coordinator = presentedViewController.transitionCoordinator + if (coordinator != nil) { + coordinator!.animate(alongsideTransition: { + (context: UIViewControllerTransitionCoordinatorContext!) -> Void in + self.chromeView.alpha = 0.0 + }, completion: nil) + } else { + chromeView.alpha = 0.0 + } + } + /** + This sets the frames of the chrome and presented views to the bounds of the container view. If this isn’t done then they won’t resize if the device is rotated. + */ + public override func containerViewWillLayoutSubviews() { + chromeView.frame = containerView!.bounds + presentedView!.frame = frameOfPresentedViewInContainerView + } + + public override var shouldPresentInFullscreen: Bool { + return true + } + + public override var adaptivePresentationStyle: UIModalPresentationStyle { + return UIModalPresentationStyle.fullScreen + } + +} diff --git a/GeneralUtils/GeneralUtils/ui/PresentationDialog/BaseViewControllerShowTransculent.swift b/GeneralUtils/GeneralUtils/ui/PresentationDialog/BaseViewControllerShowTransculent.swift new file mode 100644 index 0000000..a862693 --- /dev/null +++ b/GeneralUtils/GeneralUtils/ui/PresentationDialog/BaseViewControllerShowTransculent.swift @@ -0,0 +1,109 @@ + +import UIKit + +/** +class VcEdit: BaseViewControllerShowTransculent { + @IBOutlet weak var root: UIView! + + static func openController(_ viewController: UIViewController) { + BaseViewControllerShowTransculent.showTransculent(viewController, storyboardName: "Main", viewControllerIdentifier: "VcEdit", + isDismisWhenTapOutSide: true) + } + + override func getHeightContent() -> CGFloat { + return self.view.bounds.height + } + + override func isFullWidth() -> Bool { + return true + } +} + + + - Neu muon custom width: + override func isCustomWidth() -> Bool { + return true + } + override func getWidthContent() -> CGFloat { + return UIScreen.mainScreen().bounds.width*3/4 + } + */ +open class BaseViewControllerShowTransculent: UIViewController { + public var isDismisWhenTapOutSide = true + public var viewControllerShow: UIViewController? + + // Call this function to show + public static func showTransculent(_ viewController: UIViewController, storyboardName: String, viewControllerIdentifier: String, + isDismisWhenTapOutSide: Bool = true, initBeforeLoad: ((BaseViewControllerShowTransculent)->())? = nil) { + let storyboard: UIStoryboard = UIStoryboard(name: storyboardName, bundle: nil) + let vc = storyboard.instantiateViewController(withIdentifier: viewControllerIdentifier) as! BaseViewControllerShowTransculent + vc.isDismisWhenTapOutSide = isDismisWhenTapOutSide + vc.transitioningDelegate = vc + initBeforeLoad?(vc) + viewController.present(vc, animated: true, completion: nil) + vc.viewControllerShow = viewController + } + + public init() { + super.init(nibName: nil, bundle: nil) + modalPresentationStyle = UIModalPresentationStyle.custom + } + + public required init?(coder aDecoder: NSCoder) { + super.init(coder: aDecoder) + modalPresentationStyle = UIModalPresentationStyle.custom + } + + open func getHeightContent() -> CGFloat { + // Need require override + return CGFloat(0) + } + + open func getWidthContent() -> CGFloat { + // Need require override + return CGFloat(0) + } + + open func isCustomWidth() -> Bool { + return false + } + + open func isFullWidth() -> Bool { + return false + } + + open func align() -> Align { + return .center + } +} + +public enum Align { + case left + case right + case top + case bottom + case center +} + +// Nếu cần có thể override các phương thức trong này để xác định Size, cách anim xuất hiện và biến mất của transculent View +extension BaseViewControllerShowTransculent: UIViewControllerTransitioningDelegate { + public func presentationController(forPresented presented: UIViewController, presenting: UIViewController?, source: UIViewController) -> UIPresentationController? { + let presentationController = BaseUIPresentationController(presentedViewController: presented, presenting: presenting) + presentationController.isDismisWhenTapOutSide = isDismisWhenTapOutSide + + return presentationController + } + + public func animationController(forPresented presented: UIViewController, presenting: UIViewController, source: UIViewController) -> UIViewControllerAnimatedTransitioning? { + let animationController = AnimatedTransitioning() + animationController.isPresentation = true + return animationController + } + + public func animationController(forDismissed dismissed: UIViewController) -> UIViewControllerAnimatedTransitioning? { + let animationController = AnimatedTransitioning() + animationController.isPresentation = false + return animationController + } +} + diff --git a/GeneralUtils/GeneralUtils/ui/VCContainer.swift b/GeneralUtils/GeneralUtils/ui/VCContainer.swift new file mode 100644 index 0000000..48d154b --- /dev/null +++ b/GeneralUtils/GeneralUtils/ui/VCContainer.swift @@ -0,0 +1,32 @@ +import Foundation +import UIKit + +public class VCContainer: UIViewController, IContainerController { + @IBOutlet weak public var vTopBar: ViewTopBar! + @IBOutlet weak public var vContent: UIView! + + public var currentViewController: UIViewController? + fileprivate var titleStr: String! + + public static func openController(viewController: UIViewController, vcChild: UIViewController, title: String) { + let storyboard: UIStoryboard = UIStoryboard(name: "Main", bundle: nil) + let vcOpen = storyboard.instantiateViewController(withIdentifier: "VCContainer") as! VCContainer + vcOpen.titleStr = title + vcOpen.currentViewController = vcChild + viewController.present(vcOpen, animated: true, completion: nil) + } + + public override func viewDidLoad() { + super.viewDidLoad() + vTopBar.title = titleStr + if let vcChild = currentViewController { + self.currentViewController = nil + changeCurrentController(vcChild) + } + + } + + public func getContainerview() -> UIView { + return vContent + } +} diff --git a/GeneralUtils/GeneralUtils/ui/page/BasePageViewController.swift b/GeneralUtils/GeneralUtils/ui/page/BasePageViewController.swift new file mode 100644 index 0000000..cb23029 --- /dev/null +++ b/GeneralUtils/GeneralUtils/ui/page/BasePageViewController.swift @@ -0,0 +1,123 @@ +import UIKit + +/** + 1. Tạo một đối tượng UIPageViewController Trong storyboard + 2. Mỗi page child sẽ có dạng như sau: + class VCImgItems : UIViewController, BasePageContentViewController{ + var pageIndex: Int = 0 + } + 3. override các phương thức sau: + + override func viewDidLoad() { + super.viewDidLoad() + setSelectionPage(0) + } + + override func getViewControllerAtIndex(_ index: Int) -> UIViewController { + let vc = VCImgItems.getInstance() + vc.pageIndex = index + return vc + } + + override func getCount() -> Int { + return imgObjs.count + } + + + 4. + - Set transition style trong storyboard + - Call setSelectionPage(0) De init +*/ + +open class BasePageViewController: UIPageViewController, UIPageViewControllerDelegate, UIPageViewControllerDataSource { + public var pageChangeCallBack: PageViewControllerChangeCallBack? + public var currentSelect: Int = -1; + + override open func viewDidLoad() { + super.viewDidLoad() + self.dataSource = self; + // Set datasource cho page + self.delegate = self + } + + open func pageViewController(_ pageViewController: UIPageViewController, didFinishAnimating finished: Bool, previousViewControllers: [UIViewController], transitionCompleted completed: Bool) { + let pageIndex = (pageViewController.viewControllers!.first as! BasePageContentViewController).pageIndex + if pageIndex != currentSelect { + currentSelect = pageIndex + pageChangeCallback(currentSelect) + } + } + + open func pageChangeCallback(_ currentSelect: Int) { + if self.pageChangeCallBack != nil { + self.pageChangeCallBack?.pageChangeCallback(currentSelect) + } + } + + open func getCurrentPageContent() -> BasePageContentViewController? { + return (self.viewControllers!.first as? BasePageContentViewController) + } + + // Use this method to return to previous view. ==> Nếu là first view ==> return nill + open func pageViewController(_ pageViewController: UIPageViewController, + viewControllerBefore viewController: UIViewController) -> UIViewController? { + let pageContent: BasePageContentViewController = viewController as! BasePageContentViewController + var index = pageContent.pageIndex + if ((index == 0) || (index == NSNotFound)) { + return nil + } else { + index = index - 1; + return getViewControllerAtIndex(index) + } + } + + // Use this method to return to after view. ==> Nếu là lastest view ==> return nill + open func pageViewController(_ pageViewController: UIPageViewController, + viewControllerAfter viewController: UIViewController) -> UIViewController? { + let pageContent: BasePageContentViewController = viewController as! BasePageContentViewController + var index = pageContent.pageIndex + if (index == NSNotFound) { + return nil; + } + index += 1 + if (index == getCount()) { + return nil; + } + return getViewControllerAtIndex(index) + } + + open func setSelectionPage(_ index: Int) { + if index < 0 || index > getCount() || index == currentSelect { + return + } + var direction: UIPageViewControllerNavigationDirection = .forward + if currentSelect > index { + direction = .reverse + } + + currentSelect = index; + + let nextViewController = getViewControllerAtIndex(index) + setViewControllers([nextViewController], direction: direction, animated: true, completion: nil) + pageChangeCallback(currentSelect) + } + + open func getViewControllerAtIndex(_ index: Int) -> UIViewController { + // Need override + return UIViewController() + } + + open func getCount() -> Int { + // Need override + return 0; + } +} + +public protocol PageViewControllerChangeCallBack { + func pageChangeCallback(_ currentSelect: Int) +} + + +public protocol BasePageContentViewController { + var pageIndex: Int { get set } +} diff --git a/GeneralUtils/GeneralUtils/ui/views/CollectionView/UICollectionViewLoadData.swift b/GeneralUtils/GeneralUtils/ui/views/CollectionView/UICollectionViewLoadData.swift new file mode 100644 index 0000000..bbc747f --- /dev/null +++ b/GeneralUtils/GeneralUtils/ui/views/CollectionView/UICollectionViewLoadData.swift @@ -0,0 +1,220 @@ +import UIKit +import Foundation + +/** + - Cell sẽ được định nghia trong storyboard. cần kết thừa BaseCollectionViewCell + override func configCellWithData(baseObj: Any, index: Int) { + super.configCellWithData(baseObj: baseObj, index: index) + } + + - Call this for load data initAndLoadData + - Nếu muốn pass data ở controller ==> implement UIViewControllerLoadDataColectionView + + ======= Need override ======= + 1. + override func loadDataInBg() -> [Any] { + var result = [Any]() + + return result + } + + 2. + // List obj lưu trữ Type của cell tương ứng với identitify của cell định nghĩa trong storyboard + - Neu co 1 Cell thi khong goi. Va dat ten dung la Cell + + override func getAllCell() -> [BaseCell] { + var baseCells: [BaseCell] = [BaseCell](); + baseCells.append(BaseCell(type: 0, identifier: "Cell")) + return baseCells + } + + + 3. Neu chi co 1 type thi khong override + + override func getTypeOfData(baseobj: Any) -> Int { + if baseobj is VideoObj { + return 1 + } + return 0 + } + + func getHeightForItem(indexPath: IndexPath, width: Int) -> Int{ + return width + } + */ +public class UICollectionViewLoadData: UICollectionViewLoading , UICollectionViewDelegateFlowLayout{ + public var viewController: UIViewController! + public var itemsData: [Any] = [Any]() + public var collectionUtils: BaseCollectionViewUtils! + public var numberOfItemsPerRow: Int! + + public var collectionViewDidSelectItemAt: ((_ collectionView: UICollectionViewLoadData, _ indexPath: IndexPath) -> ())? + + // Call when need load and show data + public func initAndLoadData(_ viewController: UIViewController?, numberOfItemsPerRow: Int = 1) { + self.viewController = viewController + self.numberOfItemsPerRow = numberOfItemsPerRow + self.delegate = self + collectionUtils = BaseCollectionViewUtils.init(self) + loadDataAndUpdateToUI() + } + + private func loadDataAndUpdateToUI(){ + showLoadingView() + CommonUtils.executebackgroundThread({ + self.itemsData = self.loadDataInBg() + }, completion: { + self.reloadCollection() + }) + } + + public func reloadCollection() { + self.layoutIfNeeded() + reloadData() + if itemsData.count == 0 { + showEmpty() + } else { + removeAllLoaddingEmpty() + } + } + + public func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) { + collectionViewDidSelectItemAt?(self, indexPath) + } + + public func collectionView(_ collectionView: UICollectionView, didHighlightItemAt indexPath: IndexPath) { + collectionView.cellForItem(at: indexPath)?.alpha = 0.65 + } + public func collectionView(_ collectionView: UICollectionView, didUnhighlightItemAt indexPath: IndexPath) { + collectionView.cellForItem(at: indexPath)?.alpha = 1 + } + + public func loadDataInBg() -> [Any] { + if let controllerLoadData = viewController as? UIViewControllerLoadDataColectionView { + return controllerLoadData.loadDataInBg() + } + return [Any]() + } + + public func getItem(_ indexPath: IndexPath) -> Any { + return itemsData[indexPath.row] + } + + public func reloadItem(baseObj: U){ + var index = 0 + for item in itemsData { + if let u = item as? U , u == baseObj{ + self.reloadItems(at: [IndexPath.init(row: index, section: 0)]) + return + } + index += 1 + } + } + + public func getAllCell() -> [BaseCell] { + if let controllerLoadData = viewController as? UIViewControllerLoadDataColectionView { + return controllerLoadData.getAllCell() + } + var baseCells: [BaseCell] = [BaseCell](); + baseCells.append(BaseCell(type: 0, identifier: "Cell")) + return baseCells + } + public func getTypeOfData(baseobj: Any) -> Int { + if let controllerLoadData = viewController as? UIViewControllerLoadDataColectionView { + return controllerLoadData.getTypeOfData(baseobj: baseobj) + } + return 0 + } + + public func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAt indexPath: IndexPath) -> CGSize { + let flowLayout = collectionViewLayout as! UICollectionViewFlowLayout + let totalSpace = flowLayout.sectionInset.left + + flowLayout.sectionInset.right + + (flowLayout.minimumInteritemSpacing * CGFloat(numberOfItemsPerRow - 1)) + let width = Int((collectionView.bounds.width - totalSpace) / CGFloat(numberOfItemsPerRow)) + return CGSize(width: width, height: getHeightForItem(indexPath: indexPath, width: width)) + } + + public func getHeightForItem(indexPath: IndexPath, width: Int) -> Int{ + if let controllerLoadData = viewController as? UIViewControllerLoadDataColectionView { + return controllerLoadData.getHeightForItem(indexPath: indexPath, width: width) + } + return width + } +} + +/* + func loadDataInBg() -> [Any] { + var result = [Any]() + return result + } + + func getAllCell() -> [BaseCell] { + var baseCells: [BaseCell] = [BaseCell](); + baseCells.append(BaseCell(type: 0, identifier: "Cell")) + return baseCells + } + +func getTypeOfData(baseobj: Any) -> Int { + if baseobj is VideoObj { + return 1 + } + return 0 + } + + func getHeightForItem(indexPath: IndexPath, width: Int) -> Int{ + return width + } + */ + +public protocol UIViewControllerLoadDataColectionView { + func loadDataInBg() -> [Any] + func getAllCell() -> [BaseCell] + func getTypeOfData(baseobj: Any) -> Int + func getHeightForItem(indexPath: IndexPath, width: Int) -> Int +} + +public class BaseCollectionViewUtils : NSObject, UICollectionViewDataSource { + public var baseCells: [BaseCell]? + public var collectionViewLoadData: UICollectionViewLoadData! + + public required init(_ collectionView: UICollectionViewLoadData) { + super.init() + self.collectionViewLoadData = collectionView + collectionView.dataSource = self + } + + private func getBaseCell(_ type: Int) -> BaseCell? { + if baseCells == nil { + baseCells = collectionViewLoadData.getAllCell() + } + + for baseCell in baseCells! { + if (baseCell.type == type) { + return baseCell; + } + } + return nil + } + + public func numberOfSections(in collectionView: UICollectionView) -> Int { + return 1 + } + + public func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int { + return collectionViewLoadData.itemsData.count + } + + public func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell { + let row = indexPath.row + let item = collectionViewLoadData.itemsData[row] + let type: Int = collectionViewLoadData.getTypeOfData(baseobj: item) + let baseCell = getBaseCell(type) + + let cell = collectionView.dequeueReusableCell(withReuseIdentifier: baseCell!.identifier!, for: indexPath) as! BaseCollectionViewCell + cell.configCellWithData(baseObj: item, index: row) + cell.viewController = collectionViewLoadData.viewController + cell.collectionView = collectionViewLoadData + return cell + } +} diff --git a/GeneralUtils/GeneralUtils/ui/views/CollectionView/UICollectionViewLoading.swift b/GeneralUtils/GeneralUtils/ui/views/CollectionView/UICollectionViewLoading.swift new file mode 100644 index 0000000..a5ec328 --- /dev/null +++ b/GeneralUtils/GeneralUtils/ui/views/CollectionView/UICollectionViewLoading.swift @@ -0,0 +1,73 @@ + +import UIKit + +public class UICollectionViewLoading: UICollectionView { + + fileprivate var loadingView: UIActivityIndicatorView? + public var lableEmpty: UILabel? + + public required init(coder aDecoder: NSCoder) { + super.init(coder: aDecoder)! + showLoadingView() + } + + public override func layoutSubviews() { + super.layoutSubviews() + updatePosition() + } + + fileprivate func updatePosition(){ + if let loadingView = loadingView { + let width = loadingView.bounds.width, height = loadingView.bounds.height + loadingView.frame = CGRect(x: (self.bounds.width - width) / 2, y: 100, width: width, height: height); + } + } + + public func removeAllLoaddingEmpty() { + loadingView?.removeFromSuperview() + lableEmpty?.removeFromSuperview() + loadingView = nil + lableEmpty = nil + } + + public func showLoadingView() { + removeEmpty() + if loadingView != nil { + loadingView?.isHidden = false + loadingView?.startAnimating() + } else { + loadingView = UIActivityIndicatorView(activityIndicatorStyle: UIActivityIndicatorViewStyle.whiteLarge) + loadingView!.startAnimating() + loadingView!.color = UIColor(red: 22.0 / 255.0, green: 106.0 / 255.0, blue: 176.0 / 255.0, alpha: 1.0) + loadingView!.hidesWhenStopped = true + addSubview(loadingView!) + } + + } + + public func showError() { + showEmpty("Có lỗi sảy ra, vui lòng thử lại") + } + + public func showEmpty(_ emptyText: String? = nil) { + loadingView?.removeFromSuperview() + loadingView = nil + + lableEmpty?.removeFromSuperview() + lableEmpty = UILabel() + if let empty = emptyText { + lableEmpty!.text = empty + } else { + lableEmpty!.text = "Danh sách trống" + } + lableEmpty!.numberOfLines = 0 + lableEmpty!.textAlignment = .center + lableEmpty!.frame = CGRect(x: 5, y: self.bounds.height / 2 - 100, width: self.bounds.width - 10, height: 200); + addSubview(lableEmpty!) + } + + fileprivate func removeEmpty(){ + lableEmpty?.removeFromSuperview() + lableEmpty = nil + } +} diff --git a/GeneralUtils/GeneralUtils/ui/views/DropDown/ComboBox.swift b/GeneralUtils/GeneralUtils/ui/views/DropDown/ComboBox.swift new file mode 100644 index 0000000..a264a2f --- /dev/null +++ b/GeneralUtils/GeneralUtils/ui/views/DropDown/ComboBox.swift @@ -0,0 +1,109 @@ +import Foundation +import UIKit + +/** + Thay đổi giá trị này để show các item + dataSource = [String]() + */ + +@IBDesignable public class ComboBox: UIViewCustom { + public var tvTitle: UILabel! + public var imvDropDown: UIImageView! + + public var dropDown: DropDown? + public var delegateSelect: SelectionClosure? + //(Index, String) -> Void + + public var dataSource = [String]() + public var selectedIndex = -1 + public var selectItem: String? + + public func setSelect(_ selectItem: String, selectedIndex: Int) { + if selectedIndex == self.selectedIndex { + return + } + self.selectedIndex = selectedIndex + self.selectItem = selectItem + tvTitle.text = selectItem + self.tvTitle.textColor = self.textColor + + self.delegateSelect?(selectedIndex, selectItem) + } + + public func setSelectIndex(_ selectedIndex: Int) { + let selectItem = dataSource[selectedIndex] + setSelect(selectItem, selectedIndex: selectedIndex) + } + + public override init(frame: CGRect) { + super.init(frame: frame) + xibSetup() + } + + public required init?(coder aDecoder: NSCoder) { + super.init(coder: aDecoder) + xibSetup() + } + + func xibSetup() { + tvTitle = UILabel() + imvDropDown = UIImageView() + tvTitle.translatesAutoresizingMaskIntoConstraints = false + tvTitle.font = UIFont.systemFont(ofSize: 14) + imvDropDown.translatesAutoresizingMaskIntoConstraints = false + self.addSubview(tvTitle) + self.addSubview(imvDropDown) + NSLayoutConstraint.activate([ + tvTitle.leftAnchor.constraint(equalTo: self.leftAnchor, constant: 8), + tvTitle.topAnchor.constraint(equalTo: self.topAnchor, constant: 4), + tvTitle.bottomAnchor.constraint(equalTo: self.bottomAnchor, constant: -4), + tvTitle.centerYAnchor.constraint(equalTo: self.centerYAnchor), + + imvDropDown.rightAnchor.constraint(equalTo: self.rightAnchor, constant: -2), + imvDropDown.centerYAnchor.constraint(equalTo: self.centerYAnchor), + imvDropDown.heightAnchor.constraint(equalToConstant: 30), + imvDropDown.widthAnchor.constraint(equalToConstant: 30), + imvDropDown.leftAnchor.constraint(equalTo: tvTitle.rightAnchor, constant: 2), + ]) + + + setOnClickListener { + if self.dataSource.count == 0 { + return + } + if self.dropDown == nil { + self.dropDown = DropDown() + } + self.dropDown!.dataSource = self.dataSource + self.dropDown!.selectionAction = { [unowned self](index, item) in + self.setSelect(item, selectedIndex: index) + } + self.dropDown!.anchorView = self.tvTitle + self.dropDown!.bottomOffset = CGPoint(x: 0, y: self.tvTitle.bounds.height) + self.dropDown!.show() + } + } + + @IBInspectable public var image: UIImage? = nil { + didSet { + imvDropDown.image = image + } + } + + @IBInspectable public var textColor: UIColor = UIColor.black { + didSet { + tvTitle.textColor = textColor + } + } + + @IBInspectable public var textColorPlaceHoder: UIColor = UIColor.lightGray + + @IBInspectable public var placeHolder: String? = nil { + didSet { + if tvTitle.text == nil || tvTitle.text!.isEmpty { + tvTitle.text = placeHolder + tvTitle.textColor = textColorPlaceHoder + } + } + } +} diff --git a/GeneralUtils/GeneralUtils/ui/views/DropDown/DPDConstants.swift b/GeneralUtils/GeneralUtils/ui/views/DropDown/DPDConstants.swift new file mode 100644 index 0000000..fe68d9d --- /dev/null +++ b/GeneralUtils/GeneralUtils/ui/views/DropDown/DPDConstants.swift @@ -0,0 +1,54 @@ +// +// Constants.swift +// DropDown +// +// Created by Kevin Hirsch on 28/07/15. +// Copyright (c) 2015 Kevin Hirsch. All rights reserved. +// + +import UIKit + +internal struct DPDConstant { + + internal struct KeyPath { + + static let Frame = "frame" + + } + + internal struct ReusableIdentifier { + + static let DropDownCell = "DropDownCell" + + } + + internal struct UI { + + static let BackgroundColor = UIColor(white: 0.94, alpha: 1) + static let SelectionBackgroundColor = UIColor(white: 0.89, alpha: 1) + static let SeparatorColor = UIColor.clear + static let CornerRadius: CGFloat = 2 + static let RowHeight: CGFloat = 44 + static let HeightPadding: CGFloat = 20 + + struct Shadow { + + static let Color = UIColor.darkGray.cgColor + static let Offset = CGSize.zero + static let Opacity: Float = 0.4 + static let Radius: CGFloat = 8 + + } + + } + + internal struct Animation { + + static let Duration = 0.15 + static let EntranceOptions: UIViewAnimationOptions = [.allowUserInteraction, .curveEaseOut] + static let ExitOptions: UIViewAnimationOptions = [.allowUserInteraction, .curveEaseIn] + static let DownScaleTransform = CGAffineTransform(scaleX: 0.9, y: 0.9) + + } + +} diff --git a/GeneralUtils/GeneralUtils/ui/views/DropDown/DPDKeyboardListener.swift b/GeneralUtils/GeneralUtils/ui/views/DropDown/DPDKeyboardListener.swift new file mode 100644 index 0000000..275b07c --- /dev/null +++ b/GeneralUtils/GeneralUtils/ui/views/DropDown/DPDKeyboardListener.swift @@ -0,0 +1,68 @@ +// +// KeyboardListener.swift +// DropDown +// +// Created by Kevin Hirsch on 30/07/15. +// Copyright (c) 2015 Kevin Hirsch. All rights reserved. +// + +import UIKit + +internal final class KeyboardListener { + + static let sharedInstance = KeyboardListener() + + fileprivate(set) var isVisible = false + fileprivate(set) var keyboardFrame = CGRect.zero + fileprivate var isListening = false + + deinit { + stopListeningToKeyboard() + } + +} + +//MARK: - Notifications + +extension KeyboardListener { + + func startListeningToKeyboard() { + if isListening { + return + } + + isListening = true + + NotificationCenter.default.addObserver( + self, + selector: #selector(keyboardWillShow(_:)), + name: NSNotification.Name.UIKeyboardWillShow, + object: nil) + NotificationCenter.default.addObserver( + self, + selector: #selector(keyboardWillHide(_:)), + name: NSNotification.Name.UIKeyboardWillHide, + object: nil) + } + + func stopListeningToKeyboard() { + NotificationCenter.default.removeObserver(self) + } + + @objc + fileprivate func keyboardWillShow(_ notification: Notification) { + isVisible = true + keyboardFrame = keyboardFrameFromNotification(notification) + } + + @objc + fileprivate func keyboardWillHide(_ notification: Notification) { + isVisible = false + keyboardFrame = keyboardFrameFromNotification(notification) + } + + fileprivate func keyboardFrameFromNotification(_ notification: Notification) -> CGRect { + return (notification.userInfo?[UIKeyboardFrameEndUserInfoKey] as? NSValue)?.cgRectValue ?? CGRect.zero + } + +} diff --git a/GeneralUtils/GeneralUtils/ui/views/DropDown/DPDUIView+Extension.swift b/GeneralUtils/GeneralUtils/ui/views/DropDown/DPDUIView+Extension.swift new file mode 100644 index 0000000..8c588e4 --- /dev/null +++ b/GeneralUtils/GeneralUtils/ui/views/DropDown/DPDUIView+Extension.swift @@ -0,0 +1,57 @@ +// +// UIView+Constraints.swift +// DropDown +// +// Created by Kevin Hirsch on 28/07/15. +// Copyright (c) 2015 Kevin Hirsch. All rights reserved. +// + +import UIKit + +//MARK: - Constraints + +internal extension UIView { + + func addConstraints(format: String, options: NSLayoutFormatOptions = [], metrics: [String: AnyObject]? = nil, views: [String: UIView]) { + addConstraints(NSLayoutConstraint.constraints(withVisualFormat: format, options: options, metrics: metrics, views: views)) + } + + func addUniversalConstraints(format: String, options: NSLayoutFormatOptions = [], metrics: [String: AnyObject]? = nil, views: [String: UIView]) { + addConstraints(format: "H:\(format)", options: options, metrics: metrics, views: views) + addConstraints(format: "V:\(format)", options: options, metrics: metrics, views: views) + } + +} + + + +//MARK: - Bounds + +internal extension UIView { + + var windowFrame: CGRect? { + return superview?.convert(frame, to: nil) + } + +} + +internal extension UIWindow { + + static func visibleWindow() -> UIWindow? { + var currentWindow = UIApplication.shared.keyWindow + + if currentWindow == nil { + let frontToBackWindows = Array(UIApplication.shared.windows.reversed()) + + for window in frontToBackWindows { + if window.windowLevel == UIWindowLevelNormal { + currentWindow = window + break + } + } + } + + return currentWindow + } + +} diff --git a/GeneralUtils/GeneralUtils/ui/views/DropDown/DropDown.swift b/GeneralUtils/GeneralUtils/ui/views/DropDown/DropDown.swift new file mode 100644 index 0000000..309addf --- /dev/null +++ b/GeneralUtils/GeneralUtils/ui/views/DropDown/DropDown.swift @@ -0,0 +1,794 @@ +/** + DialogUtils.showPopupMenu + */ + +import UIKit +// Consider refactoring the code to use the non-optional operators. +fileprivate func < (lhs: T?, rhs: T?) -> Bool { + switch (lhs, rhs) { + case let (l?, r?): + return l < r + case (nil, _?): + return true + default: + return false + } +} + +// Consider refactoring the code to use the non-optional operators. +fileprivate func <= (lhs: T?, rhs: T?) -> Bool { + switch (lhs, rhs) { + case let (l?, r?): + return l <= r + default: + return !(rhs < lhs) + } +} + + +public typealias Index = Int +public typealias Closure = () -> Void +public typealias SelectionClosure = (Index, String) -> Void +public typealias ConfigurationClosure = (Index, String) -> String +private typealias ComputeLayoutTuple = (x: CGFloat, y: CGFloat, width: CGFloat, offscreenHeight: CGFloat) + +/// A Material Design drop down in replacement for `UIPickerView`. +public final class DropDown: UIView { + + /// The dismiss mode for a drop down. + public enum DismissMode { + + /// A tap outside the drop down is required to dismiss. + case onTap + + /// No tap is required to dismiss, it will dimiss when interacting with anything else. + case automatic + + /// Not dismissable by the user. + case manual + + } + + /// The direction where the drop down will show from the `anchorView`. + public enum Direction { + + /// The drop down will show below the anchor view when possible, otherwise above if there is more place than below. + case any + + /// The drop down will show above the anchor view or will not be showed if not enough space. + case top + + /// The drop down will show below or will not be showed if not enough space. + case bottom + + } + + // MARK: - Properties + + /// The current visible drop down. There can be only one visible drop down at a time. + public static weak var VisibleDropDown: DropDown? + + // MARK: UI + fileprivate let dismissableView = UIView() + fileprivate let tableViewContainer = UIView() + fileprivate let tableView = UITableView() + + /// The view to which the drop down will displayed onto. + public weak var anchorView: UIView? { + didSet { setNeedsUpdateConstraints() } + } + + /** + The possible directions where the drop down will be showed. + + See `Direction` enum for more info. + */ + public var direction = Direction.any + + /** + The offset point relative to `anchorView` when the drop down is shown above the anchor view. + + By default, the drop down is showed onto the `anchorView` with the top + left corner for its origin, so an offset equal to (0, 0). + You can change here the default drop down origin. + */ + public var topOffset: CGPoint = CGPoint.zero { + didSet { setNeedsUpdateConstraints() } + } + + /** + The offset point relative to `anchorView` when the drop down is shown below the anchor view. + + By default, the drop down is showed onto the `anchorView` with the top + left corner for its origin, so an offset equal to (0, 0). + You can change here the default drop down origin. + */ + public var bottomOffset: CGPoint = CGPoint.zero { + didSet { setNeedsUpdateConstraints() } + } + + /** + The width of the drop down. + + Defaults to `anchorView.bounds.width - offset.x`. + */ + public var width: CGFloat? { + didSet { setNeedsUpdateConstraints() } + } + + // MARK: Constraints + fileprivate var heightConstraint: NSLayoutConstraint! + fileprivate var widthConstraint: NSLayoutConstraint! + fileprivate var xConstraint: NSLayoutConstraint! + fileprivate var yConstraint: NSLayoutConstraint! + + // MARK: Appearance + public override var backgroundColor: UIColor? { + get { return tableView.backgroundColor } + set { tableView.backgroundColor = newValue } + } + + /** + The background color of the selected cell in the drop down. + + Changing the background color automatically reloads the drop down. + */ + public dynamic var selectionBackgroundColor = DPDConstant.UI.SelectionBackgroundColor { + didSet { reloadAllComponents() } + } + + /** + The color of the text for each cells of the drop down. + + Changing the text color automatically reloads the drop down. + */ + public dynamic var textColor = UIColor.black { + didSet { reloadAllComponents() } + } + + /** + The font of the text for each cells of the drop down. + + Changing the text font automatically reloads the drop down. + */ + public dynamic var textFont = UIFont.systemFont(ofSize: 15) { + didSet { reloadAllComponents() } + } + + // MARK: Content + + /** + The data source for the drop down. + + Changing the data source automatically reloads the drop down. + */ + public var dataSource = [String]() { + didSet { reloadAllComponents() } + } + + /** + The localization keys for the data source for the drop down. + + Changing this value automatically reloads the drop down. + This has uses for setting accibility identifiers on the drop down cells (same ones as the localization keys). + */ + public var localizationKeysDataSource = [String]() { + didSet { + dataSource = localizationKeysDataSource + } + } + + /// The index of the row after its seleciton. + fileprivate var selectedRowIndex: Index? + + /** + The format for the cells' text. + + By default, the cell's text takes the plain `dataSource` value. + Changing `cellConfiguration` automatically reloads the drop down. + */ + public var cellConfiguration: ConfigurationClosure? { + didSet { reloadAllComponents() } + } + + /// The action to execute when the user selects a cell. + public var selectionAction: SelectionClosure? + + /// The action to execute when the drop down will show. + public var willShowAction: Closure? + + /// The action to execute when the user cancels/hides the drop down. + public var cancelAction: Closure? + + /// The dismiss mode of the drop down. Default is `OnTap`. + public var dismissMode = DismissMode.onTap { + willSet { + if newValue == .onTap { + let gestureRecognizer = UITapGestureRecognizer(target: self, action: #selector(dismissableViewTapped)) + dismissableView.addGestureRecognizer(gestureRecognizer) + } else if let gestureRecognizer = dismissableView.gestureRecognizers?.first { + dismissableView.removeGestureRecognizer(gestureRecognizer) + } + } + } + + fileprivate var minHeight: CGFloat { + return tableView.rowHeight + } + + fileprivate var didSetupConstraints = false + + // MARK: - Init's + + deinit { + stopListeningToNotifications() + } + + /** + Creates a new instance of a drop down. + Don't forget to setup the `dataSource`, + the `anchorView` and the `selectionAction` + at least before calling `show()`. + */ + public convenience init() { + self.init(frame: CGRect.zero) + } + + /** + Creates a new instance of a drop down. + + - parameter anchorView: The view to which the drop down will displayed onto. + - parameter selectionAction: The action to execute when the user selects a cell. + - parameter dataSource: The data source for the drop down. + - parameter topOffset: The offset point relative to `anchorView` used when drop down is displayed on above the anchor view. + - parameter bottomOffset: The offset point relative to `anchorView` used when drop down is displayed on below the anchor view. + - parameter cellConfiguration: The format for the cells' text. + - parameter cancelAction: The action to execute when the user cancels/hides the drop down. + + - returns: A new instance of a drop down customized with the above parameters. + */ + public convenience init(anchorView: UIView, selectionAction: SelectionClosure? = nil, dataSource: [String] = [], topOffset: CGPoint? = nil, bottomOffset: CGPoint? = nil, cellConfiguration: ConfigurationClosure? = nil, cancelAction: Closure? = nil) { + self.init(frame: CGRect.zero) + + self.anchorView = anchorView + self.selectionAction = selectionAction + self.dataSource = dataSource + self.topOffset = topOffset ?? CGPoint.zero + self.bottomOffset = bottomOffset ?? CGPoint.zero + self.cellConfiguration = cellConfiguration + self.cancelAction = cancelAction + } + + override public init(frame: CGRect) { + super.init(frame: frame) + setup() + } + + public required init?(coder aDecoder: NSCoder) { + super.init(coder: aDecoder) + setup() + } + +} + +//MARK: - Setup + +private extension DropDown { + + func setup() { + updateConstraintsIfNeeded() + setupUI() + + dismissMode = .onTap + + tableView.delegate = self + tableView.dataSource = self + + tableView.register(DropDownCell.self, forCellReuseIdentifier: DPDConstant.ReusableIdentifier.DropDownCell) + startListeningToKeyboard() + + accessibilityIdentifier = "drop_down" + } + + func setupUI() { + super.backgroundColor = UIColor.clear + + tableViewContainer.layer.masksToBounds = false + tableViewContainer.layer.cornerRadius = DPDConstant.UI.CornerRadius + tableViewContainer.layer.shadowColor = DPDConstant.UI.Shadow.Color + tableViewContainer.layer.shadowOffset = DPDConstant.UI.Shadow.Offset + tableViewContainer.layer.shadowOpacity = DPDConstant.UI.Shadow.Opacity + tableViewContainer.layer.shadowRadius = DPDConstant.UI.Shadow.Radius + + backgroundColor = DPDConstant.UI.BackgroundColor + tableView.rowHeight = DPDConstant.UI.RowHeight + tableView.separatorColor = DPDConstant.UI.SeparatorColor + tableView.layer.cornerRadius = DPDConstant.UI.CornerRadius + tableView.layer.masksToBounds = true + + setHiddentState() + isHidden = true + } + +} + +//MARK: - UI + +extension DropDown { + + public override func updateConstraints() { + if !didSetupConstraints { + setupConstraints() + } + + didSetupConstraints = true + + let layout = computeLayout() + + if !layout.canBeDisplayed { + super.updateConstraints() + hide() + + return + } + + xConstraint.constant = layout.x + yConstraint.constant = layout.y + widthConstraint.constant = layout.width + heightConstraint.constant = layout.visibleHeight + + tableView.isScrollEnabled = layout.offscreenHeight > 0 + + DispatchQueue.main.async { [unowned self] in + self.tableView.flashScrollIndicators() + } + + super.updateConstraints() + } + + fileprivate func setupConstraints() { + translatesAutoresizingMaskIntoConstraints = false + + // Dismissable view + addSubview(dismissableView) + dismissableView.translatesAutoresizingMaskIntoConstraints = false + + addUniversalConstraints(format: "|[dismissableView]|", views: ["dismissableView": dismissableView]) + + // Table view container + addSubview(tableViewContainer) + tableViewContainer.translatesAutoresizingMaskIntoConstraints = false + + xConstraint = NSLayoutConstraint( + item: tableViewContainer, + attribute: .leading, + relatedBy: .equal, + toItem: self, + attribute: .leading, + multiplier: 1, + constant: 0) + addConstraint(xConstraint) + + yConstraint = NSLayoutConstraint( + item: tableViewContainer, + attribute: .top, + relatedBy: .equal, + toItem: self, + attribute: .top, + multiplier: 1, + constant: 0) + addConstraint(yConstraint) + + widthConstraint = NSLayoutConstraint( + item: tableViewContainer, + attribute: .width, + relatedBy: .equal, + toItem: nil, + attribute: .notAnAttribute, + multiplier: 1, + constant: 0) + tableViewContainer.addConstraint(widthConstraint) + + heightConstraint = NSLayoutConstraint( + item: tableViewContainer, + attribute: .height, + relatedBy: .equal, + toItem: nil, + attribute: .notAnAttribute, + multiplier: 1, + constant: 0) + tableViewContainer.addConstraint(heightConstraint) + + // Table view + tableViewContainer.addSubview(tableView) + tableView.translatesAutoresizingMaskIntoConstraints = false + + tableViewContainer.addUniversalConstraints(format: "|[tableView]|", views: ["tableView": tableView]) + } + + public override func layoutSubviews() { + super.layoutSubviews() + + // When orientation changes, layoutSubviews is called + // We update the constraint to update the position + setNeedsUpdateConstraints() + + let shadowPath = UIBezierPath(rect: tableViewContainer.bounds) + tableViewContainer.layer.shadowPath = shadowPath.cgPath + } + + fileprivate func computeLayout() -> (x: CGFloat, y: CGFloat, width: CGFloat, offscreenHeight: CGFloat, visibleHeight: CGFloat, canBeDisplayed: Bool, Direction: Direction) { + var layout: ComputeLayoutTuple = (0, 0, 0, 0) + var direction = self.direction + + if let window = UIWindow.visibleWindow() { + switch direction { + case .any: + layout = computeLayoutBottomDisplay(window: window) + direction = .bottom + + if layout.offscreenHeight > 0 { + let topLayout = computeLayoutForTopDisplay(window: window) + + if topLayout.offscreenHeight < layout.offscreenHeight { + layout = topLayout + direction = .top + } + } + case .bottom: + layout = computeLayoutBottomDisplay(window: window) + direction = .bottom + case .top: + layout = computeLayoutForTopDisplay(window: window) + direction = .top + } + } + + let visibleHeight = tableHeight - layout.offscreenHeight + let canBeDisplayed = visibleHeight >= minHeight + + return (layout.x, layout.y, layout.width, layout.offscreenHeight, visibleHeight, canBeDisplayed, direction) + } + + fileprivate func computeLayoutBottomDisplay(window: UIWindow) -> ComputeLayoutTuple { + var offscreenHeight: CGFloat = 0 + + let anchorViewX = (anchorView?.windowFrame?.minX ?? 0) + let anchorViewY = (anchorView?.windowFrame?.minY ?? 0) + + var x = anchorViewX + bottomOffset.x + let y = anchorViewY + bottomOffset.y + + let maxY = y + tableHeight + let windowMaxY = window.bounds.maxY - DPDConstant.UI.HeightPadding + + let keyboardListener = KeyboardListener.sharedInstance + let keyboardMinY = keyboardListener.keyboardFrame.minY - DPDConstant.UI.HeightPadding + + if keyboardListener.isVisible && maxY > keyboardMinY { + offscreenHeight = abs(maxY - keyboardMinY) + } else if maxY > windowMaxY { + offscreenHeight = abs(maxY - windowMaxY) + } + + var width = self.width ?? (anchorView?.bounds.width ?? 0) - bottomOffset.x + if width < 160 { + width = 160 + } + let lackX = anchorViewX + width - window.bounds.maxX + if lackX > 0 { + x = x - lackX - 10 + } + if x < 6 { x = 6 } + return (x, y, width, offscreenHeight) + } + + fileprivate func computeLayoutForTopDisplay(window: UIWindow) -> ComputeLayoutTuple { + var offscreenHeight: CGFloat = 0 + + let anchorViewX = (anchorView?.windowFrame?.minX ?? 0) + let anchorViewMaxY = (anchorView?.windowFrame?.minY ?? 0) + + var x = anchorViewX + topOffset.x + var y = (anchorViewMaxY + topOffset.y) - tableHeight + + let windowY = window.bounds.minY + DPDConstant.UI.HeightPadding + + if y < windowY { + offscreenHeight = abs(y - windowY) + y = windowY + } + + var width = self.width ?? (anchorView?.bounds.width ?? 0) - topOffset.x + if width < 160 { + width = 160 + } + let lackX = anchorViewX + width - window.bounds.maxX + if lackX > 0 { + x = x - lackX - 10 + } + if x < 6 { x = 6 } + return (x, y, width, offscreenHeight) + } + +} + +//MARK: - Actions + +extension DropDown { + + /** + An Objective-C alias for the show() method which converts the returned tuple into an NSDictionary. + + - returns: An NSDictionary with a value for the "canBeDisplayed" Bool, and possibly for the "offScreenHeight" Optional(CGFloat). + */ + @objc(show) + public func objc_show() -> NSDictionary { + let (canBeDisplayed, offScreenHeight) = show() + + var info = [AnyHashable: Any]() + info["canBeDisplayed"] = canBeDisplayed + if let offScreenHeight = offScreenHeight { + info["offScreenHeight"] = offScreenHeight + } + + return NSDictionary(dictionary: info) + } + + /** + Shows the drop down if enough height. + + - returns: Wether it succeed and how much height is needed to display all cells at once. + */ + @discardableResult public func show() -> (canBeDisplayed: Bool, offscreenHeight: CGFloat?) { + if self == DropDown.VisibleDropDown { + return (true, 0) + } + + if let visibleDropDown = DropDown.VisibleDropDown { + visibleDropDown.cancel() + } + + willShowAction?() + + DropDown.VisibleDropDown = self + + setNeedsUpdateConstraints() + + let visibleWindow = UIWindow.visibleWindow() + visibleWindow?.addSubview(self) + visibleWindow?.bringSubview(toFront: self) + + self.translatesAutoresizingMaskIntoConstraints = false + visibleWindow?.addUniversalConstraints(format: "|[dropDown]|", views: ["dropDown": self]) + + let layout = computeLayout() + + if !layout.canBeDisplayed { + hide() + return (layout.canBeDisplayed, layout.offscreenHeight) + } + + isHidden = false + tableViewContainer.transform = DPDConstant.Animation.DownScaleTransform + + UIView.animate( + withDuration: DPDConstant.Animation.Duration, + delay: 0, + options: DPDConstant.Animation.EntranceOptions, + animations: { [unowned self] in + self.setShowedState() + }, + completion: nil) + + selectRowAtIndex(selectedRowIndex) + + return (layout.canBeDisplayed, layout.offscreenHeight) + } + + /// Hides the drop down. + public func hide() { + if self == DropDown.VisibleDropDown { + /* + If one drop down is showed and another one is not + but we call `hide()` on the hidden one: + we don't want it to set the `VisibleDropDown` to nil. + */ + DropDown.VisibleDropDown = nil + } + + if isHidden { + return + } + + UIView.animate( + withDuration: DPDConstant.Animation.Duration, + delay: 0, + options: DPDConstant.Animation.ExitOptions, + animations: { [unowned self] in + self.setHiddentState() + }, + completion: { [unowned self] finished in + self.isHidden = true + self.removeFromSuperview() + }) + } + + fileprivate func cancel() { + hide() + cancelAction?() + } + + fileprivate func setHiddentState() { + alpha = 0 + } + + fileprivate func setShowedState() { + alpha = 1 + tableViewContainer.transform = CGAffineTransform.identity + } + +} + +//MARK: - UITableView + +extension DropDown { + + /** + Reloads all the cells. + + It should not be necessary in most cases because each change to + `dataSource`, `textColor`, `textFont`, `selectionBackgroundColor` + and `cellConfiguration` implicitly calls `reloadAllComponents()`. + */ + public func reloadAllComponents() { + tableView.reloadData() + setNeedsUpdateConstraints() + } + + /// (Pre)selects a row at a certain index. + public func selectRowAtIndex(_ index: Index?) { + if index <= dataSource.count { + selectedRowIndex = nil + return + } + if let index = index { + tableView.selectRow( + at: IndexPath(row: index, section: 0), + animated: false, + scrollPosition: .middle) + } else { + deselectRowAtIndexPath(selectedRowIndex) + } + + selectedRowIndex = index + } + + public func deselectRowAtIndexPath(_ index: Index?) { + selectedRowIndex = nil + + guard let index = index, index > 0 + else { return } + + tableView.deselectRow(at: IndexPath(row: index, section: 0), animated: true) + } + + /// Returns the index of the selected row. + public var indexForSelectedRow: Index? { + return tableView.indexPathForSelectedRow?.row + } + + /// Returns the selected item. + public var selectedItem: String? { + guard let row = tableView.indexPathForSelectedRow?.row else { return nil } + + return dataSource[row] + } + + /// Returns the height needed to display all cells. + fileprivate var tableHeight: CGFloat { + return tableView.rowHeight * CGFloat(dataSource.count) + } + +} + +//MARK: - UITableViewDataSource - UITableViewDelegate + +extension DropDown: UITableViewDataSource, UITableViewDelegate { + + public func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { + return dataSource.count + } + + public func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { + let cell = tableView.dequeueReusableCell(withIdentifier: DPDConstant.ReusableIdentifier.DropDownCell, for: indexPath) as! DropDownCell + let index = indexPath.row + + if index >= 0 && index < localizationKeysDataSource.count { + cell.accessibilityIdentifier = localizationKeysDataSource[index] + } + + cell.optionLabel.textColor = textColor + cell.optionLabel.font = textFont + cell.selectedBackgroundColor = selectionBackgroundColor + + if let cellConfiguration = cellConfiguration { + cell.optionLabel.text = cellConfiguration(index, dataSource[index]) + } else { + cell.optionLabel.text = dataSource[index] + } + + return cell + } + + public func tableView(_ tableView: UITableView, willDisplay cell: UITableViewCell, forRowAt indexPath: IndexPath) { + cell.isSelected = indexPath.row == selectedRowIndex + } + + public func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) { + selectedRowIndex = indexPath.row + selectionAction?(selectedRowIndex!, dataSource[selectedRowIndex!]) + hide() + } + +} + +//MARK: - Auto dismiss + +extension DropDown { + + public override func hitTest(_ point: CGPoint, with event: UIEvent?) -> UIView? { + let view = super.hitTest(point, with: event) + + if dismissMode == .automatic && view === dismissableView { + cancel() + return nil + } else { + return view + } + } + + @objc + fileprivate func dismissableViewTapped() { + cancel() + } + +} + +//MARK: - Keyboard events + +extension DropDown { + + /** + Starts listening to keyboard events. + Allows the drop down to display correctly when keyboard is showed. + */ + public static func startListeningToKeyboard() { + KeyboardListener.sharedInstance.startListeningToKeyboard() + } + + fileprivate func startListeningToKeyboard() { + KeyboardListener.sharedInstance.startListeningToKeyboard() + + NotificationCenter.default.addObserver( + self, + selector: #selector(keyboardUpdate), + name: NSNotification.Name.UIKeyboardWillShow, + object: nil) + NotificationCenter.default.addObserver( + self, + selector: #selector(keyboardUpdate), + name: NSNotification.Name.UIKeyboardWillHide, + object: nil) + } + + fileprivate func stopListeningToNotifications() { + NotificationCenter.default.removeObserver(self) + } + + @objc + fileprivate func keyboardUpdate() { + self.setNeedsUpdateConstraints() + } + +} diff --git a/GeneralUtils/GeneralUtils/ui/views/DropDown/DropDownCell.swift b/GeneralUtils/GeneralUtils/ui/views/DropDown/DropDownCell.swift new file mode 100644 index 0000000..673304e --- /dev/null +++ b/GeneralUtils/GeneralUtils/ui/views/DropDown/DropDownCell.swift @@ -0,0 +1,70 @@ +// +// DropDownCellTableViewCell.swift +// DropDown +// +// Created by Kevin Hirsch on 28/07/15. +// Copyright (c) 2015 Kevin Hirsch. All rights reserved. +// + +import UIKit + +public class DropDownCell: UITableViewCell { + + public var optionLabel: UILabel! + public var selectedBackgroundColor: UIColor? + + public override init(style: UITableViewCellStyle, reuseIdentifier: String?) { + super.init(style: style, reuseIdentifier: reuseIdentifier) + + optionLabel = UILabel() + optionLabel.translatesAutoresizingMaskIntoConstraints = false + self.contentView.addSubview(optionLabel) + NSLayoutConstraint.activate([optionLabel.leftAnchor.constraint(equalTo: contentView.leftAnchor, constant: 8), + optionLabel.rightAnchor.constraint(equalTo: contentView.rightAnchor, constant: -8), + optionLabel.topAnchor.constraint(equalTo: contentView.topAnchor, constant: 8), + optionLabel.bottomAnchor.constraint(equalTo: contentView.bottomAnchor, constant: -8)]) + backgroundColor = UIColor.clear + } + + public required init?(coder aDecoder: NSCoder) { + fatalError("init(coder:) has not been implemented") + } + + + public override var isSelected: Bool { + willSet { + setSelected(newValue, animated: false) + } + } + + public override var isHighlighted: Bool { + willSet { + setSelected(newValue, animated: false) + } + } + + public override func setHighlighted(_ highlighted: Bool, animated: Bool) { + setSelected(highlighted, animated: animated) + } + + public override func setSelected(_ selected: Bool, animated: Bool) { + let executeSelection: () -> Void = { [unowned self] in + if let selectedBackgroundColor = self.selectedBackgroundColor { + if selected { + self.backgroundColor = selectedBackgroundColor + } else { + self.backgroundColor = UIColor.clear + } + } + } + + if animated { + UIView.animate(withDuration: 0.3, animations: { + executeSelection() + }) + } else { + executeSelection() + } + } + +} diff --git a/GeneralUtils/GeneralUtils/ui/views/FloatRatingView.swift b/GeneralUtils/GeneralUtils/ui/views/FloatRatingView.swift new file mode 100644 index 0000000..1dd8b80 --- /dev/null +++ b/GeneralUtils/GeneralUtils/ui/views/FloatRatingView.swift @@ -0,0 +1,310 @@ +import UIKit + +@objc public protocol FloatRatingViewDelegate { + /** + Returns the rating value when touch events end + */ + func floatRatingView(_ ratingView: FloatRatingView, didUpdate rating: Float) + + /** + Returns the rating value as the user pans + */ + @objc optional func floatRatingView(_ ratingView: FloatRatingView, isUpdating rating: Float) +} + +/** + A simple rating view that can set whole, half or floating point ratings. + */ +@IBDesignable +open class FloatRatingView: UIView { + + // MARK: Float Rating View properties + + open weak var delegate: FloatRatingViewDelegate? + + /** + Array of empty image views + */ + fileprivate var emptyImageViews: [UIImageView] = [] + + /** + Array of full image views + */ + fileprivate var fullImageViews: [UIImageView] = [] + + /** + Sets the empty image (e.g. a star outline) + */ + @IBInspectable open var emptyImage: UIImage? { + didSet { + // Update empty image views + for imageView in self.emptyImageViews { + imageView.image = emptyImage + } + self.refresh() + } + } + + /** + Sets the full image that is overlayed on top of the empty image. + Should be same size and shape as the empty image. + */ + @IBInspectable open var fullImage: UIImage? { + didSet { + // Update full image views + for imageView in self.fullImageViews { + imageView.image = fullImage + } + self.refresh() + } + } + + /** + Sets the empty and full image view content mode. + */ + var imageContentMode: UIViewContentMode = UIViewContentMode.scaleAspectFit + + /** + Minimum rating. + */ + @IBInspectable open var minRating: Int = 0 { + didSet { + // Update current rating if needed + if self.rating < Float(minRating) { + self.rating = Float(minRating) + self.refresh() + } + } + } + + /** + Max rating value. + */ + @IBInspectable open var maxRating: Int = 5 { + didSet { + let needsRefresh = maxRating != oldValue + + if needsRefresh { + self.removeImageViews() + self.initImageViews() + + // Relayout and refresh + self.setNeedsLayout() + self.refresh() + } + } + } + + /** + Minimum image size. + */ + @IBInspectable open var minImageSize: CGSize = CGSize(width: 5.0, height: 5.0) + + /** + Set the current rating. + */ + @IBInspectable open var rating: Float = 0 { + didSet { + if rating != oldValue { + self.refresh() + } + } + } + + /** + Sets whether or not the rating view can be changed by panning. + */ + @IBInspectable open var editable: Bool = true + + /** + Ratings change by 0.5. Takes priority over floatRatings property. + */ + @IBInspectable open var halfRatings: Bool = false + + /** + Ratings change by floating point values. + */ + @IBInspectable open var floatRatings: Bool = false + + + // MARK: Initializations + + required override public init(frame: CGRect) { + super.init(frame: frame) + + self.initImageViews() + } + + required public init?(coder aDecoder: NSCoder) { + super.init(coder: aDecoder) + + self.initImageViews() + } + + // MARK: Refresh hides or shows full images + + func refresh() { + for i in 0..=Float(i+1) { + imageView.layer.mask = nil + imageView.isHidden = false + } + else if self.rating>Float(i) && self.rating CGSize { + let imageRatio = image.size.width / image.size.height + let viewRatio = size.width / size.height + + if imageRatio < viewRatio { + let scale = size.height / image.size.height + let width = scale * image.size.width + + return CGSize(width: width, height: size.height) + } + else { + let scale = size.width / image.size.width + let height = scale * image.size.height + + return CGSize(width: size.width, height: height) + } + } + + // Override to calculate ImageView frames + override open func layoutSubviews() { + super.layoutSubviews() + + if let emptyImage = self.emptyImage { + let desiredImageWidth = self.frame.size.width / CGFloat(self.emptyImageViews.count) + let maxImageWidth = max(self.minImageSize.width, desiredImageWidth) + let maxImageHeight = max(self.minImageSize.height, self.frame.size.height) + let imageViewSize = self.sizeForImage(emptyImage, inSize: CGSize(width: maxImageWidth, height: maxImageHeight)) + let imageXOffset = (self.frame.size.width - (imageViewSize.width * CGFloat(self.emptyImageViews.count))) / + CGFloat((self.emptyImageViews.count - 1)) + + for i in 0.. imageView.frame.origin.x { + // Find touch point in image view + let newLocation = imageView.convert(touchLocation, from:self) + + // Find decimal value for float or half rating + if imageView.point(inside: newLocation, with: nil) && (self.floatRatings || self.halfRatings) { + let decimalNum = Float(newLocation.x / imageView.frame.size.width) + newRating = Float(i) + decimalNum + if self.halfRatings { + newRating = Float(i) + (decimalNum > 0.75 ? 1:(decimalNum > 0.25 ? 0.5:0)) + } + } + // Whole rating + else { + newRating = Float(i) + 1.0 + } + break + } + } + + // Check min rating + self.rating = newRating < Float(self.minRating) ? Float(self.minRating):newRating + + // Update delegate + if let delegate = self.delegate { + delegate.floatRatingView?(self, isUpdating: self.rating) + } + } + + override open func touchesBegan(_ touches: Set, with event: UIEvent?) { + if let touch = touches.first { + let touchLocation = touch.location(in: self) + self.handleTouchAtLocation(touchLocation) + } + } + + override open func touchesMoved(_ touches: Set, with event: UIEvent?) { + if let touch = touches.first { + let touchLocation = touch.location(in: self) + self.handleTouchAtLocation(touchLocation) + } + } + + override open func touchesEnded(_ touches: Set, with event: UIEvent?) { + // Update delegate + if let delegate = self.delegate { + delegate.floatRatingView(self, didUpdate: self.rating) + } + } + +} diff --git a/GeneralUtils/GeneralUtils/ui/views/ISRadioButton.swift b/GeneralUtils/GeneralUtils/ui/views/ISRadioButton.swift new file mode 100644 index 0000000..7cbf693 --- /dev/null +++ b/GeneralUtils/GeneralUtils/ui/views/ISRadioButton.swift @@ -0,0 +1,369 @@ +import UIKit + +@IBDesignable +open class ISRadioButton: UIButton { + + var indexPath: IndexPath! + + // Container for holding other buttons in same group. + + @IBOutlet var otherButtons: Array? + + // Size of icon, default is 15.0. + + @IBInspectable open var iconSize: CGFloat = 15.0 + + // Size of selection indicator, default is iconSize * 0.5. + + @IBInspectable open var indicatorSize: CGFloat = 15.0 * 0.5 + + // Color of icon, default is black + + @IBInspectable open var iconColor: UIColor = UIColor.black + + // Stroke width of icon, default is iconSize / 9. + + @IBInspectable open var iconStrokeWidth: CGFloat = 1.6 + + // Color of selection indicator, default is black + + @IBInspectable open var indicatorColor: UIColor = UIColor.black + + // Margin width between icon and title, default is 10. 0. + + @IBInspectable open var marginWidth: CGFloat = 10.0 + + // Whether icon on the right side, default is NO. + + @IBInspectable open var iconOnRight: Bool = false + + // Whether use square icon, default is NO. + + @IBInspectable open var iconSquare: Bool = false + + // Image for radio button icon (optional). + + @IBInspectable open var icon: UIImage! + + // Image for radio button icon when selected (optional). + + @IBInspectable open var iconSelected: UIImage! + + // Whether enable multiple selection, default is NO. + + @IBInspectable open var multipleSelectionEnabled: Bool = false + + var isChaining: Bool = false + + fileprivate var setOtherButtons: NSArray { + + get { + return otherButtons! as NSArray + } + set (newValue) { + if !isChaining { + otherButtons = newValue as? Array + isChaining = true + for radioButton in otherButtons! { + let others: NSMutableArray = NSMutableArray(array: otherButtons!) + others.add(self) + others.remove(radioButton) + radioButton.setOtherButtons = others + } + isChaining = false + } + } + } + + @IBInspectable open var setIcon: UIImage { + + // Avoid to use getter it can be nill + + get { + return icon + } + + set (newValue) { + icon = newValue + self.setImage(icon, for: UIControlState()) + } + } + + @IBInspectable open var setIconSelected: UIImage { + + // Avoid to use getter it can be nill + + get { + return iconSelected + } + + set (newValue) { + iconSelected = newValue + self.setImage(iconSelected, for: .selected) + self.setImage(iconSelected, for: .highlighted) + } + } + + open var setMultipleSelectionEnabled: Bool { + + get { + return multipleSelectionEnabled + } + set (newValue) { + if !isChaining { + isChaining = true + multipleSelectionEnabled = newValue + + if self.otherButtons != nil { + for radioButton in self.otherButtons! { + radioButton.multipleSelectionEnabled = newValue + } + } + isChaining = false + } + } + } + + // MARK: -- Helpers + + func drawButton () { + if (icon == nil || self.icon.accessibilityIdentifier == "Generated Icon") { + self.setIcon = self.drawIconWithSelection(false) + } else { + self.setIcon = icon + } + if (iconSelected == nil || self.iconSelected.accessibilityIdentifier == "Generated Icon") { + self.setIconSelected = self.drawIconWithSelection(true) + } else { + self.setIconSelected = iconSelected + } + + if self.otherButtons != nil { + self.setOtherButtons = self.otherButtons! as NSArray + } + + if multipleSelectionEnabled { + self.setMultipleSelectionEnabled = multipleSelectionEnabled + } + + if self.iconOnRight { + self.imageEdgeInsets = UIEdgeInsetsMake(0, self.frame.size.width - self.icon.size.width + marginWidth, 0, 0); + self.titleEdgeInsets = UIEdgeInsetsMake(0, 0, 0, marginWidth + self.icon.size.width); + self.contentHorizontalAlignment = .right + } else { + self.titleEdgeInsets = UIEdgeInsetsMake(0, marginWidth, 0, 0); + self.titleLabel?.textAlignment = .left + self.contentHorizontalAlignment = .left + } + self.titleLabel?.adjustsFontSizeToFitWidth = false + } + + func drawIconWithSelection (_ selected: Bool) -> UIImage { + let rect: CGRect = CGRect(x: 0, y: 0, width: iconSize, height: iconSize) + + UIGraphicsBeginImageContextWithOptions(rect.size, false, 0.0); + let context = UIGraphicsGetCurrentContext() + // UIGraphicsPushContext(context!) + // draw icon + + var iconPath: UIBezierPath! + let iconRect: CGRect = CGRect(x: iconStrokeWidth / 2, y: iconStrokeWidth / 2, width: iconSize - iconStrokeWidth, height: iconSize - iconStrokeWidth); + if self.iconSquare { + iconPath = UIBezierPath(rect: iconRect) + } else { + iconPath = UIBezierPath(ovalIn: iconRect) + } + iconColor.setStroke() + iconPath.lineWidth = iconStrokeWidth; + iconPath.stroke() + context?.addPath(iconPath.cgPath); + + // draw indicator + if (selected) { + var indicatorPath: UIBezierPath! + let indicatorRect: CGRect = CGRect(x: (iconSize - indicatorSize) / 2, y: (iconSize - indicatorSize) / 2, width: indicatorSize, height: indicatorSize); + if self.iconSquare { + indicatorPath = UIBezierPath(rect: indicatorRect) + } else { + indicatorPath = UIBezierPath(ovalIn: indicatorRect) + } + indicatorColor.setStroke() + indicatorPath.lineWidth = iconStrokeWidth; + indicatorPath.stroke() + + indicatorColor.setFill() + indicatorPath.fill() + context?.addPath(indicatorPath.cgPath); + } + + let image: UIImage = UIGraphicsGetImageFromCurrentImageContext()!; + // UIGraphicsPopContext() + UIGraphicsEndImageContext(); + + image.accessibilityIdentifier = "Generated Icon"; + return image; + } + + func touchDown () { + self.isSelected = true + } + + func initRadioButton () { + super.addTarget(self, action: #selector(ISRadioButton.touchDown), for: .touchUpInside) + self.isSelected = false + } + + override open func prepareForInterfaceBuilder () { + self.initRadioButton() + self.drawButton() + } + + // MARK: -- ISRadiobutton + + // @return Selected button in same group. + + open func selectedButton() -> ISRadioButton! { + if !self.multipleSelectionEnabled { + if self.isSelected { + return self + } + } else { + for isRadioButton in self.otherButtons! { + if isRadioButton.isSelected { + return isRadioButton + } + } + } + return nil + } + + // @return Selected buttons in same group, use it only if multiple selection is enabled. + + open func selectedButtons() -> NSMutableArray { + + let selectedButtons: NSMutableArray = NSMutableArray () + if self.isSelected { + selectedButtons.add(self) + } + for isRadioButton in self.otherButtons! { + if isRadioButton.isSelected { + selectedButtons .add(self) + } + } + return selectedButtons; + } + + // Clears selection for other buttons in in same group. + + open func deselectOtherButtons() { + if self.otherButtons != nil { + for isRadioButton in self.otherButtons! { + isRadioButton.isSelected = false + } + } + } + + // @return unselected button in same group. + + open func unSelectedButtons() -> NSArray { + let unSelectedButtons: NSMutableArray = NSMutableArray () + if self.isSelected { + unSelectedButtons .add(self) + } + for isRadioButton in self.otherButtons! { + if isRadioButton.isSelected { + unSelectedButtons .add(self) + } + } + return unSelectedButtons ; + } + + // MARK: -- UIButton + + override open func titleColor(for state: UIControlState) -> UIColor { + if (state == UIControlState.selected || state == UIControlState.highlighted) { + var selectedOrHighlightedColor: UIColor! + if (state == UIControlState.selected) { + selectedOrHighlightedColor = super.titleColor(for: .selected) + } else { + selectedOrHighlightedColor = super.titleColor(for: .highlighted) + } + self.setTitleColor(selectedOrHighlightedColor, for: .selected) + self.setTitleColor(selectedOrHighlightedColor, for: .highlighted) + } + return super.titleColor(for: state)! + } + + // MARK: -- UIControl + + override open var isSelected: Bool { + didSet(oldValue) { + if (multipleSelectionEnabled) { + if oldValue == true && self.isSelected == true { + self.isSelected = false + } + } + else { + if isSelected { + self.deselectOtherButtons() + } + } + } + } + + // MARK: -- UIView + + required public init(coder aDecoder: NSCoder) { + super.init(coder: aDecoder)! + self.initRadioButton() + } + + override init(frame: CGRect) { + super.init(frame: frame) + self.initRadioButton() + } + + override open func draw(_ rect: CGRect) { + super.draw(rect) + self.drawButton() + } + + open func setTitleAndUpdateHeight(_ title: String?, hConstraint: NSLayoutConstraint) { + super.setTitle(title, for: UIControlState()) + if let title = title { + let font = UIFont.boldSystemFont(ofSize: 16) + let rect = NSString(string: title).boundingRect(with: CGSize(width: frame.width - 30, height: CGFloat(MAXFLOAT)), options: .usesLineFragmentOrigin, attributes: [NSFontAttributeName: font], context: nil) + var estimateHight = ceil(rect.height) + if estimateHight < 25 { + estimateHight = 25 + } + hConstraint.constant = estimateHight + } else { + hConstraint.constant = 25 + } + } + + open func setTitleAndUpdateHeight(titleAttText: NSAttributedString?, hConstraint: NSLayoutConstraint) { + super.setAttributedTitle(titleAttText, for: UIControlState()) + + if let title = titleAttText { + let font = UIFont.boldSystemFont(ofSize: 16) + let label:UILabel = UILabel(frame: CGRect.init(x: 0, y: 0, width: self.frame.width - 30, height: CGFloat(MAXFLOAT))) + label.numberOfLines = 0 + label.lineBreakMode = NSLineBreakMode.byWordWrapping + label.font = font + label.attributedText = title + label.sizeToFit() + var estimateHight = label.frame.height + +// let rect = title.boundingRect(with: CGSize(width: frame.width - 100, height: CGFloat(MAXFLOAT)), options: [.usesFontLeading, .usesLineFragmentOrigin], context: nil) +// var estimateHight = ceil(rect.height) + if estimateHight < 25 { + estimateHight = 25 + } + hConstraint.constant = estimateHight + } else { + hConstraint.constant = 25 + } + } +} diff --git a/GeneralUtils/GeneralUtils/ui/views/TableView/BaseCell.swift b/GeneralUtils/GeneralUtils/ui/views/TableView/BaseCell.swift new file mode 100644 index 0000000..0a441ad --- /dev/null +++ b/GeneralUtils/GeneralUtils/ui/views/TableView/BaseCell.swift @@ -0,0 +1,46 @@ +import UIKit +import Foundation + +public class BaseCell { + public var type: Int = 0 + public var identifier: String? + + public init(type: Int, identifier: String) { + self.type = type; + self.identifier = identifier; + } +} + + +/** + override public func configCellWithData(baseObj: Any, index: Int) { + super.configCellWithData(baseObj: baseObj, index: index) + } + */ +open class BaseTableViewCellUI: UITableViewCell { + public var viewController: UIViewController? + public var tableView: UITableView! + public var index: Int! + + // Need override + open func configCellWithData(baseObj: Any, index: Int) { + self.index = index + } +} + + +/** + override func configCellWithData(baseObj: Any, index: Int) { + super.configCellWithData(baseObj: baseObj, index: index) + } + */ +public class BaseCollectionViewCell: UICollectionViewCell { + public var viewController: UIViewController? + public var collectionView: UICollectionView! + public var index: Int! + + // Need override + public func configCellWithData(baseObj: Any, index: Int) { + self.index = index + } +} diff --git a/GeneralUtils/GeneralUtils/ui/views/TableView/BaseTbLoadData.swift b/GeneralUtils/GeneralUtils/ui/views/TableView/BaseTbLoadData.swift new file mode 100644 index 0000000..8447629 --- /dev/null +++ b/GeneralUtils/GeneralUtils/ui/views/TableView/BaseTbLoadData.swift @@ -0,0 +1,137 @@ +import UIKit +import Foundation + +public class BaseTbLoadData : UITableViewLoading, UITableViewDelegate, UITableViewDataSource{ + public var viewController: UIViewController! + public var itemsData: [Any] = [Any]() + public var delegateCallback: TableViewCallbackDelegate? + + public func loadDataAndUpdateToUI(){} // Need override + + public func initAndLoadData(_ vc: UIViewController) { + self.viewController = vc + if self.delegate == nil { + self.delegate = self + self.dataSource = self + } + + loadDataAndUpdateToUI() + } + + public func clearAndReload() { + itemsData.removeAll() + reloadData() + loadDataAndUpdateToUI() + } + + public func numberOfSections(in tableView: UITableView) -> Int { + return 1 + } + + public func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { + return itemsData.count + } + + public var baseCells: [BaseCell]? + private func getBaseCell(_ type: Int) -> BaseCell? { + if baseCells == nil { + baseCells = getAllCell() + } + + for baseCell in baseCells! { + if (baseCell.type == type) { + return baseCell; + } + } + return nil + } + + public func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { + let row = indexPath.row + let item = itemsData[row] + let type: Int = getTypeOfData(baseobj: item) + let baseCell = getBaseCell(type) + + let cell = tableView.dequeueReusableCell(withIdentifier: (baseCell?.identifier)!, for: indexPath) as! BaseTableViewCellUI + cell.viewController = viewController + cell.tableView = self + cell.configCellWithData(baseObj: item, index: row) + + return cell + } + + public func getTableView() -> UITableViewLoading { + return self + } + + public func getItem(_ indexPath: IndexPath) -> Any { + return itemsData[indexPath.row] + } + + public func reloadItem(baseObj: U){ + var index = 0 + for item in itemsData { + if let u = item as? U , u == baseObj{ + self.reloadRows(at: [IndexPath.init(row: index, section: 0)], with: UITableViewRowAnimation.none) + return + } + index += 1 + } + } + public func reloadRows(index: Int){ + self.reloadRows(at: [IndexPath.init(row: index, section: 0)], with: UITableViewRowAnimation.none) + } + + public func reloadDataTableView() { + getTableView().reloadData() + if itemsData.count > 0 { + getTableView().setNeedsLayout() + getTableView().layoutIfNeeded() + + getTableView().removeAllLoaddingEmpty() + } else{ + getTableView().showEmpty() + } + } + + public func getAllCell() -> [BaseCell] { + if let controllerLoadData = viewController as? IVCLoadDataTableView { + return controllerLoadData.getAllCell() + } + var baseCells: [BaseCell] = [BaseCell](); + baseCells.append(BaseCell(type: 0, identifier: "Cell")) + return baseCells + } + public func getTypeOfData(baseobj: Any) -> Int { + if let controllerLoadData = viewController as? IVCLoadDataTableView { + return controllerLoadData.getTypeOfData(baseobj: baseobj) + } + return 0 + } + // ========== + + public func getUIViewController() -> UIViewController { + return viewController + } + + public func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) { + if let vcLoadData = viewController as? IVCLoadDataTableView{ + vcLoadData.tableView(tableView, didSelectRowAt: indexPath) + } + } + + //MARK: Custom delegate + public var customDelegate: UITableViewDelegate? + public func scrollViewDidScroll(_ scrollView: UIScrollView) { + customDelegate?.scrollViewDidScroll?(scrollView) + } +} + +public protocol IVCLoadDataTableView { + func getAllCell() -> [BaseCell] + func getTypeOfData(baseobj: Any) -> Int + func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) +} +public protocol TableViewCallbackDelegate { + func callbackReloadDataComplete() +} diff --git a/GeneralUtils/GeneralUtils/ui/views/TableView/CellLoadMore.swift b/GeneralUtils/GeneralUtils/ui/views/TableView/CellLoadMore.swift new file mode 100644 index 0000000..3f0a843 --- /dev/null +++ b/GeneralUtils/GeneralUtils/ui/views/TableView/CellLoadMore.swift @@ -0,0 +1,46 @@ +import UIKit + +public class CellLoadMore: BaseTableViewCellUI { + public var tv = UILabel() + public var progress = UIActivityIndicatorView() + + public override init(style: UITableViewCellStyle, reuseIdentifier: String?) { + super.init(style: style, reuseIdentifier: reuseIdentifier) + setup() + } + public required init?(coder aDecoder: NSCoder) { + super.init(coder: aDecoder) + setup() + } + + private func setup() { + tv.textAlignment = NSTextAlignment.center + progress.hidesWhenStopped = false + progress.activityIndicatorViewStyle = .gray + tv.translatesAutoresizingMaskIntoConstraints = false + progress.translatesAutoresizingMaskIntoConstraints = false + + contentView.addSubview(tv) + contentView.addSubview(progress) + + progress.centerYAnchor.constraint(equalTo: contentView.centerYAnchor).isActive = true + progress.leftAnchor.constraint(equalTo: contentView.leftAnchor, constant: 8).isActive = true + NSLayoutConstraint.activate([ + tv.heightAnchor.constraint(equalToConstant: 30), + tv.leftAnchor.constraint(equalTo: progress.rightAnchor, constant: 8), + tv.rightAnchor.constraint(equalTo: contentView.rightAnchor, constant: -8), + tv.topAnchor.constraint(equalTo: contentView.topAnchor, constant: 8), + tv.bottomAnchor.constraint(equalTo: contentView.bottomAnchor, constant: -8) + ]) + layoutIfNeeded() + } + + public override func configCellWithData(baseObj: Any, index: Int) { + super.configCellWithData(baseObj: baseObj, index: index) + + let session: Session = baseObj as! Session + + tv.text = session.title ?? "Loading..." + progress.startAnimating() + } +} diff --git a/GeneralUtils/GeneralUtils/ui/views/TableView/UITableViewLoadDataBg.swift b/GeneralUtils/GeneralUtils/ui/views/TableView/UITableViewLoadDataBg.swift new file mode 100644 index 0000000..21aacb7 --- /dev/null +++ b/GeneralUtils/GeneralUtils/ui/views/TableView/UITableViewLoadDataBg.swift @@ -0,0 +1,95 @@ +import UIKit +/** + - Cell sẽ được định nghia trong storyboard. cần kết thừa BaseTableViewCellUI + override func configCellWithData(baseObj: Any, index: Int) { + super.configCellWithData(baseObj: baseObj, index: index) + } + + - Call this for load data initAndLoadData + - Nếu muốn pass data ở controller ==> implement IVCLoadDataTableViewBg + + ======= Need override ======= + 1. + self.tableView.separatorStyle = UITableViewCellSeparatorStyle.none + self.tableView.rowHeight = UITableViewAutomaticDimension + self.tableView.estimatedRowHeight = 400 + + override func loadDataInBg() -> [Any] { + var result = [Any]() + + return result + } + + 2. + // List obj lưu trữ Type của cell tương ứng với identitify của cell định nghĩa trong storyboard + - Neu co 1 Cell thi khong goi. Va dat ten dung la Cell + +override func getAllCell() -> [BaseCell] { + var baseCells: [BaseCell] = [BaseCell](); + baseCells.append(BaseCell(type: 0, identifier: "Cell")) + return baseCells +} + + +3. + + override func getTypeOfData(baseobj: Any) -> Int { + if baseobj is VideoObj { + return 1 + } + return 0 + } + + 5. Config cell voi extend doi tuong BaseTableViewCellUI + + */ + +public class UITableViewLoadDataBg: BaseTbLoadData{ + public override func loadDataAndUpdateToUI(){ + showLoadingView() + CommonUtils.executebackgroundThread({ + self.itemsData = self.loadDataInBg() + }, completion: { + self.reloadDataTableView() + self.delegateCallback?.callbackReloadDataComplete() + }) + } + + public func loadDataInBg() -> [Any] { + if let controllerLoadData = viewController as? IVCLoadDataTableViewBg { + return controllerLoadData.loadDataInBg() + } + return [Any]() + } +} + +/* + goi: tbView.initAndLoadData(self) + + IVCLoadDataTableViewBg +func loadDataInBg() -> [Any] { + var result = [Any]() + + return result +} + +func getAllCell() -> [BaseCell] { + var baseCells: [BaseCell] = [BaseCell](); + baseCells.append(BaseCell(type: 0, identifier: "Cell")) + return baseCells +} + +func getTypeOfData(baseobj: Any) -> Int { + if baseobj is VideoObj { + return 1 + } + return 0 +} + +func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath){} +*/ +public protocol IVCLoadDataTableViewBg: IVCLoadDataTableView { + func loadDataInBg() -> [Any] +} + + diff --git a/GeneralUtils/GeneralUtils/ui/views/TableView/UITableViewLoadDataFromUIThread.swift b/GeneralUtils/GeneralUtils/ui/views/TableView/UITableViewLoadDataFromUIThread.swift new file mode 100644 index 0000000..8eb182a --- /dev/null +++ b/GeneralUtils/GeneralUtils/ui/views/TableView/UITableViewLoadDataFromUIThread.swift @@ -0,0 +1,85 @@ + +import UIKit +/** + - Cell sẽ được định nghia trong storyboard. cần kết thừa BaseTableViewCellUI + override func configCellWithData(baseObj: Any, index: Int) { + super.configCellWithData(baseObj: baseObj, index: index) + } + + - Call this for load data initAndLoadData + - Nếu muốn pass data ở controller ==> implement UIViewControllerLoadDataTableView + + ======= Need override ======= + 1. + self.tableView.separatorStyle = UITableViewCellSeparatorStyle.none + self.tableView.rowHeight = UITableViewAutomaticDimension + self.tableView.estimatedRowHeight = 400 + + override func loadDataOnUI(complete: @escaping ([Any]?) -> ()) { + + } + + 2. + // List obj lưu trữ Type của cell tương ứng với identitify của cell định nghĩa trong storyboard + - Neu co 1 Cell thi khong goi. Va dat ten dung la Cell + + override func getAllCell() -> [BaseCell] { + var baseCells: [BaseCell] = [BaseCell](); + baseCells.append(BaseCell(type: 0, identifier: "Cell")) + return baseCells + } + +3. + override func getTypeOfData(baseobj: Any) -> Int { + if baseobj is VideoObj { + return 1 + } + return 0 + } + + 5. Config cell voi extend doi tuong BaseTableViewCellUI + + */ + +public class UITableViewLoadDataFromUIThread: BaseTbLoadData{ + public override func loadDataAndUpdateToUI(){ + showLoadingView() + loadDataOnUI(complete: { result in + if let result = result{ + self.itemsData.addAll(otherArray: result) + } + self.reloadDataTableView() + self.delegateCallback?.callbackReloadDataComplete() + }) + } + + public func loadDataOnUI(complete: @escaping(_ result: [Any]?) -> ()){ + if let vcLoadDataTableViewUIThread = viewController as? IVCLoadDataTableViewUIThread { + vcLoadDataTableViewUIThread.loadDataOnUI(complete: complete) + } + } +} + +/* +VC kế thừa: IVCLoadDataTableViewUIThread. +phải gọi: tableView.initAndLoadData(self) trong đâu đấy ở viewcontrollet + + func loadDataOnUI(complete: @escaping ([Any]?) -> ()) { + } + func getAllCell() -> [BaseCell] { + var baseCells: [BaseCell] = [BaseCell](); + baseCells.append(BaseCell(type: 0, identifier: "Cell")) + return baseCells + } + + func getTypeOfData(baseobj: Any) -> Int { + return 0 + } + func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) { + } + */ +public protocol IVCLoadDataTableViewUIThread: IVCLoadDataTableView { + func loadDataOnUI(complete: @escaping(_ result: [Any]?) -> ()) +} + + diff --git a/GeneralUtils/GeneralUtils/ui/views/TableView/UITableViewLoadMore.swift b/GeneralUtils/GeneralUtils/ui/views/TableView/UITableViewLoadMore.swift new file mode 100644 index 0000000..f1663c2 --- /dev/null +++ b/GeneralUtils/GeneralUtils/ui/views/TableView/UITableViewLoadMore.swift @@ -0,0 +1,114 @@ +import Foundation +import UIKit +/** + override func loadData(_ currentPage: Int, noItemInPage: Int, funSuccess: @escaping ([Any], _ currrentPage: Int, _ noItemInPage: Int) -> Void, funError: @escaping (Any?) -> ()) { + + } + */ +public class UITableViewLoadMore: BaseTbLoadData { + public var noItemInPage = 30 + public var currrentPage: Int = 0 // currrentPage data đã load được. Sẽ được tính từ page 1 + public var isLoadingMore = false + + public override func initAndLoadData(_ vc: UIViewController) { + register(CellLoadMore.self, forCellReuseIdentifier: "LoadingCell") + super.initAndLoadData(vc) + } + + public override func loadDataAndUpdateToUI(){ + showLoadingView() + loadMore() + } + + public func loadData(_ currentPage: Int, noItemInPage: Int, funSuccess: @escaping ([Any], _ currrentPage: Int, _ noItemInPage: Int) -> Void, funError: @escaping (Any?) -> ()) { + if let vCLoadDataTableViewLoadMore = viewController as? IVCLoadDataTableViewLoadMore { + vCLoadDataTableViewLoadMore.loadData(currentPage, noItemInPage: noItemInPage, funSuccess: funSuccess, funError: funError) + } + } + + public override func clearAndReload() { + currrentPage = 0 + super.clearAndReload() + } + + private func loadMore() { + if isLoadingMore { return } + isLoadingMore = true + currrentPage += 1 + loadData(currrentPage, noItemInPage: noItemInPage, funSuccess: loadDataSuccess, funError: loadDataError) + } + + public func loadDataSuccess(_ baseOjs: [Any], currrentPage: Int, noItemInPage: Int) { + isLoadingMore = false + self.currrentPage = currrentPage + removeLoadMoreItem() + itemsData.addAll(otherArray: baseOjs) + if baseOjs.count >= noItemInPage{ + addLoadMoreItem() + } + self.reloadData() + delegateCallback?.callbackReloadDataComplete() + if itemsData.count == 0 { + self.showEmpty() + }else{ + self.removeAllLoaddingEmpty() + } + } + public func loadDataError(_ anyObj: Any?) { + isLoadingMore = false + self.beginUpdates() + removeLoadMoreItem() + self.endUpdates() + delegateCallback?.callbackReloadDataComplete() + if itemsData.count == 0 { + self.showError() + } + } + + @discardableResult public func removeLoadMoreItem() -> Bool { + if itemsData.count == 0 { return false } + let endItem = itemsData[itemsData.count - 1] + if let session = endItem as? Session, session.type == .LoadMore { + itemsData.removeLast() + return true + } + return false + } + public func addLoadMoreItem(_ textLoadMore: String = "Loading more results ...") { + itemsData.append(Session(type: .LoadMore, title: textLoadMore)) + } + + public override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { + let cell = super.tableView(tableView, cellForRowAt: indexPath) + if cell is CellLoadMore { + self.loadMore() + } + return cell + } + + +} + +/** + func loadData(_ currentPage: Int, noItemInPage: Int, funSuccess: ([Any], _ currrentPage: Int, _ noItemInPage: Int) -> Void, funError: (Any?) -> ()) { + + } + + func getAllCell() -> [BaseCell] { + var baseCells: [BaseCell] = [BaseCell](); + baseCells.append(BaseCell(type: 0, identifier: "Cell")) + baseCells.append(BaseCell(type: 100, identifier: "LoadingCell")) + return baseCells + } + + func getTypeOfData(baseobj: Any) -> Int { + if let session = baseobj as? Session, session.type == .LoadMore { + return 100 + } + return 0 +} + */ +public protocol IVCLoadDataTableViewLoadMore: IVCLoadDataTableView { + func loadData(_ currentPage: Int, noItemInPage: Int, funSuccess: @escaping ([Any], _ currrentPage: Int, _ noItemInPage: Int) -> Void, funError: @escaping (Any?) -> ()) +} + diff --git a/GeneralUtils/GeneralUtils/ui/views/TableView/UITableViewLoading.swift b/GeneralUtils/GeneralUtils/ui/views/TableView/UITableViewLoading.swift new file mode 100644 index 0000000..b4db3a7 --- /dev/null +++ b/GeneralUtils/GeneralUtils/ui/views/TableView/UITableViewLoading.swift @@ -0,0 +1,98 @@ +import UIKit + +public class UITableViewLoading: UITableView { + + fileprivate var loadingView: UIActivityIndicatorView? + fileprivate var customView: UIView? + public var lableEmpty: UILabel? + public var emptyText: String? + + public override init(frame: CGRect, style: UITableViewStyle) { + super.init(frame: frame, style: style) + showLoadingView() + } + + public required init(coder aDecoder: NSCoder) { + super.init(coder: aDecoder)! + showLoadingView() + } + + public override func layoutSubviews() { + super.layoutSubviews() + updatePosition() + } + + fileprivate func updatePosition() { + if let loadingView = loadingView { + let width = loadingView.bounds.width, height = loadingView.bounds.height + loadingView.frame = CGRect(x: (self.bounds.width - width) / 2, y: 100, width: width, height: height); + } + if let customView = customView { + customView.frame = self.frame + } + lableEmpty?.frame = CGRect(x: 5, y: self.bounds.height / 2 - 100, width: self.bounds.width - 10, height: 200); + } + + public func addCustomView(customView: UIView) { + removeCustomView() + self.customView = customView + addSubview(customView) + } + + public func removeCustomView() { + customView?.removeFromSuperview() + customView = nil + } + + public override func reloadData() { + removeCustomView() + super.reloadData() + } + + public func removeAllLoaddingEmpty() { + loadingView?.removeFromSuperview() + lableEmpty?.removeFromSuperview() + loadingView = nil + lableEmpty = nil + } + + public func showLoadingView() { + removeEmpty() + if loadingView != nil { + loadingView?.isHidden = false + loadingView?.startAnimating() + } else { + loadingView = UIActivityIndicatorView(activityIndicatorStyle: UIActivityIndicatorViewStyle.whiteLarge) + loadingView!.startAnimating() + loadingView!.color = UIColor(red: 22.0 / 255.0, green: 106.0 / 255.0, blue: 176.0 / 255.0, alpha: 1.0) + loadingView!.hidesWhenStopped = true + addSubview(loadingView!) + } + } + + public func showError() { + showEmpty("Có lỗi sảy ra, vui lòng thử lại") + } + + public func showEmpty(_ emptyText: String? = nil) { + loadingView?.removeFromSuperview() + loadingView = nil + + lableEmpty?.removeFromSuperview() + lableEmpty = UILabel() + if let empty = emptyText { + lableEmpty!.text = empty + } else { + lableEmpty!.text = self.emptyText ?? "Danh sách trống" + } + lableEmpty!.numberOfLines = 0 + lableEmpty!.textAlignment = .center + lableEmpty!.frame = CGRect(x: 5, y: self.bounds.height / 2 - 100, width: self.bounds.width - 10, height: 200); + addSubview(lableEmpty!) + } + + fileprivate func removeEmpty() { + lableEmpty?.removeFromSuperview() + lableEmpty = nil + } +} diff --git a/GeneralUtils/GeneralUtils/ui/views/UIButtonCustom.swift b/GeneralUtils/GeneralUtils/ui/views/UIButtonCustom.swift new file mode 100644 index 0000000..848303b --- /dev/null +++ b/GeneralUtils/GeneralUtils/ui/views/UIButtonCustom.swift @@ -0,0 +1,129 @@ +import UIKit + +@IBDesignable +public class UIButtonCustom: UIButton { + @IBInspectable public var padding: CGFloat = 0 { + didSet { + self.contentEdgeInsets = UIEdgeInsetsMake(padding, padding, padding, padding) + } + } + + @IBInspectable public var paddingLeft: CGFloat = 0 { + didSet { + self.contentEdgeInsets.left = paddingLeft + } + } + + @IBInspectable public var paddingRight: CGFloat = 0 { + didSet { + self.contentEdgeInsets.right = paddingRight + } + } + + @IBInspectable public var paddingTop: CGFloat = 0 { + didSet { + self.contentEdgeInsets.top = paddingTop + } + } + + @IBInspectable public var paddingBottom: CGFloat = 0 { + didSet { + self.contentEdgeInsets.bottom = paddingBottom + } + } + + @IBInspectable public var cornerRadius: CGFloat = 0 { + didSet { + layer.cornerRadius = cornerRadius + layer.masksToBounds = cornerRadius > 0 + } + } + + @IBInspectable public var borderWidth: CGFloat = 0 { + didSet { + layer.borderWidth = borderWidth + } + } + + @IBInspectable public var borderColor: UIColor = UIColor.black { + didSet { + layer.borderColor = borderColor.cgColor + } + } + + @IBInspectable public var highlightedBackgroundColor: UIColor? = nil { + didSet { + reloadStyles() + } + } + + + public func setShadowOffset(_ width: CGFloat, height: CGFloat, opacity: Float) { + layer.shadowColor = UIColor.black.cgColor + layer.shadowOffset = CGSize(width: width, height: height) + layer.shadowOpacity = 0.3 + } + + fileprivate var saveBackgroundColor: UIColor? + fileprivate func reloadStyles() { + if isHighlighted { + if let highlightedBackgroundColor = highlightedBackgroundColor { + if saveBackgroundColor == nil { + saveBackgroundColor = backgroundColor + } + backgroundColor = highlightedBackgroundColor + } else { + self.alpha = 0.65 + } + } else { + if let saveBackgroundColor = saveBackgroundColor, highlightedBackgroundColor != nil { + backgroundColor = saveBackgroundColor + } else { + self.alpha = 1 + } + } + } + + override public var isHighlighted: Bool { + didSet { + reloadStyles() + } + } + + override public func awakeFromNib() { + if let imageView = self.imageView { + imageView.contentMode = UIViewContentMode.scaleAspectFit + } + } +} + + +@IBDesignable +class UIButtonCustomGradientBg: UIButtonCustom { + @IBInspectable var startColor: UIColor = UIColor.init(hexString: "#FBFBFB") + @IBInspectable var endColor: UIColor = UIColor.init(hexString: "#D0D0D0") + + @IBInspectable var startLocation: Double = 0.05 + @IBInspectable var endLocation: Double = 0.95 + + @IBInspectable var horizontalMode: Bool = false + @IBInspectable var diagonalMode: Bool = false + + override class var layerClass: AnyClass { return CAGradientLayer.self } + var gradientLayer: CAGradientLayer { return layer as! CAGradientLayer } + + override func layoutSubviews() { + super.layoutSubviews() + if horizontalMode { + gradientLayer.startPoint = diagonalMode ? CGPoint(x: 1, y: 0) : CGPoint(x: 0, y: 0.5) + gradientLayer.endPoint = diagonalMode ? CGPoint(x: 0, y: 1) : CGPoint(x: 1, y: 0.5) + } else { + gradientLayer.startPoint = diagonalMode ? CGPoint(x: 0, y: 0) : CGPoint(x: 0.5, y: 0) + gradientLayer.endPoint = diagonalMode ? CGPoint(x: 1, y: 1) : CGPoint(x: 0.5, y: 1) + } + gradientLayer.locations = [startLocation as NSNumber, endLocation as NSNumber] + gradientLayer.colors = [startColor.cgColor, endColor.cgColor] + } +} + + diff --git a/GeneralUtils/GeneralUtils/ui/views/UIImageViewCustom.swift b/GeneralUtils/GeneralUtils/ui/views/UIImageViewCustom.swift new file mode 100644 index 0000000..b893a22 --- /dev/null +++ b/GeneralUtils/GeneralUtils/ui/views/UIImageViewCustom.swift @@ -0,0 +1,25 @@ + +import UIKit + +@IBDesignable public class UIImageViewCustom: UIImageView { + + @IBInspectable var cornerRadius: CGFloat = 0 { + didSet { + layer.cornerRadius = cornerRadius + layer.masksToBounds = cornerRadius > 0 + } + } + + @IBInspectable var borderWidth: CGFloat = 0 { + didSet { + layer.borderWidth = borderWidth + } + } + + @IBInspectable var borderColor: UIColor = UIColor.black { + didSet { + layer.borderColor = borderColor.cgColor + } + } + +} diff --git a/GeneralUtils/GeneralUtils/ui/views/UILabelCustom.swift b/GeneralUtils/GeneralUtils/ui/views/UILabelCustom.swift new file mode 100644 index 0000000..bbbcd1d --- /dev/null +++ b/GeneralUtils/GeneralUtils/ui/views/UILabelCustom.swift @@ -0,0 +1,123 @@ +import Foundation +import UIKit + +public class UILabelCustom: UILabel { + public var tagObj: Any? + + @IBInspectable public var cornerRadius: CGFloat = 0 { + didSet { + layer.cornerRadius = cornerRadius + layer.masksToBounds = cornerRadius > 0 + } + } + + @IBInspectable public var borderWidth: CGFloat = 0 { + didSet { + layer.borderWidth = borderWidth + } + } + + @IBInspectable public var borderColor: UIColor = UIColor.black { + didSet { + layer.borderColor = borderColor.cgColor + } + } + + @IBInspectable public var topInset: CGFloat = 0.0 + @IBInspectable public var leftInset: CGFloat = 0.0 + @IBInspectable public var bottomInset: CGFloat = 0.0 + @IBInspectable public var rightInset: CGFloat = 0.0 + @IBInspectable public var isEnablePading: Bool = false + + public var insets: UIEdgeInsets { + get { + return UIEdgeInsetsMake(topInset, leftInset, bottomInset, rightInset) + } + set { + topInset = newValue.top + leftInset = newValue.left + bottomInset = newValue.bottom + rightInset = newValue.right + } + } + + public override func drawText(in rect: CGRect) { + if isEnablePading { + super.drawText(in: UIEdgeInsetsInsetRect(rect, insets)) + } else { + super.drawText(in: rect) + } + } + + public override func sizeThatFits(_ size: CGSize) -> CGSize { + if isEnablePading { + var adjSize = super.sizeThatFits(size) + adjSize.width += leftInset + rightInset + adjSize.height += topInset + bottomInset + return adjSize + } else { + return super.sizeThatFits(size) + } + } + + public override var intrinsicContentSize: CGSize { + if isEnablePading { + var contentSize = super.intrinsicContentSize + contentSize.width += leftInset + rightInset + contentSize.height += topInset + bottomInset + return contentSize + } else { + return super.intrinsicContentSize + } + } +} + +/** +Vì sử dụng cái pading bên trên bị lỗi nhỏ, khi nó gần được 2 line nhưng lại bị .... +*/ + +@IBDesignable +public class UILabelWithPading: UIViewCustom { + public var tv: UILabel! + + @IBInspectable public var topInset: CGFloat = 8 { + didSet { tv.topAnchor.constraint(equalTo: self.topAnchor, constant: topInset).isActive = true } + } + @IBInspectable public var leftInset: CGFloat = 8 { + didSet { tv.leftAnchor.constraint(equalTo: self.leftAnchor, constant: leftInset).isActive = true } + } + @IBInspectable public var bottomInset: CGFloat = 8 { + didSet { tv.bottomAnchor.constraint(equalTo: self.bottomAnchor, constant: -bottomInset).isActive = true } + } + @IBInspectable public var rightInset: CGFloat = 8 { + didSet { tv.rightAnchor.constraint(equalTo: self.rightAnchor, constant: -rightInset).isActive = true } + } + + public override init(frame: CGRect) { + super.init(frame: frame) + xibSetup() + } + + public required init?(coder aDecoder: NSCoder) { + super.init(coder: aDecoder) + xibSetup() + } + + public func setPading(topInset: CGFloat, leftInset: CGFloat, bottomInset: CGFloat, rightInset: CGFloat) { + self.topInset = topInset + self.leftInset = leftInset + self.bottomInset = bottomInset + self.rightInset = rightInset + } + + fileprivate func xibSetup() { + tv = UILabel() + tv.translatesAutoresizingMaskIntoConstraints = false + self.addSubview(tv) + NSLayoutConstraint.activate([tv.topAnchor.constraint(equalTo: self.topAnchor, constant: topInset), + tv.leftAnchor.constraint(equalTo: self.leftAnchor, constant: leftInset), + tv.rightAnchor.constraint(equalTo: self.rightAnchor, constant: -rightInset), + tv.bottomAnchor.constraint(equalTo: self.bottomAnchor, constant: -bottomInset) + ]) + } +} diff --git a/GeneralUtils/GeneralUtils/ui/views/UILableCustomLeftImage.swift b/GeneralUtils/GeneralUtils/ui/views/UILableCustomLeftImage.swift new file mode 100644 index 0000000..0d40473 --- /dev/null +++ b/GeneralUtils/GeneralUtils/ui/views/UILableCustomLeftImage.swift @@ -0,0 +1,86 @@ +import UIKit +import Foundation + +@IBDesignable public class UILableCustomLeftImage: UIViewCustom { + public var imageView: UIImageView! + public var tvTitle: UILabel! + public var viewRoot: UIStackView! + + + public override init(frame: CGRect) { + super.init(frame: frame) + setupView() + } + + public required init?(coder aDecoder: NSCoder) { + super.init(coder: aDecoder) + setupView() + } + + @IBInspectable public var image: UIImage? = nil { + didSet { + imageView.image = image + } + } + @IBInspectable public var imageW: CGFloat = 25 { + didSet { + imageView.widthAnchor.constraint(equalToConstant: imageW).isActive = true + } + } + @IBInspectable public var textPading: CGFloat = 6 { + didSet { + viewRoot.spacing = textPading + } + } + @IBInspectable public var textColor: UIColor? = nil { + didSet { + tvTitle.textColor = textColor + } + } + @IBInspectable public var numberOfLines: Int = 1 { + didSet { + tvTitle.numberOfLines = numberOfLines + } + } + + @IBInspectable public var text: String? = nil { + didSet { + tvTitle.text = text + } + } + + @IBInspectable public var align: String = "left" { + didSet { + switch align { + case "left": + viewRoot.leftAnchor.constraint(equalTo: self.leftAnchor, constant: 8).isActive = true + return + case "right": + viewRoot.rightAnchor.constraint(equalTo: self.rightAnchor, constant: -8).isActive = true + return + case "center": + viewRoot.centerXAnchor.constraint(equalTo: self.centerXAnchor).isActive = true + return + default: + break + } + } + } + + + private func setupView() { + viewRoot = UIStackView() + self.addSubview(viewRoot) + viewRoot.translatesAutoresizingMaskIntoConstraints = false + viewRoot.axis = UILayoutConstraintAxis.horizontal + imageView = UIImageView() + imageView.contentMode = UIViewContentMode.scaleAspectFit + tvTitle = UILabel() + imageView.translatesAutoresizingMaskIntoConstraints = false + tvTitle.translatesAutoresizingMaskIntoConstraints = false + + viewRoot.addArrangedSubview(imageView) + viewRoot.addArrangedSubview(tvTitle) + viewRoot.centerYAnchor.constraint(equalTo: self.centerYAnchor).isActive = true + } +} diff --git a/GeneralUtils/GeneralUtils/ui/views/UITextViewCustom.swift b/GeneralUtils/GeneralUtils/ui/views/UITextViewCustom.swift new file mode 100644 index 0000000..8e0319a --- /dev/null +++ b/GeneralUtils/GeneralUtils/ui/views/UITextViewCustom.swift @@ -0,0 +1,25 @@ +import UIKit +import Foundation + +@IBDesignable +public class UITextViewCustom: UITextView { + @IBInspectable public var cornerRadius: CGFloat = 0 { + didSet { + layer.cornerRadius = cornerRadius + layer.masksToBounds = cornerRadius > 0 + } + } + + @IBInspectable public var borderWidth: CGFloat = 0 { + didSet { + layer.borderWidth = borderWidth + } + } + + @IBInspectable public var borderColor: UIColor = UIColor.black { + didSet { + layer.borderColor = borderColor.cgColor + } + } + +} \ No newline at end of file diff --git a/GeneralUtils/GeneralUtils/ui/views/UIViewCustom.swift b/GeneralUtils/GeneralUtils/ui/views/UIViewCustom.swift new file mode 100644 index 0000000..a226f11 --- /dev/null +++ b/GeneralUtils/GeneralUtils/ui/views/UIViewCustom.swift @@ -0,0 +1,94 @@ +// +// UIViewCustom.swift +// LuyenThiTOEIC +// +// Created by Philip Tran on 12/20/16. +// Copyright © 2016 Learn English A To Z. All rights reserved. +// + +import Foundation +import UIKit + +@IBDesignable +public class UIViewCustom: UIView { + public var tagObj: Any? + + @IBInspectable public var cornerRadius: CGFloat = 0 { + didSet { + layer.cornerRadius = cornerRadius + layer.masksToBounds = cornerRadius > 0 + } + } + + @IBInspectable public var borderWidth: CGFloat = 0 { + didSet { + layer.borderWidth = borderWidth + } + } + + @IBInspectable public var borderColor: UIColor = UIColor.black { + didSet { + layer.borderColor = borderColor.cgColor + } + } + + @IBInspectable public var backgroundColorHightlight: UIColor? = nil { + didSet { + updateHightlightToUI() + } + } + + private var _isSelected: Bool = false + private var bgColorSave: UIColor? + public func setSelected(isSelected: Bool) { + _isSelected = isSelected + updateHightlightToUI() + } + + public func isSelected() -> Bool { + return _isSelected + } + + private func updateHightlightToUI() { + if _isSelected { + if bgColorSave == nil { + bgColorSave = backgroundColor + } + backgroundColor = backgroundColorHightlight + } else { + backgroundColor = bgColorSave + } + } + + public func setShadowOffset(_ width: CGFloat, height: CGFloat, opacity: Float) { + layer.shadowColor = UIColor.black.cgColor + layer.shadowOffset = CGSize(width: width, height: height) + layer.shadowOpacity = 0.3 + } + + public func setOnClickListener(clickAction: @escaping (() -> ())) { + self.isUserInteractionEnabled = true + self.clickAction = clickAction + self.addGestureRecognizer(UITapGestureRecognizer(target: self, action: #selector(onClickEvent))) + } + + private var clickAction: (() -> ())? + public func onClickEvent() { + clickAction?() + } + + public override func touchesBegan(_ touches: Set, with event: UIEvent?) { + if clickAction != nil { self.layer.opacity = 0.75 } + super.touchesBegan(touches, with: event) + } + + public override func touchesEnded(_ touches: Set, with event: UIEvent?) { + if clickAction != nil { self.layer.opacity = 1.0 } + super.touchesEnded(touches, with: event) + } + + public override func touchesCancelled(_ touches: Set, with event: UIEvent?) { + if clickAction != nil { self.layer.opacity = 1.0 } + super.touchesCancelled(touches, with: event) + } +} diff --git a/GeneralUtils/GeneralUtils/ui/views/UIViewCustomGradientBg.swift b/GeneralUtils/GeneralUtils/ui/views/UIViewCustomGradientBg.swift new file mode 100644 index 0000000..fabe8b6 --- /dev/null +++ b/GeneralUtils/GeneralUtils/ui/views/UIViewCustomGradientBg.swift @@ -0,0 +1,37 @@ +import Foundation +import UIKit + +public class UIViewCustomGradientBg: UIViewCustom { + @IBInspectable public var startColor: UIColor = UIColor.init(hexString: "#FBFBFB") + @IBInspectable public var endColor: UIColor = UIColor.init(hexString: "#D0D0D0") + + @IBInspectable public var startLocation: Double = 0.05 + @IBInspectable public var endLocation: Double = 0.95 + + @IBInspectable public var horizontalMode: Bool = false { + didSet { + layoutSubviews() + } + } + @IBInspectable public var diagonalMode: Bool = false { + didSet { + layoutSubviews() + } + } + + public override class var layerClass: AnyClass { return CAGradientLayer.self } + public var gradientLayer: CAGradientLayer { return layer as! CAGradientLayer } + + public override func layoutSubviews() { + super.layoutSubviews() + if horizontalMode { + gradientLayer.startPoint = diagonalMode ? CGPoint(x: 1, y: 0) : CGPoint(x: 0, y: 0.5) + gradientLayer.endPoint = diagonalMode ? CGPoint(x: 0, y: 1) : CGPoint(x: 1, y: 0.5) + } else { + gradientLayer.startPoint = diagonalMode ? CGPoint(x: 0, y: 0) : CGPoint(x: 0.5, y: 0) + gradientLayer.endPoint = diagonalMode ? CGPoint(x: 1, y: 1) : CGPoint(x: 0.5, y: 1) + } + gradientLayer.locations = [startLocation as NSNumber, endLocation as NSNumber] + gradientLayer.colors = [startColor.cgColor, endColor.cgColor] + } +} diff --git a/GeneralUtils/GeneralUtils/ui/views/UIViewCustomPressHightLight.swift b/GeneralUtils/GeneralUtils/ui/views/UIViewCustomPressHightLight.swift new file mode 100644 index 0000000..08d8a4a --- /dev/null +++ b/GeneralUtils/GeneralUtils/ui/views/UIViewCustomPressHightLight.swift @@ -0,0 +1,19 @@ +import Foundation +import UIKit + +public class UIViewCustomPressHightLight: UIViewCustom{ + public override func touchesBegan(_ touches: Set, with event: UIEvent?) { + self.layer.opacity = 0.7 + super.touchesBegan(touches, with: event) + } + + public override func touchesEnded(_ touches: Set, with event: UIEvent?) { + self.layer.opacity = 1.0 + super.touchesEnded(touches, with: event) + } + + public override func touchesCancelled(_ touches: Set, with event: UIEvent?) { + self.layer.opacity = 1.0 + super.touchesCancelled(touches, with: event) + } +} diff --git a/GeneralUtils/GeneralUtils/ui/views/VPlayerControl.swift b/GeneralUtils/GeneralUtils/ui/views/VPlayerControl.swift new file mode 100644 index 0000000..97bff4c --- /dev/null +++ b/GeneralUtils/GeneralUtils/ui/views/VPlayerControl.swift @@ -0,0 +1,172 @@ +import Foundation +import UIKit + +/** +Chỉ gồm slider + 2 cái time ở 2 đầu +*/ +public class VPlayerControl: UIView { + public var btnPlay: UIButton! + public var tvTimePlay: UILabel!, tvTotalTime: UILabel! + public var bgView: UIView! + public var slider: UISlider! + public var player: IPlayer? + + public var isPlaying: Bool = false + + public override init(frame: CGRect) { + super.init(frame: frame) + setupView() + } + + public required init?(coder aDecoder: NSCoder) { + super.init(coder: aDecoder) + setupView() + } + + private func setupView() { + super.backgroundColor = UIColor.clear + bgView = UIView() + bgView.translatesAutoresizingMaskIntoConstraints = false + addSubview(bgView) + bgView.leftAnchor.constraint(equalTo: self.leftAnchor, constant: 0).isActive = true + bgView.topAnchor.constraint(equalTo: self.topAnchor, constant: 0).isActive = true + bgView.rightAnchor.constraint(equalTo: self.rightAnchor, constant: 0).isActive = true + bgView.bottomAnchor.constraint(equalTo: self.bottomAnchor, constant: 0).isActive = true + + btnPlay = UIButton.init() + btnPlay.contentEdgeInsets = UIEdgeInsetsMake(3, 3, 3, 3) + btnPlay.setImage(#imageLiteral(resourceName:"play_filled"), for: UIControlState.normal) + btnPlay.contentMode = UIViewContentMode.scaleAspectFit + btnPlay.translatesAutoresizingMaskIntoConstraints = false + addSubview(btnPlay) + btnPlay.widthAnchor.constraint(equalToConstant: 40).isActive = true + btnPlay.heightAnchor.constraint(equalToConstant: 40).isActive = true + btnPlay.centerYAnchor.constraint(equalTo: self.centerYAnchor).isActive = true + btnPlay.leftAnchor.constraint(equalTo: self.leftAnchor, constant: 8).isActive = true + btnPlay.addTarget(self, action: #selector(btnPausePlayClick), for: .touchUpInside) + + let grayColor = UIColor.init(hexString: "#494949") + tvTimePlay = UILabel() + tvTimePlay.text = "0:00" + tvTimePlay.numberOfLines = 1 + tvTimePlay.font = UIFont.systemFont(ofSize: 15) + tvTimePlay.textColor = grayColor + tvTimePlay.translatesAutoresizingMaskIntoConstraints = false + addSubview(tvTimePlay) + tvTimePlay.centerYAnchor.constraint(equalTo: self.centerYAnchor).isActive = true + tvTimePlay.leftAnchor.constraint(equalTo: btnPlay.rightAnchor, constant: 12).isActive = true + + tvTotalTime = UILabel.init() + tvTotalTime.text = "0:00" + tvTotalTime.numberOfLines = 1 + tvTotalTime.font = UIFont.systemFont(ofSize: 15) + tvTotalTime.textColor = grayColor + tvTotalTime.translatesAutoresizingMaskIntoConstraints = false + addSubview(tvTotalTime) + tvTotalTime.centerYAnchor.constraint(equalTo: self.centerYAnchor).isActive = true + tvTotalTime.rightAnchor.constraint(equalTo: self.rightAnchor, constant: -8).isActive = true + + slider = UISlider() + slider.translatesAutoresizingMaskIntoConstraints = false +// slider.maximumTrackTintColor = grayColor +// slider.minimumTrackTintColor = UIColor.white + addSubview(slider) + slider.centerYAnchor.constraint(equalTo: self.centerYAnchor).isActive = true + slider.leftAnchor.constraint(equalTo: tvTimePlay.rightAnchor, constant: 8).isActive = true + slider.rightAnchor.constraint(equalTo: tvTotalTime.leftAnchor, constant: -8).isActive = true + slider.isContinuous = true + slider.addTarget(self, action: #selector(sliderNumberValueChanged), for: UIControlEvents.valueChanged) + + self.layoutIfNeeded() + } + + public func btnPausePlayClick() { + isPlaying = !isPlaying + if isPlaying { + isPlaying = player?.play() ?? false + }else{ + player?.pause() + } + updateBtnPlayState() + } + + public func updateBtnPlayState() { + if isPlaying == true { + if !isHidden { + startUpdateTimeToSlider() + } + btnPlay.setImageWithOutAnimation(#imageLiteral(resourceName:"pause_filled")) + } else { + stopUpdateTimeToSlider() + btnPlay.setImageWithOutAnimation(#imageLiteral(resourceName:"play_filled")) + } + } + + //MARK: ====== Slider ======= + public var timerUpdateTimeSlider: Timer? + private var totalTime: Double? + + public func sliderNumberValueChanged() { + if totalTime == nil { + if let duration = player?.getDuration() { + totalTime = Double(duration) + } + } + guard let totalTime = totalTime else { + return + } + player?.seekTo(slider.value * Float(totalTime), seekAhead: true) + } + + fileprivate func startUpdateTimeToSlider() { + totalTime = player?.getDuration() + updateTimeToSlider() + if timerUpdateTimeSlider == nil { + timerUpdateTimeSlider = Timer.scheduledTimer(timeInterval: 1, target: self, selector: #selector(self.updateTimeToSlider), userInfo: nil, repeats: true) + } + } + + fileprivate func stopUpdateTimeToSlider() { + timerUpdateTimeSlider?.invalidate() + timerUpdateTimeSlider = nil + } + + @objc private func updateTimeToSlider() { + if let player = self.player { + if totalTime == nil { + if let duration = player.getDuration() { + totalTime = Double(duration) + } + } + guard let totalTime = totalTime else { + return + } + let currentTime = player.getCurrentTime() + slider.value = Float(Double(currentTime) / totalTime) + tvTimePlay.text = DataTypeUtils.convertTimeDisplayInPlay(miliSecond: Int64(currentTime * 1000)) + println("currentTime: \(currentTime)") + } + } + + public override func willRemoveSubview(_ subview: UIView) { + super.willRemoveSubview(subview) + releaseResource() + } + public override func removeFromSuperview() { + super.removeFromSuperview() + releaseResource() + } + public func releaseResource() { + stopUpdateTimeToSlider() + player?.stop() + } +} + +public protocol IPlayer { + func getCurrentTime() -> Int + func getDuration() -> Double? + func seekTo(_ seconds: Float, seekAhead: Bool) + func play() -> Bool + func pause() + func stop() +} diff --git a/GeneralUtils/GeneralUtils/ui/views/VTopNotification/VTopNotification.swift b/GeneralUtils/GeneralUtils/ui/views/VTopNotification/VTopNotification.swift new file mode 100644 index 0000000..eeca6aa --- /dev/null +++ b/GeneralUtils/GeneralUtils/ui/views/VTopNotification/VTopNotification.swift @@ -0,0 +1,45 @@ +import Foundation +import UIKit + +public class VTopNotification: UIView { + @IBOutlet public weak var tvTitle: UILabel! + @IBOutlet public weak var tvSubTitle: UILabel! + + public override init(frame: CGRect) { + super.init(frame: frame) + xibSetup() + } + + public required init?(coder aDecoder: NSCoder) { + super.init(coder: aDecoder) + xibSetup() + } + + func xibSetup() { + let bundle = Bundle(for: type(of: self)) + let nib = UINib(nibName: "VTopNotification", bundle: bundle) + let view = nib.instantiate(withOwner: self, options: nil)[0] as! UIView + + view.frame = bounds + view.autoresizingMask = [UIViewAutoresizing.flexibleWidth, UIViewAutoresizing.flexibleHeight] + addSubview(view) + } + + public func setData(title: String?, subTitle: String?) { + if let title = title { + tvTitle.text = title + } else { + tvTitle.isHidden = true + } + + if let subTitle = subTitle { + tvSubTitle.text = subTitle + } else { + tvSubTitle.isHidden = true + } + } + + @IBAction public func btnCloseClick(_ sender: Any) { + self.removeFromSuperview() + } +} diff --git a/GeneralUtils/GeneralUtils/ui/views/VTopNotification/VTopNotification.xib b/GeneralUtils/GeneralUtils/ui/views/VTopNotification/VTopNotification.xib new file mode 100644 index 0000000..ff867f6 --- /dev/null +++ b/GeneralUtils/GeneralUtils/ui/views/VTopNotification/VTopNotification.xib @@ -0,0 +1,68 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/GeneralUtils/GeneralUtils/ui/views/vTopBar/ViewTopBar.swift b/GeneralUtils/GeneralUtils/ui/views/vTopBar/ViewTopBar.swift new file mode 100644 index 0000000..9952ccd --- /dev/null +++ b/GeneralUtils/GeneralUtils/ui/views/vTopBar/ViewTopBar.swift @@ -0,0 +1,196 @@ +import Foundation +import UIKit + +/* + topBar.setTableViewConnected(tableViewConnected: tableViewLoadData, topMargin: topMargin) + leftButtonClick +*/ + +@IBDesignable public class ViewTopBar: UIView, UITableViewDelegate, UITextFieldDelegate { + @IBOutlet public weak var btnLeft: UIButtonCustom! + @IBOutlet public weak var tvTitle: UILabel! + @IBOutlet public weak var stackContent: UIStackView! + @IBOutlet public var rootV: UIView! + + public var leftButtonClick: ((UIView) -> ())? + + public var editSearch: UITextField!, btnSearch: UIButtonCustom? + public var searchDelegate: ISearchAble? + public var isCallBackWhenChangeText: Bool = false + + public override init(frame: CGRect) { + super.init(frame: frame) + xibSetup() + } + + public required init?(coder aDecoder: NSCoder) { + super.init(coder: aDecoder) + xibSetup() + } + + func xibSetup() { + let bundle = Bundle(for: type(of: self)) + let nib = UINib(nibName: "ViewTopBar", bundle: bundle) + let view = nib.instantiate(withOwner: self, options: nil)[0] as! UIView + + view.frame = bounds + view.autoresizingMask = [UIViewAutoresizing.flexibleWidth, UIViewAutoresizing.flexibleHeight] + addSubview(view) + } + + @IBInspectable public var title: String? = nil { + didSet { + tvTitle.text = title + } + } + + @IBInspectable public var leftImage: UIImage? = nil { + didSet { + btnLeft.setTitle(nil, for: UIControlState()) + btnLeft.padding = 8 + btnLeft.setImage(leftImage, for: UIControlState()) + btnLeft.isHidden = false + } + } + + @IBAction public func btnBackClick(_ sender: UIButton) { + if hideSearch() { return } + if let leftButtonClick = leftButtonClick { + leftButtonClick(sender) + } else { + self.parentViewController?.dismiss(animated: true, completion: nil) + } + } + + @discardableResult public func addRightButton(image: UIImage? = nil, text: String? = nil, target: Any?, action: Selector) -> UIButtonCustom { + let btn = UIButtonCustom() + btn.widthAnchor.constraint(equalToConstant: 48).isActive = true + if let image = image { + btn.setImage(image, for: UIControlState.normal) + btn.padding = 12 + } else { + btn.setTitle(text, for: UIControlState.normal) + } + + stackContent.addArrangedSubview(btn) + btn.addTarget(target, action: action, for: UIControlEvents.touchUpInside) + return btn + } + + + // MARK: Scroll Tableview for hide Topbar + fileprivate var lastY: CGFloat = 0, height: CGFloat! + fileprivate var topMargin: NSLayoutConstraint! + public func setTableViewConnected(tableViewConnected: BaseTbLoadData, topMargin: NSLayoutConstraint) { + tableViewConnected.customDelegate = self + self.topMargin = topMargin + } + + public override func layoutSubviews() { + super.layoutSubviews() + height = self.bounds.height + 40 // 40 la cai bar notification + } + + public func scrollViewDidScroll(_ scrollView: UIScrollView) { + if editSearch?.isHidden == false { return } + guard let height = height else { return } + let yOffset = scrollView.contentOffset.y + let sub = yOffset - lastY + lastY = yOffset + + if yOffset == 0 { + topMargin.constant = 0 + return + } + if yOffset < 0 { + return + } + if (scrollView.contentOffset.y >= (scrollView.contentSize.height - scrollView.frame.size.height)) { + //reach bottom + return + } + + + let currentTop = topMargin.constant + if sub > 0 && currentTop <= -height { + return + } + if sub <= 0 && currentTop >= 0 { + return + } + var newTop = currentTop - sub + if newTop > 0 { + newTop = 0 + } + if newTop < -height { + newTop = -height + } + topMargin.constant = newTop + } + + + //MARK: ======= Search === + public func addSearch(isCallBackWhenChangeText: Bool, searchDelegate: ISearchAble) { + self.isCallBackWhenChangeText = isCallBackWhenChangeText + self.searchDelegate = searchDelegate + btnSearch = self.addRightButton(image: #imageLiteral(resourceName:"search_gray"), text: nil, target: self, action: #selector(ViewTopBar.showSearch)) + editSearch = UITextField() + rootV.addSubview(editSearch) + editSearch.font = UIFont.systemFont(ofSize: 16) + editSearch.clearButtonMode = .whileEditing + editSearch.returnKeyType = .search + editSearch.autocorrectionType = .no + editSearch.translatesAutoresizingMaskIntoConstraints = false + NSLayoutConstraint.activate([editSearch.leftAnchor.constraint(equalTo: rootV.leftAnchor, constant: 50), + editSearch.heightAnchor.constraint(equalToConstant: 30), + editSearch.centerYAnchor.constraint(equalTo: rootV.centerYAnchor), + editSearch.rightAnchor.constraint(equalTo: rootV.rightAnchor, constant: -8)]) + editSearch.isHidden = true + editSearch.delegate = self + if isCallBackWhenChangeText { + editSearch?.addTarget(self, action: #selector(textFieldSearchDidChange(_:)), for: UIControlEvents.editingChanged) + } + } + + public func hideSearch() -> Bool { + if editSearch?.isHidden == false { + tvTitle.isHidden = false + btnSearch?.isHidden = false + editSearch.isHidden = true + editSearch.endEditing(true) + editSearch.text = nil + btnLeft.setImageWithOutAnimation(#imageLiteral(resourceName:"ic_menu_black")) + searchDelegate?.closeSearch?() + return true + } + return false + } + + public func showSearch() { + tvTitle.isHidden = true + btnSearch?.isHidden = true + btnLeft.setImageWithOutAnimation(#imageLiteral(resourceName:"ic_arrow_back_black")) + editSearch.isHidden = false + editSearch.becomeFirstResponder() + searchDelegate?.openSearch?() + } + + public func textFieldShouldReturn(_ textField: UITextField) -> Bool { + searchDelegate?.updateResult(textField.text) + editSearch?.endEditing(true) + return true + } + + public func textFieldSearchDidChange(_ textField: UITextField) { + println("textFieldSearchDidChange: \(textField.text)") + searchDelegate?.updateResult(textField.text) + } +} + +@objc public protocol ISearchAble { + func updateResult(_ keyword: String?) + + @objc optional func closeSearch() + + @objc optional func openSearch() +} diff --git a/GeneralUtils/GeneralUtils/ui/views/vTopBar/ViewTopBar.xib b/GeneralUtils/GeneralUtils/ui/views/vTopBar/ViewTopBar.xib new file mode 100644 index 0000000..369ac9d --- /dev/null +++ b/GeneralUtils/GeneralUtils/ui/views/vTopBar/ViewTopBar.xib @@ -0,0 +1,81 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/GeneralUtils/LICENSE b/GeneralUtils/LICENSE new file mode 100644 index 0000000..5e3345f --- /dev/null +++ b/GeneralUtils/LICENSE @@ -0,0 +1,21 @@ +MIT License + +Copyright (c) [2017] [Quan Trinh] + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +SOFTWARE. \ No newline at end of file diff --git a/GeneralUtils/readme.txt b/GeneralUtils/readme.txt new file mode 100644 index 0000000..7eb913c --- /dev/null +++ b/GeneralUtils/readme.txt @@ -0,0 +1,10 @@ +1. Commit new code to githup + 1.1: git tag 1.0.2 (version chung) + git push -u origin master --tags + + +2. Thay đổi version trong file: GeneralUtils.podspec (giong version: 1.0.2) + +3. Thực hiện câu lệnh: (cd ở thư mục gốc) +pod repo push GeneralUtilsSpecs GeneralUtils.podspec --allow-warnings + diff --git a/Morooka.xcodeproj/project.pbxproj b/Morooka.xcodeproj/project.pbxproj index 9013668..03f5f40 100644 --- a/Morooka.xcodeproj/project.pbxproj +++ b/Morooka.xcodeproj/project.pbxproj @@ -7,6 +7,7 @@ objects = { /* Begin PBXBuildFile section */ + 5295F7353243DB8420D8D2C3 /* Pods_App.framework in Frameworks */ = {isa = PBXBuildFile; fileRef = 40743288DB54B341F7871747 /* Pods_App.framework */; }; 660BB013C4E60014E7DE6D0E /* ConfirmViewController.xib in Resources */ = {isa = PBXBuildFile; fileRef = 660BB83415EF36FF4965CB7B /* ConfirmViewController.xib */; }; 660BB033B71888619909D955 /* CellMucChupWithDelete.swift in Sources */ = {isa = PBXBuildFile; fileRef = 660BB4BD64E5830D866508ED /* CellMucChupWithDelete.swift */; }; 660BB07A7088B09DCF79C287 /* Board.swift in Sources */ = {isa = PBXBuildFile; fileRef = 660BBF0AFE4AA39A948B2960 /* Board.swift */; }; @@ -46,8 +47,11 @@ 660BBA3716805687B7792B79 /* PermissionsView.swift in Sources */ = {isa = PBXBuildFile; fileRef = 660BBE8254E91AD46A2AE93A /* PermissionsView.swift */; }; 660BBAA50200499BC72A31C9 /* VCBuyIncreasePerson.swift in Sources */ = {isa = PBXBuildFile; fileRef = 660BB10AEDBCEAFF2B1CE9C5 /* VCBuyIncreasePerson.swift */; }; 660BBADAAE9A0A55D305AFE6 /* VCPageImgs.swift in Sources */ = {isa = PBXBuildFile; fileRef = 660BB6F68DE152D997AF51E5 /* VCPageImgs.swift */; }; + 660BBAFF5B4B94C3D5D97EB5 /* FileUpload.swift in Sources */ = {isa = PBXBuildFile; fileRef = 660BB1A1B9544504860AAF96 /* FileUpload.swift */; }; + 660BBB52CA48D9835B2B4FA7 /* Constants.swift in Sources */ = {isa = PBXBuildFile; fileRef = 660BB506E0AB7C3B69DBE5D0 /* Constants.swift */; }; + 660BBBC00FF5818CE1A37FF7 /* NetWorkUtils.swift in Sources */ = {isa = PBXBuildFile; fileRef = 660BB550B5859DEC8E981BD6 /* NetWorkUtils.swift */; }; 660BBC4ABDFD58FD5C6099A0 /* CameraGlobals.swift in Sources */ = {isa = PBXBuildFile; fileRef = 660BB5CF515C992993C639D7 /* CameraGlobals.swift */; }; - 660BBCD1A02935C5843544B6 /* MucChup.swift in Sources */ = {isa = PBXBuildFile; fileRef = 660BB6D0167C62DED01BDA8D /* MucChup.swift */; }; + 660BBCD1A02935C5843544B6 /* ShootItem.swift in Sources */ = {isa = PBXBuildFile; fileRef = 660BB6D0167C62DED01BDA8D /* ShootItem.swift */; }; 660BBCE4359255D8B1472A47 /* MyConfirmViewController.swift in Sources */ = {isa = PBXBuildFile; fileRef = 660BB05216803EF2132F3387 /* MyConfirmViewController.swift */; }; 660BBD1BB9F8EF15AE9110BA /* PhotoLibraryViewController.swift in Sources */ = {isa = PBXBuildFile; fileRef = 660BBF2396B302943FBE2314 /* PhotoLibraryViewController.swift */; }; 660BBD73E0E1916B0402099D /* VCChonMucChup.swift in Sources */ = {isa = PBXBuildFile; fileRef = 660BB200DE1903184FAFF325 /* VCChonMucChup.swift */; }; @@ -63,9 +67,9 @@ 660BBFBA6272BCEDD0B31F4E /* ImageCell.swift in Sources */ = {isa = PBXBuildFile; fileRef = 660BBB621D93C542465A66E4 /* ImageCell.swift */; }; 660BBFD5638465D1B6E59B32 /* DatePickerDialog.swift in Sources */ = {isa = PBXBuildFile; fileRef = 660BB9BAD144DB921786A76F /* DatePickerDialog.swift */; }; 660BBFDEADB8218026818F26 /* CellChonMucChup.swift in Sources */ = {isa = PBXBuildFile; fileRef = 660BB07FA9FE3DE9908DD8E9 /* CellChonMucChup.swift */; }; - F983DFDA1E696D64008FEC23 /* GeneralUtils.framework in Frameworks */ = {isa = PBXBuildFile; fileRef = F983DFD91E696D53008FEC23 /* GeneralUtils.framework */; }; - F983DFDD1E696F4E008FEC23 /* GeneralUtils.framework in Frameworks */ = {isa = PBXBuildFile; fileRef = F983DFD91E696D53008FEC23 /* GeneralUtils.framework */; }; - F983DFDE1E696F4E008FEC23 /* GeneralUtils.framework in Embed Frameworks */ = {isa = PBXBuildFile; fileRef = F983DFD91E696D53008FEC23 /* GeneralUtils.framework */; settings = {ATTRIBUTES = (CodeSignOnCopy, RemoveHeadersOnCopy, ); }; }; + F9D421D61E6C029600D4F936 /* GeneralUtils.framework in Frameworks */ = {isa = PBXBuildFile; fileRef = 660BB4D67F3203721378E5E3 /* GeneralUtils.framework */; }; + F9D421D71E6C029D00D4F936 /* GeneralUtils.framework in Frameworks */ = {isa = PBXBuildFile; fileRef = 660BB4D67F3203721378E5E3 /* GeneralUtils.framework */; }; + F9D421D81E6C029D00D4F936 /* GeneralUtils.framework in Embed Frameworks */ = {isa = PBXBuildFile; fileRef = 660BB4D67F3203721378E5E3 /* GeneralUtils.framework */; settings = {ATTRIBUTES = (CodeSignOnCopy, RemoveHeadersOnCopy, ); }; }; F9D8E6941E617E2E00D789BF /* Localizable.strings in Resources */ = {isa = PBXBuildFile; fileRef = F9D8E6931E617E2E00D789BF /* Localizable.strings */; }; F9F648141E6105EA009CCEBD /* AppDelegate.swift in Sources */ = {isa = PBXBuildFile; fileRef = F9F648131E6105EA009CCEBD /* AppDelegate.swift */; }; F9F648191E6105EA009CCEBD /* Main.storyboard in Resources */ = {isa = PBXBuildFile; fileRef = F9F648171E6105EA009CCEBD /* Main.storyboard */; }; @@ -75,23 +79,16 @@ /* End PBXBuildFile section */ /* Begin PBXContainerItemProxy section */ - F983DFD81E696D53008FEC23 /* PBXContainerItemProxy */ = { + 660BBAA989A4FF96F0ED0E24 /* PBXContainerItemProxy */ = { isa = PBXContainerItemProxy; - containerPortal = F983DFD41E696D52008FEC23 /* GeneralUtils.xcodeproj */; + containerPortal = 660BBECA0152D9F9EFAEE76C /* GeneralUtils.xcodeproj */; proxyType = 2; remoteGlobalIDString = F976D5061E68747800708D6A; remoteInfo = GeneralUtils; }; - F983DFDB1E696F43008FEC23 /* PBXContainerItemProxy */ = { + F9D421D91E6C029D00D4F936 /* PBXContainerItemProxy */ = { isa = PBXContainerItemProxy; - containerPortal = F983DFD41E696D52008FEC23 /* GeneralUtils.xcodeproj */; - proxyType = 1; - remoteGlobalIDString = F976D5051E68747800708D6A; - remoteInfo = GeneralUtils; - }; - F983DFDF1E696F4E008FEC23 /* PBXContainerItemProxy */ = { - isa = PBXContainerItemProxy; - containerPortal = F983DFD41E696D52008FEC23 /* GeneralUtils.xcodeproj */; + containerPortal = 660BBECA0152D9F9EFAEE76C /* GeneralUtils.xcodeproj */; proxyType = 1; remoteGlobalIDString = F976D5051E68747800708D6A; remoteInfo = GeneralUtils; @@ -105,7 +102,7 @@ dstPath = ""; dstSubfolderSpec = 10; files = ( - F983DFDE1E696F4E008FEC23 /* GeneralUtils.framework in Embed Frameworks */, + F9D421D81E6C029D00D4F936 /* GeneralUtils.framework in Embed Frameworks */, ); name = "Embed Frameworks"; runOnlyForDeploymentPostprocessing = 0; @@ -113,11 +110,14 @@ /* End PBXCopyFilesBuildPhase section */ /* Begin PBXFileReference section */ + 40743288DB54B341F7871747 /* Pods_App.framework */ = {isa = PBXFileReference; explicitFileType = wrapper.framework; includeInIndex = 0; path = Pods_App.framework; sourceTree = BUILT_PRODUCTS_DIR; }; + 4E5AC66CBCD4532E16FE2D27 /* Pods-App.debug.xcconfig */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = text.xcconfig; name = "Pods-App.debug.xcconfig"; path = "Pods/Target Support Files/Pods-App/Pods-App.debug.xcconfig"; sourceTree = ""; }; 660BB041F5A4CA9D1B8458C4 /* SingleImageSaver.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = SingleImageSaver.swift; sourceTree = ""; }; 660BB05216803EF2132F3387 /* MyConfirmViewController.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = MyConfirmViewController.swift; sourceTree = ""; }; 660BB07FA9FE3DE9908DD8E9 /* CellChonMucChup.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = CellChonMucChup.swift; sourceTree = ""; }; 660BB0E00FC88552ADCCED03 /* VTopLogo.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = VTopLogo.swift; sourceTree = ""; }; 660BB10AEDBCEAFF2B1CE9C5 /* VCBuyIncreasePerson.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = VCBuyIncreasePerson.swift; sourceTree = ""; }; + 660BB1A1B9544504860AAF96 /* FileUpload.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = FileUpload.swift; sourceTree = ""; }; 660BB200DE1903184FAFF325 /* VCChonMucChup.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = VCChonMucChup.swift; sourceTree = ""; }; 660BB27DB3FB3EDB27BCE3DD /* CellMucChupWithCamera.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = CellMucChupWithCamera.swift; sourceTree = ""; }; 660BB2840726DE1BF658FE6C /* CameraShot.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = CameraShot.swift; sourceTree = ""; }; @@ -130,12 +130,14 @@ 660BB4BD64E5830D866508ED /* CellMucChupWithDelete.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = CellMucChupWithDelete.swift; sourceTree = ""; }; 660BB4DD0B25B26182BAE9F2 /* Session.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = Session.swift; sourceTree = ""; }; 660BB50191A22EBA51FE1A0C /* VCNhapTenCtruong.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = VCNhapTenCtruong.swift; sourceTree = ""; }; + 660BB506E0AB7C3B69DBE5D0 /* Constants.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = Constants.swift; sourceTree = ""; }; + 660BB550B5859DEC8E981BD6 /* NetWorkUtils.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = NetWorkUtils.swift; sourceTree = ""; }; 660BB5A65671E9D02EA89389 /* ConfirmViewController.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = ConfirmViewController.swift; sourceTree = ""; }; 660BB5CCC89015E195B8616B /* VCHome.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = VCHome.swift; sourceTree = ""; }; 660BB5CF515C992993C639D7 /* CameraGlobals.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = CameraGlobals.swift; sourceTree = ""; }; 660BB6690D915951748165C5 /* VCRootCreateNew.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = VCRootCreateNew.swift; sourceTree = ""; }; 660BB6B5D850CD8C79FB46AE /* CameraViewController.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = CameraViewController.swift; sourceTree = ""; }; - 660BB6D0167C62DED01BDA8D /* MucChup.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = MucChup.swift; sourceTree = ""; }; + 660BB6D0167C62DED01BDA8D /* ShootItem.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = ShootItem.swift; sourceTree = ""; }; 660BB6F68DE152D997AF51E5 /* VCPageImgs.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = VCPageImgs.swift; sourceTree = ""; }; 660BB702D96360C446B9F0F8 /* VCRoot.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = VCRoot.swift; sourceTree = ""; }; 660BB70C02558F318204A58E /* ImgObj.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = ImgObj.swift; sourceTree = ""; }; @@ -165,11 +167,12 @@ 660BBE7F33A6B7BE9E7D5723 /* VcEdit.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = VcEdit.swift; sourceTree = ""; }; 660BBE8254E91AD46A2AE93A /* PermissionsView.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = PermissionsView.swift; sourceTree = ""; }; 660BBE8DACAA2464075AFFF8 /* VCInputId.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = VCInputId.swift; sourceTree = ""; }; + 660BBECA0152D9F9EFAEE76C /* GeneralUtils.xcodeproj */ = {isa = PBXFileReference; lastKnownFileType = "wrapper.pb-project"; name = GeneralUtils.xcodeproj; path = GeneralUtils/GeneralUtils.xcodeproj; sourceTree = ""; }; 660BBEDF8CDE53E1B271BD54 /* VCNhapTenCty.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = VCNhapTenCty.swift; sourceTree = ""; }; 660BBF0AFE4AA39A948B2960 /* Board.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = Board.swift; sourceTree = ""; }; 660BBF2396B302943FBE2314 /* PhotoLibraryViewController.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = PhotoLibraryViewController.swift; sourceTree = ""; }; 660BBF69F72B470BE44AD1D8 /* VCConfirmId.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = VCConfirmId.swift; sourceTree = ""; }; - F983DFD41E696D52008FEC23 /* GeneralUtils.xcodeproj */ = {isa = PBXFileReference; lastKnownFileType = "wrapper.pb-project"; name = GeneralUtils.xcodeproj; path = ../../Lib/GeneralUtils/GeneralUtils.xcodeproj; sourceTree = ""; }; + 98A3103DA59678FDFDBA9065 /* Pods-App.release.xcconfig */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = text.xcconfig; name = "Pods-App.release.xcconfig"; path = "Pods/Target Support Files/Pods-App/Pods-App.release.xcconfig"; sourceTree = ""; }; F9D8E6931E617E2E00D789BF /* Localizable.strings */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = text.plist.strings; path = Localizable.strings; sourceTree = ""; }; F9F648101E6105EA009CCEBD /* App.app */ = {isa = PBXFileReference; explicitFileType = wrapper.application; includeInIndex = 0; path = App.app; sourceTree = BUILT_PRODUCTS_DIR; }; F9F648131E6105EA009CCEBD /* AppDelegate.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = AppDelegate.swift; sourceTree = ""; }; @@ -185,14 +188,23 @@ isa = PBXFrameworksBuildPhase; buildActionMask = 2147483647; files = ( - F983DFDA1E696D64008FEC23 /* GeneralUtils.framework in Frameworks */, - F983DFDD1E696F4E008FEC23 /* GeneralUtils.framework in Frameworks */, + F9D421D61E6C029600D4F936 /* GeneralUtils.framework in Frameworks */, + F9D421D71E6C029D00D4F936 /* GeneralUtils.framework in Frameworks */, + 5295F7353243DB8420D8D2C3 /* Pods_App.framework in Frameworks */, ); runOnlyForDeploymentPostprocessing = 0; }; /* End PBXFrameworksBuildPhase section */ /* Begin PBXGroup section */ + 660BB2253E0724743F7D90B1 /* Products */ = { + isa = PBXGroup; + children = ( + 660BB4D67F3203721378E5E3 /* GeneralUtils.framework */, + ); + name = Products; + sourceTree = ""; + }; 660BB510D628B92A26E01038 /* Views */ = { isa = PBXGroup; children = ( @@ -268,7 +280,7 @@ isa = PBXGroup; children = ( 660BB4DD0B25B26182BAE9F2 /* Session.swift */, - 660BB6D0167C62DED01BDA8D /* MucChup.swift */, + 660BB6D0167C62DED01BDA8D /* ShootItem.swift */, 660BB8C3076658F6777F23F4 /* CongTruong.swift */, 660BB70C02558F318204A58E /* ImgObj.swift */, ); @@ -340,6 +352,9 @@ children = ( 660BB7E1FEE6358AA0FF7932 /* SecurityUtils.swift */, 660BB42B47139662CF868143 /* AppUtils.swift */, + 660BB506E0AB7C3B69DBE5D0 /* Constants.swift */, + 660BB550B5859DEC8E981BD6 /* NetWorkUtils.swift */, + 660BB1A1B9544504860AAF96 /* FileUpload.swift */, ); path = utils; sourceTree = ""; @@ -354,28 +369,31 @@ path = firstInput; sourceTree = ""; }; - F44D129BC6EF626BD41DF3BC /* Frameworks */ = { + E6E524311AECE26D46DE3B7A /* Pods */ = { isa = PBXGroup; children = ( + 4E5AC66CBCD4532E16FE2D27 /* Pods-App.debug.xcconfig */, + 98A3103DA59678FDFDBA9065 /* Pods-App.release.xcconfig */, ); - name = Frameworks; + name = Pods; sourceTree = ""; }; - F983DFD51E696D52008FEC23 /* Products */ = { + F44D129BC6EF626BD41DF3BC /* Frameworks */ = { isa = PBXGroup; children = ( - F983DFD91E696D53008FEC23 /* GeneralUtils.framework */, + 40743288DB54B341F7871747 /* Pods_App.framework */, ); - name = Products; + name = Frameworks; sourceTree = ""; }; F9F648071E6105EA009CCEBD = { isa = PBXGroup; children = ( - F983DFD41E696D52008FEC23 /* GeneralUtils.xcodeproj */, F9F648121E6105EA009CCEBD /* App */, F9F648111E6105EA009CCEBD /* Products */, F44D129BC6EF626BD41DF3BC /* Frameworks */, + E6E524311AECE26D46DE3B7A /* Pods */, + 660BBECA0152D9F9EFAEE76C /* GeneralUtils.xcodeproj */, ); sourceTree = ""; }; @@ -415,16 +433,18 @@ isa = PBXNativeTarget; buildConfigurationList = F9F648221E6105EA009CCEBD /* Build configuration list for PBXNativeTarget "App" */; buildPhases = ( + D3F185E28D16DC603C27EC2F /* [CP] Check Pods Manifest.lock */, F9F6480C1E6105EA009CCEBD /* Sources */, F9F6480D1E6105EA009CCEBD /* Frameworks */, F9F6480E1E6105EA009CCEBD /* Resources */, F9519F2F1E695F4C0019EC20 /* Embed Frameworks */, + D05518C5A273FE90FC67BCCE /* [CP] Embed Pods Frameworks */, + DC704D4E2710E935A7EE93C8 /* [CP] Copy Pods Resources */, ); buildRules = ( ); dependencies = ( - F983DFDC1E696F43008FEC23 /* PBXTargetDependency */, - F983DFE01E696F4E008FEC23 /* PBXTargetDependency */, + F9D421DA1E6C029D00D4F936 /* PBXTargetDependency */, ); name = App; productName = App; @@ -460,8 +480,8 @@ projectDirPath = ""; projectReferences = ( { - ProductGroup = F983DFD51E696D52008FEC23 /* Products */; - ProjectRef = F983DFD41E696D52008FEC23 /* GeneralUtils.xcodeproj */; + ProductGroup = 660BB2253E0724743F7D90B1 /* Products */; + ProjectRef = 660BBECA0152D9F9EFAEE76C /* GeneralUtils.xcodeproj */; }, ); projectRoot = ""; @@ -472,11 +492,11 @@ /* End PBXProject section */ /* Begin PBXReferenceProxy section */ - F983DFD91E696D53008FEC23 /* GeneralUtils.framework */ = { + 660BB4D67F3203721378E5E3 /* GeneralUtils.framework */ = { isa = PBXReferenceProxy; fileType = wrapper.framework; path = GeneralUtils.framework; - remoteRef = F983DFD81E696D53008FEC23 /* PBXContainerItemProxy */; + remoteRef = 660BBAA989A4FF96F0ED0E24 /* PBXContainerItemProxy */; sourceTree = BUILT_PRODUCTS_DIR; }; /* End PBXReferenceProxy section */ @@ -498,6 +518,54 @@ }; /* End PBXResourcesBuildPhase section */ +/* Begin PBXShellScriptBuildPhase section */ + D05518C5A273FE90FC67BCCE /* [CP] Embed Pods Frameworks */ = { + isa = PBXShellScriptBuildPhase; + buildActionMask = 2147483647; + files = ( + ); + inputPaths = ( + ); + name = "[CP] Embed Pods Frameworks"; + outputPaths = ( + ); + runOnlyForDeploymentPostprocessing = 0; + shellPath = /bin/sh; + shellScript = "\"${SRCROOT}/Pods/Target Support Files/Pods-App/Pods-App-frameworks.sh\"\n"; + showEnvVarsInLog = 0; + }; + D3F185E28D16DC603C27EC2F /* [CP] Check Pods Manifest.lock */ = { + isa = PBXShellScriptBuildPhase; + buildActionMask = 2147483647; + files = ( + ); + inputPaths = ( + ); + name = "[CP] Check Pods Manifest.lock"; + outputPaths = ( + ); + runOnlyForDeploymentPostprocessing = 0; + shellPath = /bin/sh; + shellScript = "diff \"${PODS_ROOT}/../Podfile.lock\" \"${PODS_ROOT}/Manifest.lock\" > /dev/null\nif [ $? != 0 ] ; then\n # print error to STDERR\n echo \"error: The sandbox is not in sync with the Podfile.lock. Run 'pod install' or update your CocoaPods installation.\" >&2\n exit 1\nfi\n"; + showEnvVarsInLog = 0; + }; + DC704D4E2710E935A7EE93C8 /* [CP] Copy Pods Resources */ = { + isa = PBXShellScriptBuildPhase; + buildActionMask = 2147483647; + files = ( + ); + inputPaths = ( + ); + name = "[CP] Copy Pods Resources"; + outputPaths = ( + ); + runOnlyForDeploymentPostprocessing = 0; + shellPath = /bin/sh; + shellScript = "\"${SRCROOT}/Pods/Target Support Files/Pods-App/Pods-App-resources.sh\"\n"; + showEnvVarsInLog = 0; + }; +/* End PBXShellScriptBuildPhase section */ + /* Begin PBXSourcesBuildPhase section */ F9F6480C1E6105EA009CCEBD /* Sources */ = { isa = PBXSourcesBuildPhase; @@ -518,7 +586,7 @@ 660BBD91D7ED633F0D6C8F82 /* VCNhapTenCty.swift in Sources */, 660BB1BFD392263F36E00D87 /* VCNhapTenCtruong.swift in Sources */, 660BB1B30E2061006033A438 /* VCNhapMucChup.swift in Sources */, - 660BBCD1A02935C5843544B6 /* MucChup.swift in Sources */, + 660BBCD1A02935C5843544B6 /* ShootItem.swift in Sources */, 660BB1EB08BCA748E7C80012 /* CongTruong.swift in Sources */, 660BB033B71888619909D955 /* CellMucChupWithDelete.swift in Sources */, 660BBD73E0E1916B0402099D /* VCChonMucChup.swift in Sources */, @@ -558,21 +626,19 @@ 660BBA02DED5935CC2C25C50 /* VCAddPerson.swift in Sources */, 660BBADAAE9A0A55D305AFE6 /* VCPageImgs.swift in Sources */, 660BBE81FD9741C467B318B2 /* ImgObj.swift in Sources */, + 660BBB52CA48D9835B2B4FA7 /* Constants.swift in Sources */, + 660BBBC00FF5818CE1A37FF7 /* NetWorkUtils.swift in Sources */, + 660BBAFF5B4B94C3D5D97EB5 /* FileUpload.swift in Sources */, ); runOnlyForDeploymentPostprocessing = 0; }; /* End PBXSourcesBuildPhase section */ /* Begin PBXTargetDependency section */ - F983DFDC1E696F43008FEC23 /* PBXTargetDependency */ = { - isa = PBXTargetDependency; - name = GeneralUtils; - targetProxy = F983DFDB1E696F43008FEC23 /* PBXContainerItemProxy */; - }; - F983DFE01E696F4E008FEC23 /* PBXTargetDependency */ = { + F9D421DA1E6C029D00D4F936 /* PBXTargetDependency */ = { isa = PBXTargetDependency; name = GeneralUtils; - targetProxy = F983DFDF1E696F4E008FEC23 /* PBXContainerItemProxy */; + targetProxy = F9D421D91E6C029D00D4F936 /* PBXContainerItemProxy */; }; /* End PBXTargetDependency section */ @@ -683,6 +749,7 @@ }; F9F648231E6105EA009CCEBD /* Debug */ = { isa = XCBuildConfiguration; + baseConfigurationReference = 4E5AC66CBCD4532E16FE2D27 /* Pods-App.debug.xcconfig */; buildSettings = { ALWAYS_EMBED_SWIFT_STANDARD_LIBRARIES = YES; ASSETCATALOG_COMPILER_APPICON_NAME = AppIcon; @@ -702,6 +769,7 @@ }; F9F648241E6105EA009CCEBD /* Release */ = { isa = XCBuildConfiguration; + baseConfigurationReference = 98A3103DA59678FDFDBA9065 /* Pods-App.release.xcconfig */; buildSettings = { ALWAYS_EMBED_SWIFT_STANDARD_LIBRARIES = YES; ASSETCATALOG_COMPILER_APPICON_NAME = AppIcon; diff --git a/Morooka.xcodeproj/project.xcworkspace/xcuserdata/ptran.xcuserdatad/UserInterfaceState.xcuserstate b/Morooka.xcodeproj/project.xcworkspace/xcuserdata/ptran.xcuserdatad/UserInterfaceState.xcuserstate index b280338be56a1a1364c71033fbfa68ddb2cea063..81f5d1231bc02276d77e7e6ca16efc9f12598d60 100644 GIT binary patch literal 31059 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�eOKf7M2zqfut{e$(3>YuFNQU84X&idW;uh+j(|91V6`s4K{>(A7GTK{?d zrTQ!NKi2=IBXp#W)7k3mbu!%;ov$uH7p#lW$#t>1cwLq*PgkHT(v|9}b+tO3u0hwR zyGOS|w?}tScT)GB?gQN!-6y)wbQg5jbk}u1>weSyF%eFrCNdMpObnlxHnDEvf{9xv z?w$D3#8)Q1Hu2EJHz&R~@q>wHCVn#U(~0LN{-~$*oZeP%uXogs)O+iF^uBt3eY8GK zpQumPr|Q%71^Pn0T3@X1(hK^f`sMnS`qlb={W|@V`px>M_0Qv!tk(I3^H(4W$u z)_ONLRSkO@jx=0o_`2bnhVL4FZTPL> z4+Cf54YmengNwn<;BD|R_!;Dectet5oFT)IWym(D4D|-V@POeV!(zjuhGm8ohBbyw zhNleM49^*M7+x_PG`wjzY&dQ>WjJm4z;MxU)$q09JHwBLUktxD5{-6^PK_>&?u}y_ zy&L@+0~%u*6C0BoQya4yvl~^7xs8(>=Ql2I+}yaW@p*HtDgmMNuT84-uk~l+uKxoH CH6!Q% literal 40506 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 UL3s3UzZOLzORkMA`M)9a7myL+X#fBK diff --git a/Morooka.xcodeproj/xcuserdata/ptran.xcuserdatad/xcschemes/xcschememanagement.plist b/Morooka.xcodeproj/xcuserdata/ptran.xcuserdatad/xcschemes/xcschememanagement.plist index 92267b2..5860007 100644 --- a/Morooka.xcodeproj/xcuserdata/ptran.xcuserdatad/xcschemes/xcschememanagement.plist +++ b/Morooka.xcodeproj/xcuserdata/ptran.xcuserdatad/xcschemes/xcschememanagement.plist @@ -7,7 +7,7 @@ Moroka.xcscheme orderHint - 1 + 0 SuppressBuildableAutocreation diff --git a/Morooka.xcworkspace/contents.xcworkspacedata b/Morooka.xcworkspace/contents.xcworkspacedata new file mode 100644 index 0000000..5107ca4 --- /dev/null +++ b/Morooka.xcworkspace/contents.xcworkspacedata @@ -0,0 +1,10 @@ + + + + + + + diff --git a/Morooka.xcworkspace/xcshareddata/Morooka.xcscmblueprint b/Morooka.xcworkspace/xcshareddata/Morooka.xcscmblueprint new file mode 100644 index 0000000..f8fe324 --- /dev/null +++ b/Morooka.xcworkspace/xcshareddata/Morooka.xcscmblueprint @@ -0,0 +1,30 @@ +{ + "DVTSourceControlWorkspaceBlueprintPrimaryRemoteRepositoryKey" : "CCEA63EE63A95B3A503F055CB7EA22B5A3317247", + "DVTSourceControlWorkspaceBlueprintWorkingCopyRepositoryLocationsKey" : { + + }, + "DVTSourceControlWorkspaceBlueprintWorkingCopyStatesKey" : { + "7F44B3BDB580CA4541F3492AE6A41498050AC27C" : 9223372036854775807, + "CCEA63EE63A95B3A503F055CB7EA22B5A3317247" : 9223372036854775807 + }, + "DVTSourceControlWorkspaceBlueprintIdentifierKey" : "380A52FB-BC92-4F71-B53D-20956C1F5057", + "DVTSourceControlWorkspaceBlueprintWorkingCopyPathsKey" : { + "7F44B3BDB580CA4541F3492AE6A41498050AC27C" : "..\/Lib\/GeneralUtils", + "CCEA63EE63A95B3A503F055CB7EA22B5A3317247" : "Morooka1\/" + }, + "DVTSourceControlWorkspaceBlueprintNameKey" : "Morooka", + "DVTSourceControlWorkspaceBlueprintVersion" : 204, + "DVTSourceControlWorkspaceBlueprintRelativePathToProjectKey" : "Morooka.xcworkspace", + "DVTSourceControlWorkspaceBlueprintRemoteRepositoriesKey" : [ + { + "DVTSourceControlWorkspaceBlueprintRemoteRepositoryURLKey" : "https:\/\/github.com\/quanptit\/GeneralUtils.git", + "DVTSourceControlWorkspaceBlueprintRemoteRepositorySystemKey" : "com.apple.dt.Xcode.sourcecontrol.Git", + "DVTSourceControlWorkspaceBlueprintRemoteRepositoryIdentifierKey" : "7F44B3BDB580CA4541F3492AE6A41498050AC27C" + }, + { + "DVTSourceControlWorkspaceBlueprintRemoteRepositoryURLKey" : "http:\/\/timesfun.net\/quan\/morooka-ios.git", + "DVTSourceControlWorkspaceBlueprintRemoteRepositorySystemKey" : "com.apple.dt.Xcode.sourcecontrol.Git", + "DVTSourceControlWorkspaceBlueprintRemoteRepositoryIdentifierKey" : "CCEA63EE63A95B3A503F055CB7EA22B5A3317247" + } + ] +} \ No newline at end of file diff --git a/Morooka.xcworkspace/xcuserdata/ptran.xcuserdatad/UserInterfaceState.xcuserstate b/Morooka.xcworkspace/xcuserdata/ptran.xcuserdatad/UserInterfaceState.xcuserstate new file mode 100644 index 0000000000000000000000000000000000000000..a1c3ab771cac2c2ca11b46c0966c722943eea493 GIT binary patch literal 12286 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 literal 0 HcmV?d00001 diff --git a/Morooka.xcworkspace/xcuserdata/ptran.xcuserdatad/xcschemes/xcschememanagement.plist b/Morooka.xcworkspace/xcuserdata/ptran.xcuserdatad/xcschemes/xcschememanagement.plist new file mode 100644 index 0000000..ee3458d --- /dev/null +++ b/Morooka.xcworkspace/xcuserdata/ptran.xcuserdatad/xcschemes/xcschememanagement.plist @@ -0,0 +1,5 @@ + + + + + diff --git a/Podfile b/Podfile new file mode 100644 index 0000000..c7ca4c8 --- /dev/null +++ b/Podfile @@ -0,0 +1,10 @@ +# Uncomment the next line to define a global platform for your project +#platform :ios, '9.0' + +target 'App' do + # Comment the next line if you're not using Swift and don't want to use dynamic frameworks + use_frameworks! + + + pod 'Alamofire' +end diff --git a/Podfile.lock b/Podfile.lock new file mode 100644 index 0000000..a2c0289 --- /dev/null +++ b/Podfile.lock @@ -0,0 +1,12 @@ +PODS: + - Alamofire (4.3.0) + +DEPENDENCIES: + - Alamofire + +SPEC CHECKSUMS: + Alamofire: 856a113053a7bc9cbe5d6367a555d773fc5cfef7 + +PODFILE CHECKSUM: dc296b3fd9b6b081ed51a782cf5b4fec2b21bb1c + +COCOAPODS: 1.2.0.beta.3 diff --git a/Pods/Alamofire/LICENSE b/Pods/Alamofire/LICENSE new file mode 100644 index 0000000..4cfbf72 --- /dev/null +++ b/Pods/Alamofire/LICENSE @@ -0,0 +1,19 @@ +Copyright (c) 2014-2016 Alamofire Software Foundation (http://alamofire.org/) + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in +all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN +THE SOFTWARE. diff --git a/Pods/Alamofire/README.md b/Pods/Alamofire/README.md new file mode 100644 index 0000000..9526a9a --- /dev/null +++ b/Pods/Alamofire/README.md @@ -0,0 +1,1764 @@ +![Alamofire: Elegant Networking in Swift](https://raw.githubusercontent.com/Alamofire/Alamofire/assets/alamofire.png) + +[![Build Status](https://travis-ci.org/Alamofire/Alamofire.svg?branch=master)](https://travis-ci.org/Alamofire/Alamofire) +[![CocoaPods Compatible](https://img.shields.io/cocoapods/v/Alamofire.svg)](https://img.shields.io/cocoapods/v/Alamofire.svg) +[![Carthage Compatible](https://img.shields.io/badge/Carthage-compatible-4BC51D.svg?style=flat)](https://github.com/Carthage/Carthage) +[![Platform](https://img.shields.io/cocoapods/p/Alamofire.svg?style=flat)](http://cocoadocs.org/docsets/Alamofire) +[![Twitter](https://img.shields.io/badge/twitter-@AlamofireSF-blue.svg?style=flat)](http://twitter.com/AlamofireSF) + +Alamofire is an HTTP networking library written in Swift. + +- [Features](#features) +- [Component Libraries](#component-libraries) +- [Requirements](#requirements) +- [Migration Guides](#migration-guides) +- [Communication](#communication) +- [Installation](#installation) +- [Usage](#usage) + - **Intro -** [Making a Request](#making-a-request), [Response Handling](#response-handling), [Response Validation](#response-validation), [Response Caching](#response-caching) + - **HTTP -** [HTTP Methods](#http-methods), [Parameter Encoding](#parameter-encoding), [HTTP Headers](#http-headers), [Authentication](#authentication) + - **Large Data -** [Downloading Data to a File](#downloading-data-to-a-file), [Uploading Data to a Server](#uploading-data-to-a-server) + - **Tools -** [Statistical Metrics](#statistical-metrics), [cURL Command Output](#curl-command-output) +- [Advanced Usage](#advanced-usage) + - **URL Session -** [Session Manager](#session-manager), [Session Delegate](#session-delegate), [Request](#request) + - **Routing -** [Routing Requests](#routing-requests), [Adapting and Retrying Requests](#adapting-and-retrying-requests) + - **Model Objects -** [Custom Response Serialization](#custom-response-serialization) + - **Connection -** [Security](#security), [Network Reachability](#network-reachability) +- [Open Radars](#open-radars) +- [FAQ](#faq) +- [Credits](#credits) +- [Donations](#donations) +- [License](#license) + +## Features + +- [x] Chainable Request / Response Methods +- [x] URL / JSON / plist Parameter Encoding +- [x] Upload File / Data / Stream / MultipartFormData +- [x] Download File using Request or Resume Data +- [x] Authentication with URLCredential +- [x] HTTP Response Validation +- [x] Upload and Download Progress Closures with Progress +- [x] cURL Command Output +- [x] Dynamically Adapt and Retry Requests +- [x] TLS Certificate and Public Key Pinning +- [x] Network Reachability +- [x] Comprehensive Unit and Integration Test Coverage +- [x] [Complete Documentation](http://cocoadocs.org/docsets/Alamofire) + +## Component Libraries + +In order to keep Alamofire focused specifically on core networking implementations, additional component libraries have been created by the [Alamofire Software Foundation](https://github.com/Alamofire/Foundation) to bring additional functionality to the Alamofire ecosystem. + +- [AlamofireImage](https://github.com/Alamofire/AlamofireImage) - An image library including image response serializers, `UIImage` and `UIImageView` extensions, custom image filters, an auto-purging in-memory cache and a priority-based image downloading system. +- [AlamofireNetworkActivityIndicator](https://github.com/Alamofire/AlamofireNetworkActivityIndicator) - Controls the visibility of the network activity indicator on iOS using Alamofire. It contains configurable delay timers to help mitigate flicker and can support `URLSession` instances not managed by Alamofire. + +## Requirements + +- iOS 8.0+ / macOS 10.10+ / tvOS 9.0+ / watchOS 2.0+ +- Xcode 8.1+ +- Swift 3.0+ + +## Migration Guides + +- [Alamofire 4.0 Migration Guide](https://github.com/Alamofire/Alamofire/blob/master/Documentation/Alamofire%204.0%20Migration%20Guide.md) +- [Alamofire 3.0 Migration Guide](https://github.com/Alamofire/Alamofire/blob/master/Documentation/Alamofire%203.0%20Migration%20Guide.md) +- [Alamofire 2.0 Migration Guide](https://github.com/Alamofire/Alamofire/blob/master/Documentation/Alamofire%202.0%20Migration%20Guide.md) + +## Communication + +- If you **need help**, use [Stack Overflow](http://stackoverflow.com/questions/tagged/alamofire). (Tag 'alamofire') +- If you'd like to **ask a general question**, use [Stack Overflow](http://stackoverflow.com/questions/tagged/alamofire). +- If you **found a bug**, open an issue. +- If you **have a feature request**, open an issue. +- If you **want to contribute**, submit a pull request. + +## Installation + +### CocoaPods + +[CocoaPods](http://cocoapods.org) is a dependency manager for Cocoa projects. You can install it with the following command: + +```bash +$ gem install cocoapods +``` + +> CocoaPods 1.1.0+ is required to build Alamofire 4.0.0+. + +To integrate Alamofire into your Xcode project using CocoaPods, specify it in your `Podfile`: + +```ruby +source 'https://github.com/CocoaPods/Specs.git' +platform :ios, '10.0' +use_frameworks! + +target '' do + pod 'Alamofire', '~> 4.3' +end +``` + +Then, run the following command: + +```bash +$ pod install +``` + +### Carthage + +[Carthage](https://github.com/Carthage/Carthage) is a decentralized dependency manager that builds your dependencies and provides you with binary frameworks. + +You can install Carthage with [Homebrew](http://brew.sh/) using the following command: + +```bash +$ brew update +$ brew install carthage +``` + +To integrate Alamofire into your Xcode project using Carthage, specify it in your `Cartfile`: + +```ogdl +github "Alamofire/Alamofire" ~> 4.3 +``` + +Run `carthage update` to build the framework and drag the built `Alamofire.framework` into your Xcode project. + +### Swift Pacakge Manager + +The [Swift Pacakage Manager](https://swift.org/package-manager/) is a tool for automating the distribution of Swift code and is integrated into the `swift` compiler. It is in early development, but Alamofire does support its use on supported platforms. + +Once you have your Swift package set up, adding Alamofire as a dependency is as easy as adding it to the `dependencies` value of your `Package.swift`. + +```swift +dependencies: [ + .Package(url: "https://github.com/Alamofire/Alamofire.git", majorVersion: 4) +] +``` + +### Manually + +If you prefer not to use either of the aforementioned dependency managers, you can integrate Alamofire into your project manually. + +#### Embedded Framework + +- Open up Terminal, `cd` into your top-level project directory, and run the following command "if" your project is not initialized as a git repository: + + ```bash +$ git init +``` + +- Add Alamofire as a git [submodule](http://git-scm.com/docs/git-submodule) by running the following command: + + ```bash +$ git submodule add https://github.com/Alamofire/Alamofire.git +``` + +- Open the new `Alamofire` folder, and drag the `Alamofire.xcodeproj` into the Project Navigator of your application's Xcode project. + + > It should appear nested underneath your application's blue project icon. Whether it is above or below all the other Xcode groups does not matter. + +- Select the `Alamofire.xcodeproj` in the Project Navigator and verify the deployment target matches that of your application target. +- Next, select your application project in the Project Navigator (blue project icon) to navigate to the target configuration window and select the application target under the "Targets" heading in the sidebar. +- In the tab bar at the top of that window, open the "General" panel. +- Click on the `+` button under the "Embedded Binaries" section. +- You will see two different `Alamofire.xcodeproj` folders each with two different versions of the `Alamofire.framework` nested inside a `Products` folder. + + > It does not matter which `Products` folder you choose from, but it does matter whether you choose the top or bottom `Alamofire.framework`. + +- Select the top `Alamofire.framework` for iOS and the bottom one for OS X. + + > You can verify which one you selected by inspecting the build log for your project. The build target for `Alamofire` will be listed as either `Alamofire iOS`, `Alamofire macOS`, `Alamofire tvOS` or `Alamofire watchOS`. + +- And that's it! + + > The `Alamofire.framework` is automagically added as a target dependency, linked framework and embedded framework in a copy files build phase which is all you need to build on the simulator and a device. + +--- + +## Usage + +### Making a Request + +```swift +import Alamofire + +Alamofire.request("https://httpbin.org/get") +``` + +### Response Handling + +Handling the `Response` of a `Request` made in Alamofire involves chaining a response handler onto the `Request`. + +```swift +Alamofire.request("https://httpbin.org/get").responseJSON { response in + print(response.request) // original URL request + print(response.response) // HTTP URL response + print(response.data) // server data + print(response.result) // result of response serialization + + if let JSON = response.result.value { + print("JSON: \(JSON)") + } +} +``` + +In the above example, the `responseJSON` handler is appended to the `Request` to be executed once the `Request` is complete. Rather than blocking execution to wait for a response from the server, a [callback](http://en.wikipedia.org/wiki/Callback_%28computer_programming%29) in the form of a closure is specified to handle the response once it's received. The result of a request is only available inside the scope of a response closure. Any execution contingent on the response or data received from the server must be done within a response closure. + +> Networking in Alamofire is done _asynchronously_. Asynchronous programming may be a source of frustration to programmers unfamiliar with the concept, but there are [very good reasons](https://developer.apple.com/library/ios/qa/qa1693/_index.html) for doing it this way. + +Alamofire contains five different response handlers by default including: + +```swift +// Response Handler - Unserialized Response +func response( + queue: DispatchQueue?, + completionHandler: @escaping (DefaultDataResponse) -> Void) + -> Self + +// Response Data Handler - Serialized into Data +func responseData( + queue: DispatchQueue?, + completionHandler: @escaping (DataResponse) -> Void) + -> Self + +// Response String Handler - Serialized into String +func responseString( + queue: DispatchQueue?, + encoding: String.Encoding?, + completionHandler: @escaping (DataResponse) -> Void) + -> Self + +// Response JSON Handler - Serialized into Any +func responseJSON( + queue: DispatchQueue?, + completionHandler: @escaping (DataResponse) -> Void) + -> Self + +// Response PropertyList (plist) Handler - Serialized into Any +func responsePropertyList( + queue: DispatchQueue?, + completionHandler: @escaping (DataResponse) -> Void)) + -> Self +``` + +None of the response handlers perform any validation of the `HTTPURLResponse` it gets back from the server. + +> For example, response status codes in the `400..<499` and `500..<599` ranges do NOT automatically trigger an `Error`. Alamofire uses [Response Validation](#response-validation) method chaining to achieve this. + +#### Response Handler + +The `response` handler does NOT evaluate any of the response data. It merely forwards on all information directly from the URL session delegate. It is the Alamofire equivalent of using `cURL` to execute a `Request`. + +```swift +Alamofire.request("https://httpbin.org/get").response { response in + print("Request: \(response.request)") + print("Response: \(response.response)") + print("Error: \(response.error)") + + if let data = response.data, let utf8Text = String(data: data, encoding: .utf8) { + print("Data: \(utf8Text)") + } +} +``` + +> We strongly encourage you to leverage the other response serializers taking advantage of `Response` and `Result` types. + +#### Response Data Handler + +The `responseData` handler uses the `responseDataSerializer` (the object that serializes the server data into some other type) to extract the `Data` returned by the server. If no errors occur and `Data` is returned, the response `Result` will be a `.success` and the `value` will be of type `Data`. + +```swift +Alamofire.request("https://httpbin.org/get").responseData { response in + debugPrint("All Response Info: \(response)") + + if let data = response.result.value, let utf8Text = String(data: data, encoding: .utf8) { + print("Data: \(utf8Text)") + } +} +``` + +#### Response String Handler + +The `responseString` handler uses the `responseStringSerializer` to convert the `Data` returned by the server into a `String` with the specified encoding. If no errors occur and the server data is successfully serialized into a `String`, the response `Result` will be a `.success` and the `value` will be of type `String`. + +```swift +Alamofire.request("https://httpbin.org/get").responseString { response in + print("Success: \(response.result.isSuccess)") + print("Response String: \(response.result.value)") +} +``` + +> If no encoding is specified, Alamofire will use the text encoding specified in the `HTTPURLResponse` from the server. If the text encoding cannot be determined by the server response, it defaults to `.isoLatin1`. + +#### Response JSON Handler + +The `responseJSON` handler uses the `responseJSONSerializer` to convert the `Data` returned by the server into an `Any` type using the specified `JSONSerialization.ReadingOptions`. If no errors occur and the server data is successfully serialized into a JSON object, the response `Result` will be a `.success` and the `value` will be of type `Any`. + +```swift +Alamofire.request("https://httpbin.org/get").responseJSON { response in + debugPrint(response) + + if let json = response.result.value { + print("JSON: \(json)") + } +} +``` + +> All JSON serialization is handled by the `JSONSerialization` API in the `Foundation` framework. + +#### Chained Response Handlers + +Response handlers can even be chained: + +```swift +Alamofire.request("https://httpbin.org/get") + .responseString { response in + print("Response String: \(response.result.value)") + } + .responseJSON { response in + print("Response JSON: \(response.result.value)") + } +``` + +> It is important to note that using multiple response handlers on the same `Request` requires the server data to be serialized multiple times. Once for each response handler. + +#### Response Handler Queue + +Response handlers by default are executed on the main dispatch queue. However, a custom dispatch queue can be provided instead. + +```swift +let utilityQueue = DispatchQueue.global(qos: .utility) + +Alamofire.request("https://httpbin.org/get").responseJSON(queue: utilityQueue) { response in + print("Executing response handler on utility queue") +} +``` + +### Response Validation + +By default, Alamofire treats any completed request to be successful, regardless of the content of the response. Calling `validate` before a response handler causes an error to be generated if the response had an unacceptable status code or MIME type. + +#### Manual Validation + +```swift +Alamofire.request("https://httpbin.org/get") + .validate(statusCode: 200..<300) + .validate(contentType: ["application/json"]) + .responseData { response in + switch response.result { + case .success: + print("Validation Successful") + case .failure(let error): + print(error) + } + } +``` + +#### Automatic Validation + +Automatically validates status code within `200...299` range, and that the `Content-Type` header of the response matches the `Accept` header of the request, if one is provided. + +```swift +Alamofire.request("https://httpbin.org/get").validate().responseJSON { response in + switch response.result { + case .success: + print("Validation Successful") + case .failure(let error): + print(error) + } +} +``` + +### Response Caching + +Response Caching is handled on the system framework level by [`URLCache`](https://developer.apple.com/reference/foundation/urlcache). It provides a composite in-memory and on-disk cache and lets you manipulate the sizes of both the in-memory and on-disk portions. + +> By default, Alamofire leverages the shared `URLCache`. In order to customize it, see the [Session Manager Configurations](#session-manager) section. + +### HTTP Methods + +The `HTTPMethod` enumeration lists the HTTP methods defined in [RFC 7231 §4.3](http://tools.ietf.org/html/rfc7231#section-4.3): + +```swift +public enum HTTPMethod: String { + case options = "OPTIONS" + case get = "GET" + case head = "HEAD" + case post = "POST" + case put = "PUT" + case patch = "PATCH" + case delete = "DELETE" + case trace = "TRACE" + case connect = "CONNECT" +} +``` + +These values can be passed as the `method` argument to the `Alamofire.request` API: + +```swift +Alamofire.request("https://httpbin.org/get") // method defaults to `.get` + +Alamofire.request("https://httpbin.org/post", method: .post) +Alamofire.request("https://httpbin.org/put", method: .put) +Alamofire.request("https://httpbin.org/delete", method: .delete) +``` + +> The `Alamofire.request` method parameter defaults to `.get`. + +### Parameter Encoding + +Alamofire supports three types of parameter encoding including: `URL`, `JSON` and `PropertyList`. It can also support any custom encoding that conforms to the `ParameterEncoding` protocol. + +#### URL Encoding + +The `URLEncoding` type creates a url-encoded query string to be set as or appended to any existing URL query string or set as the HTTP body of the URL request. Whether the query string is set or appended to any existing URL query string or set as the HTTP body depends on the `Destination` of the encoding. The `Destination` enumeration has three cases: + +- `.methodDependent` - Applies encoded query string result to existing query string for `GET`, `HEAD` and `DELETE` requests and sets as the HTTP body for requests with any other HTTP method. +- `.queryString` - Sets or appends encoded query string result to existing query string. +- `.httpBody` - Sets encoded query string result as the HTTP body of the URL request. + +The `Content-Type` HTTP header field of an encoded request with HTTP body is set to `application/x-www-form-urlencoded; charset=utf-8`. Since there is no published specification for how to encode collection types, the convention of appending `[]` to the key for array values (`foo[]=1&foo[]=2`), and appending the key surrounded by square brackets for nested dictionary values (`foo[bar]=baz`). + +##### GET Request With URL-Encoded Parameters + +```swift +let parameters: Parameters = ["foo": "bar"] + +// All three of these calls are equivalent +Alamofire.request("https://httpbin.org/get", parameters: parameters) // encoding defaults to `URLEncoding.default` +Alamofire.request("https://httpbin.org/get", parameters: parameters, encoding: URLEncoding.default) +Alamofire.request("https://httpbin.org/get", parameters: parameters, encoding: URLEncoding(destination: .methodDependent)) + +// https://httpbin.org/get?foo=bar +``` + +##### POST Request With URL-Encoded Parameters + +```swift +let parameters: Parameters = [ + "foo": "bar", + "baz": ["a", 1], + "qux": [ + "x": 1, + "y": 2, + "z": 3 + ] +] + +// All three of these calls are equivalent +Alamofire.request("https://httpbin.org/post", parameters: parameters) +Alamofire.request("https://httpbin.org/post", parameters: parameters, encoding: URLEncoding.default) +Alamofire.request("https://httpbin.org/post", parameters: parameters, encoding: URLEncoding.httpBody) + +// HTTP body: foo=bar&baz[]=a&baz[]=1&qux[x]=1&qux[y]=2&qux[z]=3 +``` + +#### JSON Encoding + +The `JSONEncoding` type creates a JSON representation of the parameters object, which is set as the HTTP body of the request. The `Content-Type` HTTP header field of an encoded request is set to `application/json`. + +##### POST Request with JSON-Encoded Parameters + +```swift +let parameters: Parameters = [ + "foo": [1,2,3], + "bar": [ + "baz": "qux" + ] +] + +// Both calls are equivalent +Alamofire.request("https://httpbin.org/post", method: .post, parameters: parameters, encoding: JSONEncoding.default) +Alamofire.request("https://httpbin.org/post", method: .post, parameters: parameters, encoding: JSONEncoding(options: [])) + +// HTTP body: {"foo": [1, 2, 3], "bar": {"baz": "qux"}} +``` + +#### Property List Encoding + +The `PropertyListEncoding` uses `PropertyListSerialization` to create a plist representation of the parameters object, according to the associated format and write options values, which is set as the body of the request. The `Content-Type` HTTP header field of an encoded request is set to `application/x-plist`. + +#### Custom Encoding + +In the event that the provided `ParameterEncoding` types do not meet your needs, you can create your own custom encoding. Here's a quick example of how you could build a custom `JSONStringArrayEncoding` type to encode a JSON string array onto a `Request`. + +```swift +struct JSONStringArrayEncoding: ParameterEncoding { + private let array: [String] + + init(array: [String]) { + self.array = array + } + + func encode(_ urlRequest: URLRequestConvertible, with parameters: Parameters?) throws -> URLRequest { + var urlRequest = urlRequest.urlRequest + + let data = try JSONSerialization.data(withJSONObject: array, options: []) + + if urlRequest.value(forHTTPHeaderField: "Content-Type") == nil { + urlRequest.setValue("application/json", forHTTPHeaderField: "Content-Type") + } + + urlRequest.httpBody = data + + return urlRequest + } +} +``` + +#### Manual Parameter Encoding of a URLRequest + +The `ParameterEncoding` APIs can be used outside of making network requests. + +```swift +let url = URL(string: "https://httpbin.org/get")! +var urlRequest = URLRequest(url: url) + +let parameters: Parameters = ["foo": "bar"] +let encodedURLRequest = try URLEncoding.queryString.encode(urlRequest, with: parameters) +``` + +### HTTP Headers + +Adding a custom HTTP header to a `Request` is supported directly in the global `request` method. This makes it easy to attach HTTP headers to a `Request` that can be constantly changing. + +```swift +let headers: HTTPHeaders = [ + "Authorization": "Basic QWxhZGRpbjpvcGVuIHNlc2FtZQ==", + "Accept": "application/json" +] + +Alamofire.request("https://httpbin.org/headers", headers: headers).responseJSON { response in + debugPrint(response) +} +``` + +> For HTTP headers that do not change, it is recommended to set them on the `URLSessionConfiguration` so they are automatically applied to any `URLSessionTask` created by the underlying `URLSession`. For more information, see the [Session Manager Configurations](#session-manager) section. + +The default Alamofire `SessionManager` provides a default set of headers for every `Request`. These include: + +- `Accept-Encoding`, which defaults to `gzip;q=1.0, compress;q=0.5`, per [RFC 7230 §4.2.3](https://tools.ietf.org/html/rfc7230#section-4.2.3). +- `Accept-Language`, which defaults to up to the top 6 preferred languages on the system, formatted like `en;q=1.0`, per [RFC 7231 §5.3.5](https://tools.ietf.org/html/rfc7231#section-5.3.5). +- `User-Agent`, which contains versioning information about the current app. For example: `iOS Example/1.0 (com.alamofire.iOS-Example; build:1; iOS 10.0.0) Alamofire/4.0.0`, per [RFC 7231 §5.5.3](https://tools.ietf.org/html/rfc7231#section-5.5.3). + +If you need to customize these headers, a custom `URLSessionConfiguration` should be created, the `defaultHTTPHeaders` property updated and the configuration applied to a new `SessionManager` instance. + +### Authentication + +Authentication is handled on the system framework level by [`URLCredential`](https://developer.apple.com/reference/foundation/nsurlcredential) and [`URLAuthenticationChallenge`](https://developer.apple.com/reference/foundation/urlauthenticationchallenge). + +**Supported Authentication Schemes** + +- [HTTP Basic](http://en.wikipedia.org/wiki/Basic_access_authentication) +- [HTTP Digest](http://en.wikipedia.org/wiki/Digest_access_authentication) +- [Kerberos](http://en.wikipedia.org/wiki/Kerberos_%28protocol%29) +- [NTLM](http://en.wikipedia.org/wiki/NT_LAN_Manager) + +#### HTTP Basic Authentication + +The `authenticate` method on a `Request` will automatically provide a `URLCredential` to a `URLAuthenticationChallenge` when appropriate: + +```swift +let user = "user" +let password = "password" + +Alamofire.request("https://httpbin.org/basic-auth/\(user)/\(password)") + .authenticate(user: user, password: password) + .responseJSON { response in + debugPrint(response) + } +``` + +Depending upon your server implementation, an `Authorization` header may also be appropriate: + +```swift +let user = "user" +let password = "password" + +var headers: HTTPHeaders = [:] + +if let authorizationHeader = Request.authorizationHeader(user: user, password: password) { + headers[authorizationHeader.key] = authorizationHeader.value +} + +Alamofire.request("https://httpbin.org/basic-auth/user/password", headers: headers) + .responseJSON { response in + debugPrint(response) + } +``` + +#### Authentication with URLCredential + +```swift +let user = "user" +let password = "password" + +let credential = URLCredential(user: user, password: password, persistence: .forSession) + +Alamofire.request("https://httpbin.org/basic-auth/\(user)/\(password)") + .authenticate(usingCredential: credential) + .responseJSON { response in + debugPrint(response) + } +``` + +> It is important to note that when using a `URLCredential` for authentication, the underlying `URLSession` will actually end up making two requests if a challenge is issued by the server. The first request will not include the credential which "may" trigger a challenge from the server. The challenge is then received by Alamofire, the credential is appended and the request is retried by the underlying `URLSession`. + +### Downloading Data to a File + +Requests made in Alamofire that fetch data from a server can download the data in-memory or on-disk. The `Alamofire.request` APIs used in all the examples so far always downloads the server data in-memory. This is great for smaller payloads because it's more efficient, but really bad for larger payloads because the download could run your entire application out-of-memory. Because of this, you can also use the `Alamofire.download` APIs to download the server data to a temporary file on-disk. + +> This will only work on `macOS` as is. Other platforms don't allow access to the filesystem outside of your app's sandbox. To download files on other platforms, see the [Download File Destination](#download-file-destination) section. + +```swift +Alamofire.download("https://httpbin.org/image/png").responseData { response in + if let data = response.result.value { + let image = UIImage(data: data) + } +} +``` + +> The `Alamofire.download` APIs should also be used if you need to download data while your app is in the background. For more information, please see the [Session Manager Configurations](#session-manager) section. + +#### Download File Destination + +You can also provide a `DownloadFileDestination` closure to move the file from the temporary directory to a final destination. Before the temporary file is actually moved to the `destinationURL`, the `DownloadOptions` specified in the closure will be executed. The two currently supported `DownloadOptions` are: + +- `.createIntermediateDirectories` - Creates intermediate directories for the destination URL if specified. +- `.removePreviousFile` - Removes a previous file from the destination URL if specified. + +```swift +let destination: DownloadRequest.DownloadFileDestination = { _, _ in + let documentsURL = FileManager.default.urls(for: .documentDirectory, in: .userDomainMask)[0] + let fileURL = documentsURL.appendPathComponent("pig.png") + + return (fileURL, [.removePreviousFile, .createIntermediateDirectories]) +} + +Alamofire.download(urlString, to: destination).response { response in + print(response) + + if response.error == nil, let imagePath = response.destinationURL?.path { + let image = UIImage(contentsOfFile: imagePath) + } +} +``` + +You can also use the suggested download destination API. + +```swift +let destination = DownloadRequest.suggestedDownloadDestination(directory: .documentDirectory) +Alamofire.download("https://httpbin.org/image/png", to: destination) +``` + +#### Download Progress + +Many times it can be helpful to report download progress to the user. Any `DownloadRequest` can report download progress using the `downloadProgress` API. + +```swift +Alamofire.download("https://httpbin.org/image/png") + .downloadProgress { progress in + print("Download Progress: \(progress.fractionCompleted)") + } + .responseData { response in + if let data = response.result.value { + let image = UIImage(data: data) + } + } +``` + +The `downloadProgress` API also takes a `queue` parameter which defines which `DispatchQueue` the download progress closure should be called on. + +```swift +let utilityQueue = DispatchQueue.global(qos: .utility) + +Alamofire.download("https://httpbin.org/image/png") + .downloadProgress(queue: utilityQueue) { progress in + print("Download Progress: \(progress.fractionCompleted)") + } + .responseData { response in + if let data = response.result.value { + let image = UIImage(data: data) + } + } +``` + +#### Resuming a Download + +If a `DownloadRequest` is cancelled or interrupted, the underlying URL session may generate resume data for the active `DownloadRequest`. If this happens, the resume data can be re-used to restart the `DownloadRequest` where it left off. The resume data can be accessed through the download response, then reused when trying to restart the request. + +> **IMPORTANT:** On the latest release of all the Apple platforms (iOS 10, macOS 10.12, tvOS 10, watchOS 3), `resumeData` is broken on background URL session configurations. There's an underlying bug in the `resumeData` generation logic where the data is written incorrectly and will always fail to resume the download. For more information about the bug and possible workarounds, please see this Stack Overflow [post](http://stackoverflow.com/a/39347461/1342462). + +```swift +class ImageRequestor { + private var resumeData: Data? + private var image: UIImage? + + func fetchImage(completion: (UIImage?) -> Void) { + guard image == nil else { completion(image) ; return } + + let destination: DownloadRequest.DownloadFileDestination = { _, _ in + let documentsURL = FileManager.default.urls(for: .documentDirectory, in: .userDomainMask)[0] + let fileURL = documentsURL.appendPathComponent("pig.png") + + return (fileURL, [.removePreviousFile, .createIntermediateDirectories]) + } + + let request: DownloadRequest + + if let resumeData = resumeData { + request = Alamofire.download(resumingWith: resumeData) + } else { + request = Alamofire.download("https://httpbin.org/image/png") + } + + request.responseData { response in + switch response.result { + case .success(let data): + self.image = UIImage(data: data) + case .failure: + self.resumeData = response.resumeData + } + } + } +} +``` + +### Uploading Data to a Server + +When sending relatively small amounts of data to a server using JSON or URL encoded parameters, the `Alamofire.request` APIs are usually sufficient. If you need to send much larger amounts of data from a file URL or an `InputStream`, then the `Alamofire.upload` APIs are what you want to use. + +> The `Alamofire.upload` APIs should also be used if you need to upload data while your app is in the background. For more information, please see the [Session Manager Configurations](#session-manager) section. + +#### Uploading Data + +```swift +let imageData = UIPNGRepresentation(image)! + +Alamofire.upload(imageData, to: "https://httpbin.org/post").responseJSON { response in + debugPrint(response) +} +``` + +#### Uploading a File + +```swift +let fileURL = Bundle.main.url(forResource: "video", withExtension: "mov") + +Alamofire.upload(fileURL, to: "https://httpbin.org/post").responseJSON { response in + debugPrint(response) +} +``` + +#### Uploading Multipart Form Data + +```swift +Alamofire.upload( + multipartFormData: { multipartFormData in + multipartFormData.append(unicornImageURL, withName: "unicorn") + multipartFormData.append(rainbowImageURL, withName: "rainbow") + }, + to: "https://httpbin.org/post", + encodingCompletion: { encodingResult in + switch encodingResult { + case .success(let upload, _, _): + upload.responseJSON { response in + debugPrint(response) + } + case .failure(let encodingError): + print(encodingError) + } + } +) +``` + +#### Upload Progress + +While your user is waiting for their upload to complete, sometimes it can be handy to show the progress of the upload to the user. Any `UploadRequest` can report both upload progress and download progress of the response data using the `uploadProgress` and `downloadProgress` APIs. + +```swift +let fileURL = Bundle.main.url(forResource: "video", withExtension: "mov") + +Alamofire.upload(fileURL, to: "https://httpbin.org/post") + .uploadProgress { progress in // main queue by default + print("Upload Progress: \(progress.fractionCompleted)") + } + .downloadProgress { progress in // main queue by default + print("Download Progress: \(progress.fractionCompleted)") + } + .responseJSON { response in + debugPrint(response) + } +``` + +### Statistical Metrics + +#### Timeline + +Alamofire collects timings throughout the lifecycle of a `Request` and creates a `Timeline` object exposed as a property on all response types. + +```swift +Alamofire.request("https://httpbin.org/get").responseJSON { response in + print(response.timeline) +} +``` + +The above reports the following `Timeline` info: + +- `Latency`: 0.428 seconds +- `Request Duration`: 0.428 seconds +- `Serialization Duration`: 0.001 seconds +- `Total Duration`: 0.429 seconds + +#### URL Session Task Metrics + +In iOS and tvOS 10 and macOS 10.12, Apple introduced the new [URLSessionTaskMetrics](https://developer.apple.com/reference/foundation/urlsessiontaskmetrics) APIs. The task metrics encapsulate some fantastic statistical information about the request and response execution. The API is very similar to the `Timeline`, but provides many more statistics that Alamofire doesn't have access to compute. The metrics can be accessed through any response type. + +```swift +Alamofire.request("https://httpbin.org/get").responseJSON { response in + print(response.metrics) +} +``` + +It's important to note that these APIs are only available on iOS and tvOS 10 and macOS 10.12. Therefore, depending on your deployment target, you may need to use these inside availability checks: + +```swift +Alamofire.request("https://httpbin.org/get").responseJSON { response in + if #available(iOS 10.0. *) { + print(response.metrics) + } +} +``` + +### cURL Command Output + +Debugging platform issues can be frustrating. Thankfully, Alamofire `Request` objects conform to both the `CustomStringConvertible` and `CustomDebugStringConvertible` protocols to provide some VERY helpful debugging tools. + +#### CustomStringConvertible + +```swift +let request = Alamofire.request("https://httpbin.org/ip") + +print(request) +// GET https://httpbin.org/ip (200) +``` + +#### CustomDebugStringConvertible + +```swift +let request = Alamofire.request("https://httpbin.org/get", parameters: ["foo": "bar"]) +debugPrint(request) +``` + +Outputs: + +```bash +$ curl -i \ + -H "User-Agent: Alamofire/4.0.0" \ + -H "Accept-Encoding: gzip;q=1.0, compress;q=0.5" \ + -H "Accept-Language: en;q=1.0,fr;q=0.9,de;q=0.8,zh-Hans;q=0.7,zh-Hant;q=0.6,ja;q=0.5" \ + "https://httpbin.org/get?foo=bar" +``` + +--- + +## Advanced Usage + +Alamofire is built on `URLSession` and the Foundation URL Loading System. To make the most of this framework, it is recommended that you be familiar with the concepts and capabilities of the underlying networking stack. + +**Recommended Reading** + +- [URL Loading System Programming Guide](https://developer.apple.com/library/mac/documentation/Cocoa/Conceptual/URLLoadingSystem/URLLoadingSystem.html) +- [URLSession Class Reference](https://developer.apple.com/reference/foundation/nsurlsession) +- [URLCache Class Reference](https://developer.apple.com/reference/foundation/urlcache) +- [URLAuthenticationChallenge Class Reference](https://developer.apple.com/reference/foundation/urlauthenticationchallenge) + +### Session Manager + +Top-level convenience methods like `Alamofire.request` use a default instance of `Alamofire.SessionManager`, which is configured with the default `URLSessionConfiguration`. + +As such, the following two statements are equivalent: + +```swift +Alamofire.request("https://httpbin.org/get") +``` + +```swift +let sessionManager = Alamofire.SessionManager.default +sessionManager.request("https://httpbin.org/get") +``` + +Applications can create session managers for background and ephemeral sessions, as well as new managers that customize the default session configuration, such as for default headers (`httpAdditionalHeaders`) or timeout interval (`timeoutIntervalForRequest`). + +#### Creating a Session Manager with Default Configuration + +```swift +let configuration = URLSessionConfiguration.default +let sessionManager = Alamofire.SessionManager(configuration: configuration) +``` + +#### Creating a Session Manager with Background Configuration + +```swift +let configuration = URLSessionConfiguration.background(withIdentifier: "com.example.app.background") +let sessionManager = Alamofire.SessionManager(configuration: configuration) +``` + +#### Creating a Session Manager with Ephemeral Configuration + +```swift +let configuration = URLSessionConfiguration.ephemeral +let sessionManager = Alamofire.SessionManager(configuration: configuration) +``` + +#### Modifying the Session Configuration + +```swift +var defaultHeaders = Alamofire.SessionManager.default.defaultHTTPHeaders +defaultHeaders["DNT"] = "1 (Do Not Track Enabled)" + +let configuration = URLSessionConfiguration.default +configuration.httpAdditionalHeaders = defaultHeaders + +let sessionManager = Alamofire.SessionManager(configuration: configuration) +``` + +> This is **not** recommended for `Authorization` or `Content-Type` headers. Instead, use the `headers` parameter in the top-level `Alamofire.request` APIs, `URLRequestConvertible` and `ParameterEncoding`, respectively. + +### Session Delegate + +By default, an Alamofire `SessionManager` instance creates a `SessionDelegate` object to handle all the various types of delegate callbacks that are generated by the underlying `URLSession`. The implementations of each delegate method handle the most common use cases for these types of calls abstracting the complexity away from the top-level APIs. However, advanced users may find the need to override the default functionality for various reasons. + +#### Override Closures + +The first way to customize the `SessionDelegate` behavior is through the use of the override closures. Each closure gives you the ability to override the implementation of the matching `SessionDelegate` API, yet still use the default implementation for all other APIs. This makes it easy to customize subsets of the delegate functionality. Here are a few examples of some of the override closures available: + +```swift +/// Overrides default behavior for URLSessionDelegate method `urlSession(_:didReceive:completionHandler:)`. +open var sessionDidReceiveChallenge: ((URLSession, URLAuthenticationChallenge) -> (URLSession.AuthChallengeDisposition, URLCredential?))? + +/// Overrides default behavior for URLSessionDelegate method `urlSessionDidFinishEvents(forBackgroundURLSession:)`. +open var sessionDidFinishEventsForBackgroundURLSession: ((URLSession) -> Void)? + +/// Overrides default behavior for URLSessionTaskDelegate method `urlSession(_:task:willPerformHTTPRedirection:newRequest:completionHandler:)`. +open var taskWillPerformHTTPRedirection: ((URLSession, URLSessionTask, HTTPURLResponse, URLRequest) -> URLRequest?)? + +/// Overrides default behavior for URLSessionDataDelegate method `urlSession(_:dataTask:willCacheResponse:completionHandler:)`. +open var dataTaskWillCacheResponse: ((URLSession, URLSessionDataTask, CachedURLResponse) -> CachedURLResponse?)? +``` + +The following is a short example of how to use the `taskWillPerformHTTPRedirection` to avoid following redirects to any `apple.com` domains. + +```swift +let sessionManager = Alamofire.SessionManager(configuration: URLSessionConfiguration.default) +let delegate: Alamofire.SessionDelegate = sessionManager.delegate + +delegate.taskWillPerformHTTPRedirection = { session, task, response, request in + var finalRequest = request + + if + let originalRequest = task.originalRequest, + let urlString = originalRequest.url?.urlString, + urlString.contains("apple.com") + { + finalRequest = originalRequest + } + + return finalRequest +} +``` + +#### Subclassing + +Another way to override the default implementation of the `SessionDelegate` is to subclass it. Subclassing allows you completely customize the behavior of the API or to create a proxy for the API and still use the default implementation. Creating a proxy allows you to log events, emit notifications, provide pre and post hook implementations, etc. Here's a quick example of subclassing the `SessionDelegate` and logging a message when a redirect occurs. + +```swift +class LoggingSessionDelegate: SessionDelegate { + override func urlSession( + _ session: URLSession, + task: URLSessionTask, + willPerformHTTPRedirection response: HTTPURLResponse, + newRequest request: URLRequest, + completionHandler: @escaping (URLRequest?) -> Void) + { + print("URLSession will perform HTTP redirection to request: \(request)") + + super.urlSession( + session, + task: task, + willPerformHTTPRedirection: response, + newRequest: request, + completionHandler: completionHandler + ) + } +} +``` + +Generally speaking, either the default implementation or the override closures should provide the necessary functionality required. Subclassing should only be used as a last resort. + +> It is important to keep in mind that the `subdelegates` are initialized and destroyed in the default implementation. Be careful when subclassing to not introduce memory leaks. + +### Request + +The result of a `request`, `download`, `upload` or `stream` methods are a `DataRequest`, `DownloadRequest`, `UploadRequest` and `StreamRequest` which all inherit from `Request`. All `Request` instances are always created by an owning session manager, and never initialized directly. + +Each subclass has specialized methods such as `authenticate`, `validate`, `responseJSON` and `uploadProgress` that each return the caller instance in order to facilitate method chaining. + +Requests can be suspended, resumed and cancelled: + +- `suspend()`: Suspends the underlying task and dispatch queue. +- `resume()`: Resumes the underlying task and dispatch queue. If the owning manager does not have `startRequestsImmediately` set to `true`, the request must call `resume()` in order to start. +- `cancel()`: Cancels the underlying task, producing an error that is passed to any registered response handlers. + +### Routing Requests + +As apps grow in size, it's important to adopt common patterns as you build out your network stack. An important part of that design is how to route your requests. The Alamofire `URLConvertible` and `URLRequestConvertible` protocols along with the `Router` design pattern are here to help. + +#### URLConvertible + +Types adopting the `URLConvertible` protocol can be used to construct URLs, which are then used to construct URL requests internally. `String`, `URL`, and `URLComponents` conform to `URLConvertible` by default, allowing any of them to be passed as `url` parameters to the `request`, `upload`, and `download` methods: + +```swift +let urlString = "https://httpbin.org/post" +Alamofire.request(urlString, method: .post) + +let url = URL(string: urlString)! +Alamofire.request(url, method: .post) + +let urlComponents = URLComponents(url: url, resolvingAgainstBaseURL: true)! +Alamofire.request(urlComponents, method: .post) +``` + +Applications interacting with web applications in a significant manner are encouraged to have custom types conform to `URLConvertible` as a convenient way to map domain-specific models to server resources. + +##### Type-Safe Routing + +```swift +extension User: URLConvertible { + static let baseURLString = "https://example.com" + + func asURL() throws -> URL { + let urlString = User.baseURLString + "/users/\(username)/" + return try urlString.asURL() + } +} +``` + +```swift +let user = User(username: "mattt") +Alamofire.request(user) // https://example.com/users/mattt +``` + +#### URLRequestConvertible + +Types adopting the `URLRequestConvertible` protocol can be used to construct URL requests. `URLRequest` conforms to `URLRequestConvertible` by default, allowing it to be passed into `request`, `upload`, and `download` methods directly (this is the recommended way to specify custom HTTP body for individual requests): + +```swift +let url = URL(string: "https://httpbin.org/post")! +var urlRequest = URLRequest(url: url) +urlRequest.httpMethod = "POST" + +let parameters = ["foo": "bar"] + +do { + urlRequest.httpBody = try JSONSerialization.data(withJSONObject: parameters, options: []) +} catch { + // No-op +} + +urlRequest.setValue("application/json", forHTTPHeaderField: "Content-Type") + +Alamofire.request(urlRequest) +``` + +Applications interacting with web applications in a significant manner are encouraged to have custom types conform to `URLRequestConvertible` as a way to ensure consistency of requested endpoints. Such an approach can be used to abstract away server-side inconsistencies and provide type-safe routing, as well as manage authentication credentials and other state. + +##### API Parameter Abstraction + +```swift +enum Router: URLRequestConvertible { + case search(query: String, page: Int) + + static let baseURLString = "https://example.com" + static let perPage = 50 + + // MARK: URLRequestConvertible + + func asURLRequest() throws -> URLRequest { + let result: (path: String, parameters: Parameters) = { + switch self { + case let .search(query, page) where page > 0: + return ("/search", ["q": query, "offset": Router.perPage * page]) + case let .search(query, _): + return ("/search", ["q": query]) + } + }() + + let url = try Router.baseURLString.asURL() + let urlRequest = URLRequest(url: url.appendingPathComponent(result.path)) + + return try URLEncoding.default.encode(urlRequest, with: result.parameters) + } +} +``` + +```swift +Alamofire.request(Router.search(query: "foo bar", page: 1)) // https://example.com/search?q=foo%20bar&offset=50 +``` + +##### CRUD & Authorization + +```swift +import Alamofire + +enum Router: URLRequestConvertible { + case createUser(parameters: Parameters) + case readUser(username: String) + case updateUser(username: String, parameters: Parameters) + case destroyUser(username: String) + + static let baseURLString = "https://example.com" + + var method: HTTPMethod { + switch self { + case .createUser: + return .post + case .readUser: + return .get + case .updateUser: + return .put + case .destroyUser: + return .delete + } + } + + var path: String { + switch self { + case .createUser: + return "/users" + case .readUser(let username): + return "/users/\(username)" + case .updateUser(let username, _): + return "/users/\(username)" + case .destroyUser(let username): + return "/users/\(username)" + } + } + + // MARK: URLRequestConvertible + + func asURLRequest() throws -> URLRequest { + let url = try Router.baseURLString.asURL() + + var urlRequest = URLRequest(url: url.appendingPathComponent(path)) + urlRequest.httpMethod = method.rawValue + + switch self { + case .createUser(let parameters): + urlRequest = try URLEncoding.default.encode(urlRequest, with: parameters) + case .updateUser(_, let parameters): + urlRequest = try URLEncoding.default.encode(urlRequest, with: parameters) + default: + break + } + + return urlRequest + } +} +``` + +```swift +Alamofire.request(Router.readUser("mattt")) // GET https://example.com/users/mattt +``` + +### Adapting and Retrying Requests + +Most web services these days are behind some sort of authentication system. One of the more common ones today is OAuth. This generally involves generating an access token authorizing your application or user to call the various supported web services. While creating these initial access tokens can be laborsome, it can be even more complicated when your access token expires and you need to fetch a new one. There are many thread-safety issues that need to be considered. + +The `RequestAdapter` and `RequestRetrier` protocols were created to make it much easier to create a thread-safe authentication system for a specific set of web services. + +#### RequestAdapter + +The `RequestAdapter` protocol allows each `Request` made on a `SessionManager` to be inspected and adapted before being created. One very specific way to use an adapter is to append an `Authorization` header to requests behind a certain type of authentication. + +```swift +class AccessTokenAdapter: RequestAdapter { + private let accessToken: String + + init(accessToken: String) { + self.accessToken = accessToken + } + + func adapt(_ urlRequest: URLRequest) throws -> URLRequest { + var urlRequest = urlRequest + + if let urlString = urlRequest.url?.absoluteString, urlString.hasPrefix("https://httpbin.org") { + urlRequest.setValue("Bearer " + accessToken, forHTTPHeaderField: "Authorization") + } + + return urlRequest + } +} +``` + +```swift +let sessionManager = SessionManager() +sessionManager.adapter = AccessTokenAdapter(accessToken: "1234") + +sessionManager.request("https://httpbin.org/get") +``` + +#### RequestRetrier + +The `RequestRetrier` protocol allows a `Request` that encountered an `Error` while being executed to be retried. When using both the `RequestAdapter` and `RequestRetrier` protocols together, you can create credential refresh systems for OAuth1, OAuth2, Basic Auth and even exponential backoff retry policies. The possibilities are endless. Here's an example of how you could implement a refresh flow for OAuth2 access tokens. + +> **DISCLAIMER:** This is **NOT** a global `OAuth2` solution. It is merely an example demonstrating how one could use the `RequestAdapter` in conjunction with the `RequestRetrier` to create a thread-safe refresh system. + +> To reiterate, **do NOT copy** this sample code and drop it into a production application. This is merely an example. Each authentication system must be tailored to a particular platform and authentication type. + +```swift +class OAuth2Handler: RequestAdapter, RequestRetrier { + private typealias RefreshCompletion = (_ succeeded: Bool, _ accessToken: String?, _ refreshToken: String?) -> Void + + private let sessionManager: SessionManager = { + let configuration = URLSessionConfiguration.default + configuration.httpAdditionalHeaders = SessionManager.defaultHTTPHeaders + + return SessionManager(configuration: configuration) + }() + + private let lock = NSLock() + + private var clientID: String + private var baseURLString: String + private var accessToken: String + private var refreshToken: String + + private var isRefreshing = false + private var requestsToRetry: [RequestRetryCompletion] = [] + + // MARK: - Initialization + + public init(clientID: String, baseURLString: String, accessToken: String, refreshToken: String) { + self.clientID = clientID + self.baseURLString = baseURLString + self.accessToken = accessToken + self.refreshToken = refreshToken + } + + // MARK: - RequestAdapter + + func adapt(_ urlRequest: URLRequest) throws -> URLRequest { + if let urlString = urlRequest.url?.absoluteString, urlString.hasPrefix(baseURLString) { + var urlRequest = urlRequest + urlRequest.setValue("Bearer " + accessToken, forHTTPHeaderField: "Authorization") + return urlRequest + } + + return urlRequest + } + + // MARK: - RequestRetrier + + func should(_ manager: SessionManager, retry request: Request, with error: Error, completion: @escaping RequestRetryCompletion) { + lock.lock() ; defer { lock.unlock() } + + if let response = request.task?.response as? HTTPURLResponse, response.statusCode == 401 { + requestsToRetry.append(completion) + + if !isRefreshing { + refreshTokens { [weak self] succeeded, accessToken, refreshToken in + guard let strongSelf = self else { return } + + strongSelf.lock.lock() ; defer { strongSelf.lock.unlock() } + + if let accessToken = accessToken, let refreshToken = refreshToken { + strongSelf.accessToken = accessToken + strongSelf.refreshToken = refreshToken + } + + strongSelf.requestsToRetry.forEach { $0(succeeded, 0.0) } + strongSelf.requestsToRetry.removeAll() + } + } + } else { + completion(false, 0.0) + } + } + + // MARK: - Private - Refresh Tokens + + private func refreshTokens(completion: @escaping RefreshCompletion) { + guard !isRefreshing else { return } + + isRefreshing = true + + let urlString = "\(baseURLString)/oauth2/token" + + let parameters: [String: Any] = [ + "access_token": accessToken, + "refresh_token": refreshToken, + "client_id": clientID, + "grant_type": "refresh_token" + ] + + sessionManager.request(urlString, method: .post, parameters: parameters, encoding: JSONEncoding.default) + .responseJSON { [weak self] response in + guard let strongSelf = self else { return } + + if + let json = response.result.value as? [String: Any], + let accessToken = json["access_token"] as? String, + let refreshToken = json["refresh_token"] as? String + { + completion(true, accessToken, refreshToken) + } else { + completion(false, nil, nil) + } + + strongSelf.isRefreshing = false + } + } +} +``` + +```swift +let baseURLString = "https://some.domain-behind-oauth2.com" + +let oauthHandler = OAuth2Handler( + clientID: "12345678", + baseURLString: baseURLString, + accessToken: "abcd1234", + refreshToken: "ef56789a" +) + +let sessionManager = SessionManager() +sessionManager.adapter = oauthHandler +sessionManager.retrier = oauthHandler + +let urlString = "\(baseURLString)/some/endpoint" + +sessionManager.request(urlString).validate().responseJSON { response in + debugPrint(response) +} +``` + +Once the `OAuth2Handler` is applied as both the `adapter` and `retrier` for the `SessionManager`, it will handle an invalid access token error by automatically refreshing the access token and retrying all failed requests in the same order they failed. + +> If you needed them to execute in the same order they were created, you could sort them by their task identifiers. + +The example above only checks for a `401` response code which is not nearly robust enough, but does demonstrate how one could check for an invalid access token error. In a production application, one would want to check the `realm` and most likely the `www-authenticate` header response although it depends on the OAuth2 implementation. + +Another important note is that this authentication system could be shared between multiple session managers. For example, you may need to use both a `default` and `ephemeral` session configuration for the same set of web services. The example above allows the same `oauthHandler` instance to be shared across multiple session managers to manage the single refresh flow. + +### Custom Response Serialization + +#### Handling Errors + +Before implementing custom response serializers or object serialization methods, it's important to consider how to handle any errors that may occur. There are two basic options: passing existing errors along unmodified, to be dealt with at response time; or, wrapping all errors in an `Error` type specific to your app. + +For example, here's a simple `BackendError` enum which will be used in later examples: + +```swift +enum BackendError: Error { + case network(error: Error) // Capture any underlying Error from the URLSession API + case dataSerialization(error: Error) + case jsonSerialization(error: Error) + case xmlSerialization(error: Error) + case objectSerialization(reason: String) +} +``` + +#### Creating a Custom Response Serializer + +Alamofire provides built-in response serialization for strings, JSON, and property lists, but others can be added in extensions on `Alamofire.DataRequest` and / or `Alamofire.DownloadRequest`. + +For example, here's how a response handler using [Ono](https://github.com/mattt/Ono) might be implemented: + +```swift +extension DataRequest { + static func xmlResponseSerializer() -> DataResponseSerializer { + return DataResponseSerializer { request, response, data, error in + // Pass through any underlying URLSession error to the .network case. + guard error == nil else { return .failure(BackendError.network(error: error!)) } + + // Use Alamofire's existing data serializer to extract the data, passing the error as nil, as it has + // already been handled. + let result = Request.serializeResponseData(response: response, data: data, error: nil) + + guard case let .success(validData) = result else { + return .failure(BackendError.dataSerialization(error: result.error! as! AFError)) + } + + do { + let xml = try ONOXMLDocument(data: validData) + return .success(xml) + } catch { + return .failure(BackendError.xmlSerialization(error: error)) + } + } + } + + @discardableResult + func responseXMLDocument( + queue: DispatchQueue? = nil, + completionHandler: @escaping (DataResponse) -> Void) + -> Self + { + return response( + queue: queue, + responseSerializer: DataRequest.xmlResponseSerializer(), + completionHandler: completionHandler + ) + } +} +``` + +#### Generic Response Object Serialization + +Generics can be used to provide automatic, type-safe response object serialization. + +```swift +protocol ResponseObjectSerializable { + init?(response: HTTPURLResponse, representation: Any) +} + +extension DataRequest { + func responseObject( + queue: DispatchQueue? = nil, + completionHandler: @escaping (DataResponse) -> Void) + -> Self + { + let responseSerializer = DataResponseSerializer { request, response, data, error in + guard error == nil else { return .failure(BackendError.network(error: error!)) } + + let jsonResponseSerializer = DataRequest.jsonResponseSerializer(options: .allowFragments) + let result = jsonResponseSerializer.serializeResponse(request, response, data, nil) + + guard case let .success(jsonObject) = result else { + return .failure(BackendError.jsonSerialization(error: result.error!)) + } + + guard let response = response, let responseObject = T(response: response, representation: jsonObject) else { + return .failure(BackendError.objectSerialization(reason: "JSON could not be serialized: \(jsonObject)")) + } + + return .success(responseObject) + } + + return response(queue: queue, responseSerializer: responseSerializer, completionHandler: completionHandler) + } +} +``` + +```swift +struct User: ResponseObjectSerializable, CustomStringConvertible { + let username: String + let name: String + + var description: String { + return "User: { username: \(username), name: \(name) }" + } + + init?(response: HTTPURLResponse, representation: Any) { + guard + let username = response.url?.lastPathComponent, + let representation = representation as? [String: Any], + let name = representation["name"] as? String + else { return nil } + + self.username = username + self.name = name + } +} +``` + +```swift +Alamofire.request("https://example.com/users/mattt").responseObject { (response: DataResponse) in + debugPrint(response) + + if let user = response.result.value { + print("User: { username: \(user.username), name: \(user.name) }") + } +} +``` + +The same approach can also be used to handle endpoints that return a representation of a collection of objects: + +```swift +protocol ResponseCollectionSerializable { + static func collection(from response: HTTPURLResponse, withRepresentation representation: Any) -> [Self] +} + +extension ResponseCollectionSerializable where Self: ResponseObjectSerializable { + static func collection(from response: HTTPURLResponse, withRepresentation representation: Any) -> [Self] { + var collection: [Self] = [] + + if let representation = representation as? [[String: Any]] { + for itemRepresentation in representation { + if let item = Self(response: response, representation: itemRepresentation) { + collection.append(item) + } + } + } + + return collection + } +} +``` + +```swift +extension DataRequest { + @discardableResult + func responseCollection( + queue: DispatchQueue? = nil, + completionHandler: @escaping (DataResponse<[T]>) -> Void) -> Self + { + let responseSerializer = DataResponseSerializer<[T]> { request, response, data, error in + guard error == nil else { return .failure(BackendError.network(error: error!)) } + + let jsonSerializer = DataRequest.jsonResponseSerializer(options: .allowFragments) + let result = jsonSerializer.serializeResponse(request, response, data, nil) + + guard case let .success(jsonObject) = result else { + return .failure(BackendError.jsonSerialization(error: result.error!)) + } + + guard let response = response else { + let reason = "Response collection could not be serialized due to nil response." + return .failure(BackendError.objectSerialization(reason: reason)) + } + + return .success(T.collection(from: response, withRepresentation: jsonObject)) + } + + return response(responseSerializer: responseSerializer, completionHandler: completionHandler) + } +} +``` + +```swift +struct User: ResponseObjectSerializable, ResponseCollectionSerializable, CustomStringConvertible { + let username: String + let name: String + + var description: String { + return "User: { username: \(username), name: \(name) }" + } + + init?(response: HTTPURLResponse, representation: Any) { + guard + let username = response.url?.lastPathComponent, + let representation = representation as? [String: Any], + let name = representation["name"] as? String + else { return nil } + + self.username = username + self.name = name + } +} +``` + +```swift +Alamofire.request("https://example.com/users").responseCollection { (response: DataResponse<[User]>) in + debugPrint(response) + + if let users = response.result.value { + users.forEach { print("- \($0)") } + } +} +``` + +### Security + +Using a secure HTTPS connection when communicating with servers and web services is an important step in securing sensitive data. By default, Alamofire will evaluate the certificate chain provided by the server using Apple's built in validation provided by the Security framework. While this guarantees the certificate chain is valid, it does not prevent man-in-the-middle (MITM) attacks or other potential vulnerabilities. In order to mitigate MITM attacks, applications dealing with sensitive customer data or financial information should use certificate or public key pinning provided by the `ServerTrustPolicy`. + +#### ServerTrustPolicy + +The `ServerTrustPolicy` enumeration evaluates the server trust generally provided by an `URLAuthenticationChallenge` when connecting to a server over a secure HTTPS connection. + +```swift +let serverTrustPolicy = ServerTrustPolicy.pinCertificates( + certificates: ServerTrustPolicy.certificatesInBundle(), + validateCertificateChain: true, + validateHost: true +) +``` + +There are many different cases of server trust evaluation giving you complete control over the validation process: + +* `performDefaultEvaluation`: Uses the default server trust evaluation while allowing you to control whether to validate the host provided by the challenge. +* `pinCertificates`: Uses the pinned certificates to validate the server trust. The server trust is considered valid if one of the pinned certificates match one of the server certificates. +* `pinPublicKeys`: Uses the pinned public keys to validate the server trust. The server trust is considered valid if one of the pinned public keys match one of the server certificate public keys. +* `disableEvaluation`: Disables all evaluation which in turn will always consider any server trust as valid. +* `customEvaluation`: Uses the associated closure to evaluate the validity of the server trust thus giving you complete control over the validation process. Use with caution. + +#### Server Trust Policy Manager + +The `ServerTrustPolicyManager` is responsible for storing an internal mapping of server trust policies to a particular host. This allows Alamofire to evaluate each host against a different server trust policy. + +```swift +let serverTrustPolicies: [String: ServerTrustPolicy] = [ + "test.example.com": .pinCertificates( + certificates: ServerTrustPolicy.certificatesInBundle(), + validateCertificateChain: true, + validateHost: true + ), + "insecure.expired-apis.com": .disableEvaluation +] + +let sessionManager = SessionManager( + serverTrustPolicyManager: ServerTrustPolicyManager(policies: serverTrustPolicies) +) +``` + +> Make sure to keep a reference to the new `SessionManager` instance, otherwise your requests will all get cancelled when your `sessionManager` is deallocated. + +These server trust policies will result in the following behavior: + +- `test.example.com` will always use certificate pinning with certificate chain and host validation enabled thus requiring the following criteria to be met to allow the TLS handshake to succeed: + - Certificate chain MUST be valid. + - Certificate chain MUST include one of the pinned certificates. + - Challenge host MUST match the host in the certificate chain's leaf certificate. +- `insecure.expired-apis.com` will never evaluate the certificate chain and will always allow the TLS handshake to succeed. +- All other hosts will use the default evaluation provided by Apple. + +##### Subclassing Server Trust Policy Manager + +If you find yourself needing more flexible server trust policy matching behavior (i.e. wildcarded domains), then subclass the `ServerTrustPolicyManager` and override the `serverTrustPolicyForHost` method with your own custom implementation. + +```swift +class CustomServerTrustPolicyManager: ServerTrustPolicyManager { + override func serverTrustPolicy(forHost host: String) -> ServerTrustPolicy? { + var policy: ServerTrustPolicy? + + // Implement your custom domain matching behavior... + + return policy + } +} +``` + +#### Validating the Host + +The `.performDefaultEvaluation`, `.pinCertificates` and `.pinPublicKeys` server trust policies all take a `validateHost` parameter. Setting the value to `true` will cause the server trust evaluation to verify that hostname in the certificate matches the hostname of the challenge. If they do not match, evaluation will fail. A `validateHost` value of `false` will still evaluate the full certificate chain, but will not validate the hostname of the leaf certificate. + +> It is recommended that `validateHost` always be set to `true` in production environments. + +#### Validating the Certificate Chain + +Pinning certificates and public keys both have the option of validating the certificate chain using the `validateCertificateChain` parameter. By setting this value to `true`, the full certificate chain will be evaluated in addition to performing a byte equality check against the pinned certificates or public keys. A value of `false` will skip the certificate chain validation, but will still perform the byte equality check. + +There are several cases where it may make sense to disable certificate chain validation. The most common use cases for disabling validation are self-signed and expired certificates. The evaluation would always fail in both of these cases, but the byte equality check will still ensure you are receiving the certificate you expect from the server. + +> It is recommended that `validateCertificateChain` always be set to `true` in production environments. + +#### App Transport Security + +With the addition of App Transport Security (ATS) in iOS 9, it is possible that using a custom `ServerTrustPolicyManager` with several `ServerTrustPolicy` objects will have no effect. If you continuously see `CFNetwork SSLHandshake failed (-9806)` errors, you have probably run into this problem. Apple's ATS system overrides the entire challenge system unless you configure the ATS settings in your app's plist to disable enough of it to allow your app to evaluate the server trust. + +If you run into this problem (high probability with self-signed certificates), you can work around this issue by adding the following to your `Info.plist`. + +```xml + + NSAppTransportSecurity + + NSExceptionDomains + + example.com + + NSExceptionAllowsInsecureHTTPLoads + + NSExceptionRequiresForwardSecrecy + + NSIncludesSubdomains + + + NSTemporaryExceptionMinimumTLSVersion + TLSv1.2 + + + + +``` + +Whether you need to set the `NSExceptionRequiresForwardSecrecy` to `NO` depends on whether your TLS connection is using an allowed cipher suite. In certain cases, it will need to be set to `NO`. The `NSExceptionAllowsInsecureHTTPLoads` MUST be set to `YES` in order to allow the `SessionDelegate` to receive challenge callbacks. Once the challenge callbacks are being called, the `ServerTrustPolicyManager` will take over the server trust evaluation. You may also need to specify the `NSTemporaryExceptionMinimumTLSVersion` if you're trying to connect to a host that only supports TLS versions less than `1.2`. + +> It is recommended to always use valid certificates in production environments. + +### Network Reachability + +The `NetworkReachabilityManager` listens for reachability changes of hosts and addresses for both WWAN and WiFi network interfaces. + +```swift +let manager = NetworkReachabilityManager(host: "www.apple.com") + +manager?.listener = { status in + print("Network Status Changed: \(status)") +} + +manager?.startListening() +``` + +> Make sure to remember to retain the `manager` in the above example, or no status changes will be reported. + +There are some important things to remember when using network reachability to determine what to do next. + +- **Do NOT** use Reachability to determine if a network request should be sent. + - You should **ALWAYS** send it. +- When Reachability is restored, use the event to retry failed network requests. + - Even though the network requests may still fail, this is a good moment to retry them. +- The network reachability status can be useful for determining why a network request may have failed. + - If a network request fails, it is more useful to tell the user that the network request failed due to being offline rather than a more technical error, such as "request timed out." + +> It is recommended to check out [WWDC 2012 Session 706, "Networking Best Practices"](https://developer.apple.com/videos/play/wwdc2012-706/) for more info. + +--- + +## Open Radars + +The following radars have some effect on the current implementation of Alamofire. + +- [`rdar://21349340`](http://www.openradar.me/radar?id=5517037090635776) - Compiler throwing warning due to toll-free bridging issue in test case +- [`rdar://26761490`](http://www.openradar.me/radar?id=5010235949318144) - Swift string interpolation causing memory leak with common usage +- `rdar://26870455` - Background URL Session Configurations do not work in the simulator +- `rdar://26849668` - Some URLProtocol APIs do not properly handle `URLRequest` + +## FAQ + +### What's the origin of the name Alamofire? + +Alamofire is named after the [Alamo Fire flower](https://aggie-horticulture.tamu.edu/wildseed/alamofire.html), a hybrid variant of the Bluebonnet, the official state flower of Texas. + +### What logic belongs in a Router vs. a Request Adapter? + +Simple, static data such as paths, parameters and common headers belong in the `Router`. Dynamic data such as an `Authorization` header whose value can changed based on an authentication system belongs in a `RequestAdapter`. + +The reason the dynamic data MUST be placed into the `RequestAdapter` is to support retry operations. When a `Request` is retried, the original request is not rebuilt meaning the `Router` will not be called again. The `RequestAdapter` is called again allowing the dynamic data to be updated on the original request before retrying the `Request`. + +--- + +## Credits + +Alamofire is owned and maintained by the [Alamofire Software Foundation](http://alamofire.org). You can follow them on Twitter at [@AlamofireSF](https://twitter.com/AlamofireSF) for project updates and releases. + +### Security Disclosure + +If you believe you have identified a security vulnerability with Alamofire, you should report it as soon as possible via email to security@alamofire.org. Please do not post it to a public issue tracker. + +## Donations + +The [ASF](https://github.com/Alamofire/Foundation#members) is looking to raise money to officially register as a federal non-profit organization. Registering will allow us members to gain some legal protections and also allow us to put donations to use, tax free. Donating to the ASF will enable us to: + +- Pay our legal fees to register as a federal non-profit organization +- Pay our yearly legal fees to keep the non-profit in good status +- Pay for our mail servers to help us stay on top of all questions and security issues +- Potentially fund test servers to make it easier for us to test the edge cases +- Potentially fund developers to work on one of our projects full-time + +The community adoption of the ASF libraries has been amazing. We are greatly humbled by your enthusiasm around the projects, and want to continue to do everything we can to move the needle forward. With your continued support, the ASF will be able to improve its reach and also provide better legal safety for the core members. If you use any of our libraries for work, see if your employers would be interested in donating. Our initial goal is to raise $1000 to get all our legal ducks in a row and kickstart this campaign. Any amount you can donate today to help us reach our goal would be greatly appreciated. + +Click here to lend your support to: Alamofire Software Foundation and make a donation at pledgie.com ! + +## License + +Alamofire is released under the MIT license. See LICENSE for details. diff --git a/Pods/Alamofire/Source/AFError.swift b/Pods/Alamofire/Source/AFError.swift new file mode 100644 index 0000000..f047695 --- /dev/null +++ b/Pods/Alamofire/Source/AFError.swift @@ -0,0 +1,460 @@ +// +// AFError.swift +// +// Copyright (c) 2014-2016 Alamofire Software Foundation (http://alamofire.org/) +// +// Permission is hereby granted, free of charge, to any person obtaining a copy +// of this software and associated documentation files (the "Software"), to deal +// in the Software without restriction, including without limitation the rights +// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +// copies of the Software, and to permit persons to whom the Software is +// furnished to do so, subject to the following conditions: +// +// The above copyright notice and this permission notice shall be included in +// all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN +// THE SOFTWARE. +// + +import Foundation + +/// `AFError` is the error type returned by Alamofire. It encompasses a few different types of errors, each with +/// their own associated reasons. +/// +/// - invalidURL: Returned when a `URLConvertible` type fails to create a valid `URL`. +/// - parameterEncodingFailed: Returned when a parameter encoding object throws an error during the encoding process. +/// - multipartEncodingFailed: Returned when some step in the multipart encoding process fails. +/// - responseValidationFailed: Returned when a `validate()` call fails. +/// - responseSerializationFailed: Returned when a response serializer encounters an error in the serialization process. +public enum AFError: Error { + /// The underlying reason the parameter encoding error occurred. + /// + /// - missingURL: The URL request did not have a URL to encode. + /// - jsonEncodingFailed: JSON serialization failed with an underlying system error during the + /// encoding process. + /// - propertyListEncodingFailed: Property list serialization failed with an underlying system error during + /// encoding process. + public enum ParameterEncodingFailureReason { + case missingURL + case jsonEncodingFailed(error: Error) + case propertyListEncodingFailed(error: Error) + } + + /// The underlying reason the multipart encoding error occurred. + /// + /// - bodyPartURLInvalid: The `fileURL` provided for reading an encodable body part isn't a + /// file URL. + /// - bodyPartFilenameInvalid: The filename of the `fileURL` provided has either an empty + /// `lastPathComponent` or `pathExtension. + /// - bodyPartFileNotReachable: The file at the `fileURL` provided was not reachable. + /// - bodyPartFileNotReachableWithError: Attempting to check the reachability of the `fileURL` provided threw + /// an error. + /// - bodyPartFileIsDirectory: The file at the `fileURL` provided is actually a directory. + /// - bodyPartFileSizeNotAvailable: The size of the file at the `fileURL` provided was not returned by + /// the system. + /// - bodyPartFileSizeQueryFailedWithError: The attempt to find the size of the file at the `fileURL` provided + /// threw an error. + /// - bodyPartInputStreamCreationFailed: An `InputStream` could not be created for the provided `fileURL`. + /// - outputStreamCreationFailed: An `OutputStream` could not be created when attempting to write the + /// encoded data to disk. + /// - outputStreamFileAlreadyExists: The encoded body data could not be writtent disk because a file + /// already exists at the provided `fileURL`. + /// - outputStreamURLInvalid: The `fileURL` provided for writing the encoded body data to disk is + /// not a file URL. + /// - outputStreamWriteFailed: The attempt to write the encoded body data to disk failed with an + /// underlying error. + /// - inputStreamReadFailed: The attempt to read an encoded body part `InputStream` failed with + /// underlying system error. + public enum MultipartEncodingFailureReason { + case bodyPartURLInvalid(url: URL) + case bodyPartFilenameInvalid(in: URL) + case bodyPartFileNotReachable(at: URL) + case bodyPartFileNotReachableWithError(atURL: URL, error: Error) + case bodyPartFileIsDirectory(at: URL) + case bodyPartFileSizeNotAvailable(at: URL) + case bodyPartFileSizeQueryFailedWithError(forURL: URL, error: Error) + case bodyPartInputStreamCreationFailed(for: URL) + + case outputStreamCreationFailed(for: URL) + case outputStreamFileAlreadyExists(at: URL) + case outputStreamURLInvalid(url: URL) + case outputStreamWriteFailed(error: Error) + + case inputStreamReadFailed(error: Error) + } + + /// The underlying reason the response validation error occurred. + /// + /// - dataFileNil: The data file containing the server response did not exist. + /// - dataFileReadFailed: The data file containing the server response could not be read. + /// - missingContentType: The response did not contain a `Content-Type` and the `acceptableContentTypes` + /// provided did not contain wildcard type. + /// - unacceptableContentType: The response `Content-Type` did not match any type in the provided + /// `acceptableContentTypes`. + /// - unacceptableStatusCode: The response status code was not acceptable. + public enum ResponseValidationFailureReason { + case dataFileNil + case dataFileReadFailed(at: URL) + case missingContentType(acceptableContentTypes: [String]) + case unacceptableContentType(acceptableContentTypes: [String], responseContentType: String) + case unacceptableStatusCode(code: Int) + } + + /// The underlying reason the response serialization error occurred. + /// + /// - inputDataNil: The server response contained no data. + /// - inputDataNilOrZeroLength: The server response contained no data or the data was zero length. + /// - inputFileNil: The file containing the server response did not exist. + /// - inputFileReadFailed: The file containing the server response could not be read. + /// - stringSerializationFailed: String serialization failed using the provided `String.Encoding`. + /// - jsonSerializationFailed: JSON serialization failed with an underlying system error. + /// - propertyListSerializationFailed: Property list serialization failed with an underlying system error. + public enum ResponseSerializationFailureReason { + case inputDataNil + case inputDataNilOrZeroLength + case inputFileNil + case inputFileReadFailed(at: URL) + case stringSerializationFailed(encoding: String.Encoding) + case jsonSerializationFailed(error: Error) + case propertyListSerializationFailed(error: Error) + } + + case invalidURL(url: URLConvertible) + case parameterEncodingFailed(reason: ParameterEncodingFailureReason) + case multipartEncodingFailed(reason: MultipartEncodingFailureReason) + case responseValidationFailed(reason: ResponseValidationFailureReason) + case responseSerializationFailed(reason: ResponseSerializationFailureReason) +} + +// MARK: - Adapt Error + +struct AdaptError: Error { + let error: Error +} + +extension Error { + var underlyingAdaptError: Error? { return (self as? AdaptError)?.error } +} + +// MARK: - Error Booleans + +extension AFError { + /// Returns whether the AFError is an invalid URL error. + public var isInvalidURLError: Bool { + if case .invalidURL = self { return true } + return false + } + + /// Returns whether the AFError is a parameter encoding error. When `true`, the `underlyingError` property will + /// contain the associated value. + public var isParameterEncodingError: Bool { + if case .parameterEncodingFailed = self { return true } + return false + } + + /// Returns whether the AFError is a multipart encoding error. When `true`, the `url` and `underlyingError` properties + /// will contain the associated values. + public var isMultipartEncodingError: Bool { + if case .multipartEncodingFailed = self { return true } + return false + } + + /// Returns whether the `AFError` is a response validation error. When `true`, the `acceptableContentTypes`, + /// `responseContentType`, and `responseCode` properties will contain the associated values. + public var isResponseValidationError: Bool { + if case .responseValidationFailed = self { return true } + return false + } + + /// Returns whether the `AFError` is a response serialization error. When `true`, the `failedStringEncoding` and + /// `underlyingError` properties will contain the associated values. + public var isResponseSerializationError: Bool { + if case .responseSerializationFailed = self { return true } + return false + } +} + +// MARK: - Convenience Properties + +extension AFError { + /// The `URLConvertible` associated with the error. + public var urlConvertible: URLConvertible? { + switch self { + case .invalidURL(let url): + return url + default: + return nil + } + } + + /// The `URL` associated with the error. + public var url: URL? { + switch self { + case .multipartEncodingFailed(let reason): + return reason.url + default: + return nil + } + } + + /// The `Error` returned by a system framework associated with a `.parameterEncodingFailed`, + /// `.multipartEncodingFailed` or `.responseSerializationFailed` error. + public var underlyingError: Error? { + switch self { + case .parameterEncodingFailed(let reason): + return reason.underlyingError + case .multipartEncodingFailed(let reason): + return reason.underlyingError + case .responseSerializationFailed(let reason): + return reason.underlyingError + default: + return nil + } + } + + /// The acceptable `Content-Type`s of a `.responseValidationFailed` error. + public var acceptableContentTypes: [String]? { + switch self { + case .responseValidationFailed(let reason): + return reason.acceptableContentTypes + default: + return nil + } + } + + /// The response `Content-Type` of a `.responseValidationFailed` error. + public var responseContentType: String? { + switch self { + case .responseValidationFailed(let reason): + return reason.responseContentType + default: + return nil + } + } + + /// The response code of a `.responseValidationFailed` error. + public var responseCode: Int? { + switch self { + case .responseValidationFailed(let reason): + return reason.responseCode + default: + return nil + } + } + + /// The `String.Encoding` associated with a failed `.stringResponse()` call. + public var failedStringEncoding: String.Encoding? { + switch self { + case .responseSerializationFailed(let reason): + return reason.failedStringEncoding + default: + return nil + } + } +} + +extension AFError.ParameterEncodingFailureReason { + var underlyingError: Error? { + switch self { + case .jsonEncodingFailed(let error), .propertyListEncodingFailed(let error): + return error + default: + return nil + } + } +} + +extension AFError.MultipartEncodingFailureReason { + var url: URL? { + switch self { + case .bodyPartURLInvalid(let url), .bodyPartFilenameInvalid(let url), .bodyPartFileNotReachable(let url), + .bodyPartFileIsDirectory(let url), .bodyPartFileSizeNotAvailable(let url), + .bodyPartInputStreamCreationFailed(let url), .outputStreamCreationFailed(let url), + .outputStreamFileAlreadyExists(let url), .outputStreamURLInvalid(let url), + .bodyPartFileNotReachableWithError(let url, _), .bodyPartFileSizeQueryFailedWithError(let url, _): + return url + default: + return nil + } + } + + var underlyingError: Error? { + switch self { + case .bodyPartFileNotReachableWithError(_, let error), .bodyPartFileSizeQueryFailedWithError(_, let error), + .outputStreamWriteFailed(let error), .inputStreamReadFailed(let error): + return error + default: + return nil + } + } +} + +extension AFError.ResponseValidationFailureReason { + var acceptableContentTypes: [String]? { + switch self { + case .missingContentType(let types), .unacceptableContentType(let types, _): + return types + default: + return nil + } + } + + var responseContentType: String? { + switch self { + case .unacceptableContentType(_, let responseType): + return responseType + default: + return nil + } + } + + var responseCode: Int? { + switch self { + case .unacceptableStatusCode(let code): + return code + default: + return nil + } + } +} + +extension AFError.ResponseSerializationFailureReason { + var failedStringEncoding: String.Encoding? { + switch self { + case .stringSerializationFailed(let encoding): + return encoding + default: + return nil + } + } + + var underlyingError: Error? { + switch self { + case .jsonSerializationFailed(let error), .propertyListSerializationFailed(let error): + return error + default: + return nil + } + } +} + +// MARK: - Error Descriptions + +extension AFError: LocalizedError { + public var errorDescription: String? { + switch self { + case .invalidURL(let url): + return "URL is not valid: \(url)" + case .parameterEncodingFailed(let reason): + return reason.localizedDescription + case .multipartEncodingFailed(let reason): + return reason.localizedDescription + case .responseValidationFailed(let reason): + return reason.localizedDescription + case .responseSerializationFailed(let reason): + return reason.localizedDescription + } + } +} + +extension AFError.ParameterEncodingFailureReason { + var localizedDescription: String { + switch self { + case .missingURL: + return "URL request to encode was missing a URL" + case .jsonEncodingFailed(let error): + return "JSON could not be encoded because of error:\n\(error.localizedDescription)" + case .propertyListEncodingFailed(let error): + return "PropertyList could not be encoded because of error:\n\(error.localizedDescription)" + } + } +} + +extension AFError.MultipartEncodingFailureReason { + var localizedDescription: String { + switch self { + case .bodyPartURLInvalid(let url): + return "The URL provided is not a file URL: \(url)" + case .bodyPartFilenameInvalid(let url): + return "The URL provided does not have a valid filename: \(url)" + case .bodyPartFileNotReachable(let url): + return "The URL provided is not reachable: \(url)" + case .bodyPartFileNotReachableWithError(let url, let error): + return ( + "The system returned an error while checking the provided URL for " + + "reachability.\nURL: \(url)\nError: \(error)" + ) + case .bodyPartFileIsDirectory(let url): + return "The URL provided is a directory: \(url)" + case .bodyPartFileSizeNotAvailable(let url): + return "Could not fetch the file size from the provided URL: \(url)" + case .bodyPartFileSizeQueryFailedWithError(let url, let error): + return ( + "The system returned an error while attempting to fetch the file size from the " + + "provided URL.\nURL: \(url)\nError: \(error)" + ) + case .bodyPartInputStreamCreationFailed(let url): + return "Failed to create an InputStream for the provided URL: \(url)" + case .outputStreamCreationFailed(let url): + return "Failed to create an OutputStream for URL: \(url)" + case .outputStreamFileAlreadyExists(let url): + return "A file already exists at the provided URL: \(url)" + case .outputStreamURLInvalid(let url): + return "The provided OutputStream URL is invalid: \(url)" + case .outputStreamWriteFailed(let error): + return "OutputStream write failed with error: \(error)" + case .inputStreamReadFailed(let error): + return "InputStream read failed with error: \(error)" + } + } +} + +extension AFError.ResponseSerializationFailureReason { + var localizedDescription: String { + switch self { + case .inputDataNil: + return "Response could not be serialized, input data was nil." + case .inputDataNilOrZeroLength: + return "Response could not be serialized, input data was nil or zero length." + case .inputFileNil: + return "Response could not be serialized, input file was nil." + case .inputFileReadFailed(let url): + return "Response could not be serialized, input file could not be read: \(url)." + case .stringSerializationFailed(let encoding): + return "String could not be serialized with encoding: \(encoding)." + case .jsonSerializationFailed(let error): + return "JSON could not be serialized because of error:\n\(error.localizedDescription)" + case .propertyListSerializationFailed(let error): + return "PropertyList could not be serialized because of error:\n\(error.localizedDescription)" + } + } +} + +extension AFError.ResponseValidationFailureReason { + var localizedDescription: String { + switch self { + case .dataFileNil: + return "Response could not be validated, data file was nil." + case .dataFileReadFailed(let url): + return "Response could not be validated, data file could not be read: \(url)." + case .missingContentType(let types): + return ( + "Response Content-Type was missing and acceptable content types " + + "(\(types.joined(separator: ","))) do not match \"*/*\"." + ) + case .unacceptableContentType(let acceptableTypes, let responseType): + return ( + "Response Content-Type \"\(responseType)\" does not match any acceptable types: " + + "\(acceptableTypes.joined(separator: ","))." + ) + case .unacceptableStatusCode(let code): + return "Response status code was unacceptable: \(code)." + } + } +} diff --git a/Pods/Alamofire/Source/Alamofire.swift b/Pods/Alamofire/Source/Alamofire.swift new file mode 100644 index 0000000..86d54d8 --- /dev/null +++ b/Pods/Alamofire/Source/Alamofire.swift @@ -0,0 +1,465 @@ +// +// Alamofire.swift +// +// Copyright (c) 2014-2016 Alamofire Software Foundation (http://alamofire.org/) +// +// Permission is hereby granted, free of charge, to any person obtaining a copy +// of this software and associated documentation files (the "Software"), to deal +// in the Software without restriction, including without limitation the rights +// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +// copies of the Software, and to permit persons to whom the Software is +// furnished to do so, subject to the following conditions: +// +// The above copyright notice and this permission notice shall be included in +// all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN +// THE SOFTWARE. +// + +import Foundation + +/// Types adopting the `URLConvertible` protocol can be used to construct URLs, which are then used to construct +/// URL requests. +public protocol URLConvertible { + /// Returns a URL that conforms to RFC 2396 or throws an `Error`. + /// + /// - throws: An `Error` if the type cannot be converted to a `URL`. + /// + /// - returns: A URL or throws an `Error`. + func asURL() throws -> URL +} + +extension String: URLConvertible { + /// Returns a URL if `self` represents a valid URL string that conforms to RFC 2396 or throws an `AFError`. + /// + /// - throws: An `AFError.invalidURL` if `self` is not a valid URL string. + /// + /// - returns: A URL or throws an `AFError`. + public func asURL() throws -> URL { + guard let url = URL(string: self) else { throw AFError.invalidURL(url: self) } + return url + } +} + +extension URL: URLConvertible { + /// Returns self. + public func asURL() throws -> URL { return self } +} + +extension URLComponents: URLConvertible { + /// Returns a URL if `url` is not nil, otherise throws an `Error`. + /// + /// - throws: An `AFError.invalidURL` if `url` is `nil`. + /// + /// - returns: A URL or throws an `AFError`. + public func asURL() throws -> URL { + guard let url = url else { throw AFError.invalidURL(url: self) } + return url + } +} + +// MARK: - + +/// Types adopting the `URLRequestConvertible` protocol can be used to construct URL requests. +public protocol URLRequestConvertible { + /// Returns a URL request or throws if an `Error` was encountered. + /// + /// - throws: An `Error` if the underlying `URLRequest` is `nil`. + /// + /// - returns: A URL request. + func asURLRequest() throws -> URLRequest +} + +extension URLRequestConvertible { + /// The URL request. + public var urlRequest: URLRequest? { return try? asURLRequest() } +} + +extension URLRequest: URLRequestConvertible { + /// Returns a URL request or throws if an `Error` was encountered. + public func asURLRequest() throws -> URLRequest { return self } +} + +// MARK: - + +extension URLRequest { + /// Creates an instance with the specified `method`, `urlString` and `headers`. + /// + /// - parameter url: The URL. + /// - parameter method: The HTTP method. + /// - parameter headers: The HTTP headers. `nil` by default. + /// + /// - returns: The new `URLRequest` instance. + public init(url: URLConvertible, method: HTTPMethod, headers: HTTPHeaders? = nil) throws { + let url = try url.asURL() + + self.init(url: url) + + httpMethod = method.rawValue + + if let headers = headers { + for (headerField, headerValue) in headers { + setValue(headerValue, forHTTPHeaderField: headerField) + } + } + } + + func adapt(using adapter: RequestAdapter?) throws -> URLRequest { + guard let adapter = adapter else { return self } + return try adapter.adapt(self) + } +} + +// MARK: - Data Request + +/// Creates a `DataRequest` using the default `SessionManager` to retrieve the contents of the specified `url`, +/// `method`, `parameters`, `encoding` and `headers`. +/// +/// - parameter url: The URL. +/// - parameter method: The HTTP method. `.get` by default. +/// - parameter parameters: The parameters. `nil` by default. +/// - parameter encoding: The parameter encoding. `URLEncoding.default` by default. +/// - parameter headers: The HTTP headers. `nil` by default. +/// +/// - returns: The created `DataRequest`. +@discardableResult +public func request( + _ url: URLConvertible, + method: HTTPMethod = .get, + parameters: Parameters? = nil, + encoding: ParameterEncoding = URLEncoding.default, + headers: HTTPHeaders? = nil) + -> DataRequest +{ + return SessionManager.default.request( + url, + method: method, + parameters: parameters, + encoding: encoding, + headers: headers + ) +} + +/// Creates a `DataRequest` using the default `SessionManager` to retrieve the contents of a URL based on the +/// specified `urlRequest`. +/// +/// - parameter urlRequest: The URL request +/// +/// - returns: The created `DataRequest`. +@discardableResult +public func request(_ urlRequest: URLRequestConvertible) -> DataRequest { + return SessionManager.default.request(urlRequest) +} + +// MARK: - Download Request + +// MARK: URL Request + +/// Creates a `DownloadRequest` using the default `SessionManager` to retrieve the contents of the specified `url`, +/// `method`, `parameters`, `encoding`, `headers` and save them to the `destination`. +/// +/// If `destination` is not specified, the contents will remain in the temporary location determined by the +/// underlying URL session. +/// +/// - parameter url: The URL. +/// - parameter method: The HTTP method. `.get` by default. +/// - parameter parameters: The parameters. `nil` by default. +/// - parameter encoding: The parameter encoding. `URLEncoding.default` by default. +/// - parameter headers: The HTTP headers. `nil` by default. +/// - parameter destination: The closure used to determine the destination of the downloaded file. `nil` by default. +/// +/// - returns: The created `DownloadRequest`. +@discardableResult +public func download( + _ url: URLConvertible, + method: HTTPMethod = .get, + parameters: Parameters? = nil, + encoding: ParameterEncoding = URLEncoding.default, + headers: HTTPHeaders? = nil, + to destination: DownloadRequest.DownloadFileDestination? = nil) + -> DownloadRequest +{ + return SessionManager.default.download( + url, + method: method, + parameters: parameters, + encoding: encoding, + headers: headers, + to: destination + ) +} + +/// Creates a `DownloadRequest` using the default `SessionManager` to retrieve the contents of a URL based on the +/// specified `urlRequest` and save them to the `destination`. +/// +/// If `destination` is not specified, the contents will remain in the temporary location determined by the +/// underlying URL session. +/// +/// - parameter urlRequest: The URL request. +/// - parameter destination: The closure used to determine the destination of the downloaded file. `nil` by default. +/// +/// - returns: The created `DownloadRequest`. +@discardableResult +public func download( + _ urlRequest: URLRequestConvertible, + to destination: DownloadRequest.DownloadFileDestination? = nil) + -> DownloadRequest +{ + return SessionManager.default.download(urlRequest, to: destination) +} + +// MARK: Resume Data + +/// Creates a `DownloadRequest` using the default `SessionManager` from the `resumeData` produced from a +/// previous request cancellation to retrieve the contents of the original request and save them to the `destination`. +/// +/// If `destination` is not specified, the contents will remain in the temporary location determined by the +/// underlying URL session. +/// +/// On the latest release of all the Apple platforms (iOS 10, macOS 10.12, tvOS 10, watchOS 3), `resumeData` is broken +/// on background URL session configurations. There's an underlying bug in the `resumeData` generation logic where the +/// data is written incorrectly and will always fail to resume the download. For more information about the bug and +/// possible workarounds, please refer to the following Stack Overflow post: +/// +/// - http://stackoverflow.com/a/39347461/1342462 +/// +/// - parameter resumeData: The resume data. This is an opaque data blob produced by `URLSessionDownloadTask` +/// when a task is cancelled. See `URLSession -downloadTask(withResumeData:)` for additional +/// information. +/// - parameter destination: The closure used to determine the destination of the downloaded file. `nil` by default. +/// +/// - returns: The created `DownloadRequest`. +@discardableResult +public func download( + resumingWith resumeData: Data, + to destination: DownloadRequest.DownloadFileDestination? = nil) + -> DownloadRequest +{ + return SessionManager.default.download(resumingWith: resumeData, to: destination) +} + +// MARK: - Upload Request + +// MARK: File + +/// Creates an `UploadRequest` using the default `SessionManager` from the specified `url`, `method` and `headers` +/// for uploading the `file`. +/// +/// - parameter file: The file to upload. +/// - parameter url: The URL. +/// - parameter method: The HTTP method. `.post` by default. +/// - parameter headers: The HTTP headers. `nil` by default. +/// +/// - returns: The created `UploadRequest`. +@discardableResult +public func upload( + _ fileURL: URL, + to url: URLConvertible, + method: HTTPMethod = .post, + headers: HTTPHeaders? = nil) + -> UploadRequest +{ + return SessionManager.default.upload(fileURL, to: url, method: method, headers: headers) +} + +/// Creates a `UploadRequest` using the default `SessionManager` from the specified `urlRequest` for +/// uploading the `file`. +/// +/// - parameter file: The file to upload. +/// - parameter urlRequest: The URL request. +/// +/// - returns: The created `UploadRequest`. +@discardableResult +public func upload(_ fileURL: URL, with urlRequest: URLRequestConvertible) -> UploadRequest { + return SessionManager.default.upload(fileURL, with: urlRequest) +} + +// MARK: Data + +/// Creates an `UploadRequest` using the default `SessionManager` from the specified `url`, `method` and `headers` +/// for uploading the `data`. +/// +/// - parameter data: The data to upload. +/// - parameter url: The URL. +/// - parameter method: The HTTP method. `.post` by default. +/// - parameter headers: The HTTP headers. `nil` by default. +/// +/// - returns: The created `UploadRequest`. +@discardableResult +public func upload( + _ data: Data, + to url: URLConvertible, + method: HTTPMethod = .post, + headers: HTTPHeaders? = nil) + -> UploadRequest +{ + return SessionManager.default.upload(data, to: url, method: method, headers: headers) +} + +/// Creates an `UploadRequest` using the default `SessionManager` from the specified `urlRequest` for +/// uploading the `data`. +/// +/// - parameter data: The data to upload. +/// - parameter urlRequest: The URL request. +/// +/// - returns: The created `UploadRequest`. +@discardableResult +public func upload(_ data: Data, with urlRequest: URLRequestConvertible) -> UploadRequest { + return SessionManager.default.upload(data, with: urlRequest) +} + +// MARK: InputStream + +/// Creates an `UploadRequest` using the default `SessionManager` from the specified `url`, `method` and `headers` +/// for uploading the `stream`. +/// +/// - parameter stream: The stream to upload. +/// - parameter url: The URL. +/// - parameter method: The HTTP method. `.post` by default. +/// - parameter headers: The HTTP headers. `nil` by default. +/// +/// - returns: The created `UploadRequest`. +@discardableResult +public func upload( + _ stream: InputStream, + to url: URLConvertible, + method: HTTPMethod = .post, + headers: HTTPHeaders? = nil) + -> UploadRequest +{ + return SessionManager.default.upload(stream, to: url, method: method, headers: headers) +} + +/// Creates an `UploadRequest` using the default `SessionManager` from the specified `urlRequest` for +/// uploading the `stream`. +/// +/// - parameter urlRequest: The URL request. +/// - parameter stream: The stream to upload. +/// +/// - returns: The created `UploadRequest`. +@discardableResult +public func upload(_ stream: InputStream, with urlRequest: URLRequestConvertible) -> UploadRequest { + return SessionManager.default.upload(stream, with: urlRequest) +} + +// MARK: MultipartFormData + +/// Encodes `multipartFormData` using `encodingMemoryThreshold` with the default `SessionManager` and calls +/// `encodingCompletion` with new `UploadRequest` using the `url`, `method` and `headers`. +/// +/// It is important to understand the memory implications of uploading `MultipartFormData`. If the cummulative +/// payload is small, encoding the data in-memory and directly uploading to a server is the by far the most +/// efficient approach. However, if the payload is too large, encoding the data in-memory could cause your app to +/// be terminated. Larger payloads must first be written to disk using input and output streams to keep the memory +/// footprint low, then the data can be uploaded as a stream from the resulting file. Streaming from disk MUST be +/// used for larger payloads such as video content. +/// +/// The `encodingMemoryThreshold` parameter allows Alamofire to automatically determine whether to encode in-memory +/// or stream from disk. If the content length of the `MultipartFormData` is below the `encodingMemoryThreshold`, +/// encoding takes place in-memory. If the content length exceeds the threshold, the data is streamed to disk +/// during the encoding process. Then the result is uploaded as data or as a stream depending on which encoding +/// technique was used. +/// +/// - parameter multipartFormData: The closure used to append body parts to the `MultipartFormData`. +/// - parameter encodingMemoryThreshold: The encoding memory threshold in bytes. +/// `multipartFormDataEncodingMemoryThreshold` by default. +/// - parameter url: The URL. +/// - parameter method: The HTTP method. `.post` by default. +/// - parameter headers: The HTTP headers. `nil` by default. +/// - parameter encodingCompletion: The closure called when the `MultipartFormData` encoding is complete. +public func upload( + multipartFormData: @escaping (MultipartFormData) -> Void, + usingThreshold encodingMemoryThreshold: UInt64 = SessionManager.multipartFormDataEncodingMemoryThreshold, + to url: URLConvertible, + method: HTTPMethod = .post, + headers: HTTPHeaders? = nil, + encodingCompletion: ((SessionManager.MultipartFormDataEncodingResult) -> Void)?) +{ + return SessionManager.default.upload( + multipartFormData: multipartFormData, + usingThreshold: encodingMemoryThreshold, + to: url, + method: method, + headers: headers, + encodingCompletion: encodingCompletion + ) +} + +/// Encodes `multipartFormData` using `encodingMemoryThreshold` and the default `SessionManager` and +/// calls `encodingCompletion` with new `UploadRequest` using the `urlRequest`. +/// +/// It is important to understand the memory implications of uploading `MultipartFormData`. If the cummulative +/// payload is small, encoding the data in-memory and directly uploading to a server is the by far the most +/// efficient approach. However, if the payload is too large, encoding the data in-memory could cause your app to +/// be terminated. Larger payloads must first be written to disk using input and output streams to keep the memory +/// footprint low, then the data can be uploaded as a stream from the resulting file. Streaming from disk MUST be +/// used for larger payloads such as video content. +/// +/// The `encodingMemoryThreshold` parameter allows Alamofire to automatically determine whether to encode in-memory +/// or stream from disk. If the content length of the `MultipartFormData` is below the `encodingMemoryThreshold`, +/// encoding takes place in-memory. If the content length exceeds the threshold, the data is streamed to disk +/// during the encoding process. Then the result is uploaded as data or as a stream depending on which encoding +/// technique was used. +/// +/// - parameter multipartFormData: The closure used to append body parts to the `MultipartFormData`. +/// - parameter encodingMemoryThreshold: The encoding memory threshold in bytes. +/// `multipartFormDataEncodingMemoryThreshold` by default. +/// - parameter urlRequest: The URL request. +/// - parameter encodingCompletion: The closure called when the `MultipartFormData` encoding is complete. +public func upload( + multipartFormData: @escaping (MultipartFormData) -> Void, + usingThreshold encodingMemoryThreshold: UInt64 = SessionManager.multipartFormDataEncodingMemoryThreshold, + with urlRequest: URLRequestConvertible, + encodingCompletion: ((SessionManager.MultipartFormDataEncodingResult) -> Void)?) +{ + return SessionManager.default.upload( + multipartFormData: multipartFormData, + usingThreshold: encodingMemoryThreshold, + with: urlRequest, + encodingCompletion: encodingCompletion + ) +} + +#if !os(watchOS) + +// MARK: - Stream Request + +// MARK: Hostname and Port + +/// Creates a `StreamRequest` using the default `SessionManager` for bidirectional streaming with the `hostname` +/// and `port`. +/// +/// If `startRequestsImmediately` is `true`, the request will have `resume()` called before being returned. +/// +/// - parameter hostName: The hostname of the server to connect to. +/// - parameter port: The port of the server to connect to. +/// +/// - returns: The created `StreamRequest`. +@discardableResult +@available(iOS 9.0, macOS 10.11, tvOS 9.0, *) +public func stream(withHostName hostName: String, port: Int) -> StreamRequest { + return SessionManager.default.stream(withHostName: hostName, port: port) +} + +// MARK: NetService + +/// Creates a `StreamRequest` using the default `SessionManager` for bidirectional streaming with the `netService`. +/// +/// If `startRequestsImmediately` is `true`, the request will have `resume()` called before being returned. +/// +/// - parameter netService: The net service used to identify the endpoint. +/// +/// - returns: The created `StreamRequest`. +@discardableResult +@available(iOS 9.0, macOS 10.11, tvOS 9.0, *) +public func stream(with netService: NetService) -> StreamRequest { + return SessionManager.default.stream(with: netService) +} + +#endif diff --git a/Pods/Alamofire/Source/DispatchQueue+Alamofire.swift b/Pods/Alamofire/Source/DispatchQueue+Alamofire.swift new file mode 100644 index 0000000..78e214e --- /dev/null +++ b/Pods/Alamofire/Source/DispatchQueue+Alamofire.swift @@ -0,0 +1,37 @@ +// +// DispatchQueue+Alamofire.swift +// +// Copyright (c) 2014-2016 Alamofire Software Foundation (http://alamofire.org/) +// +// Permission is hereby granted, free of charge, to any person obtaining a copy +// of this software and associated documentation files (the "Software"), to deal +// in the Software without restriction, including without limitation the rights +// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +// copies of the Software, and to permit persons to whom the Software is +// furnished to do so, subject to the following conditions: +// +// The above copyright notice and this permission notice shall be included in +// all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN +// THE SOFTWARE. +// + +import Dispatch +import Foundation + +extension DispatchQueue { + static var userInteractive: DispatchQueue { return DispatchQueue.global(qos: .userInteractive) } + static var userInitiated: DispatchQueue { return DispatchQueue.global(qos: .userInitiated) } + static var utility: DispatchQueue { return DispatchQueue.global(qos: .utility) } + static var background: DispatchQueue { return DispatchQueue.global(qos: .background) } + + func after(_ delay: TimeInterval, execute closure: @escaping () -> Void) { + asyncAfter(deadline: .now() + delay, execute: closure) + } +} diff --git a/Pods/Alamofire/Source/MultipartFormData.swift b/Pods/Alamofire/Source/MultipartFormData.swift new file mode 100644 index 0000000..1ce4d19 --- /dev/null +++ b/Pods/Alamofire/Source/MultipartFormData.swift @@ -0,0 +1,581 @@ +// +// MultipartFormData.swift +// +// Copyright (c) 2014-2016 Alamofire Software Foundation (http://alamofire.org/) +// +// Permission is hereby granted, free of charge, to any person obtaining a copy +// of this software and associated documentation files (the "Software"), to deal +// in the Software without restriction, including without limitation the rights +// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +// copies of the Software, and to permit persons to whom the Software is +// furnished to do so, subject to the following conditions: +// +// The above copyright notice and this permission notice shall be included in +// all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN +// THE SOFTWARE. +// + +import Foundation + +#if os(iOS) || os(watchOS) || os(tvOS) +import MobileCoreServices +#elseif os(macOS) +import CoreServices +#endif + +/// Constructs `multipart/form-data` for uploads within an HTTP or HTTPS body. There are currently two ways to encode +/// multipart form data. The first way is to encode the data directly in memory. This is very efficient, but can lead +/// to memory issues if the dataset is too large. The second way is designed for larger datasets and will write all the +/// data to a single file on disk with all the proper boundary segmentation. The second approach MUST be used for +/// larger datasets such as video content, otherwise your app may run out of memory when trying to encode the dataset. +/// +/// For more information on `multipart/form-data` in general, please refer to the RFC-2388 and RFC-2045 specs as well +/// and the w3 form documentation. +/// +/// - https://www.ietf.org/rfc/rfc2388.txt +/// - https://www.ietf.org/rfc/rfc2045.txt +/// - https://www.w3.org/TR/html401/interact/forms.html#h-17.13 +open class MultipartFormData { + + // MARK: - Helper Types + + struct EncodingCharacters { + static let crlf = "\r\n" + } + + struct BoundaryGenerator { + enum BoundaryType { + case initial, encapsulated, final + } + + static func randomBoundary() -> String { + return String(format: "alamofire.boundary.%08x%08x", arc4random(), arc4random()) + } + + static func boundaryData(forBoundaryType boundaryType: BoundaryType, boundary: String) -> Data { + let boundaryText: String + + switch boundaryType { + case .initial: + boundaryText = "--\(boundary)\(EncodingCharacters.crlf)" + case .encapsulated: + boundaryText = "\(EncodingCharacters.crlf)--\(boundary)\(EncodingCharacters.crlf)" + case .final: + boundaryText = "\(EncodingCharacters.crlf)--\(boundary)--\(EncodingCharacters.crlf)" + } + + return boundaryText.data(using: String.Encoding.utf8, allowLossyConversion: false)! + } + } + + class BodyPart { + let headers: HTTPHeaders + let bodyStream: InputStream + let bodyContentLength: UInt64 + var hasInitialBoundary = false + var hasFinalBoundary = false + + init(headers: HTTPHeaders, bodyStream: InputStream, bodyContentLength: UInt64) { + self.headers = headers + self.bodyStream = bodyStream + self.bodyContentLength = bodyContentLength + } + } + + // MARK: - Properties + + /// The `Content-Type` header value containing the boundary used to generate the `multipart/form-data`. + open var contentType: String { return "multipart/form-data; boundary=\(boundary)" } + + /// The content length of all body parts used to generate the `multipart/form-data` not including the boundaries. + public var contentLength: UInt64 { return bodyParts.reduce(0) { $0 + $1.bodyContentLength } } + + /// The boundary used to separate the body parts in the encoded form data. + public let boundary: String + + private var bodyParts: [BodyPart] + private var bodyPartError: AFError? + private let streamBufferSize: Int + + // MARK: - Lifecycle + + /// Creates a multipart form data object. + /// + /// - returns: The multipart form data object. + public init() { + self.boundary = BoundaryGenerator.randomBoundary() + self.bodyParts = [] + + /// + /// The optimal read/write buffer size in bytes for input and output streams is 1024 (1KB). For more + /// information, please refer to the following article: + /// - https://developer.apple.com/library/mac/documentation/Cocoa/Conceptual/Streams/Articles/ReadingInputStreams.html + /// + + self.streamBufferSize = 1024 + } + + // MARK: - Body Parts + + /// Creates a body part from the data and appends it to the multipart form data object. + /// + /// The body part data will be encoded using the following format: + /// + /// - `Content-Disposition: form-data; name=#{name}` (HTTP Header) + /// - Encoded data + /// - Multipart form boundary + /// + /// - parameter data: The data to encode into the multipart form data. + /// - parameter name: The name to associate with the data in the `Content-Disposition` HTTP header. + public func append(_ data: Data, withName name: String) { + let headers = contentHeaders(withName: name) + let stream = InputStream(data: data) + let length = UInt64(data.count) + + append(stream, withLength: length, headers: headers) + } + + /// Creates a body part from the data and appends it to the multipart form data object. + /// + /// The body part data will be encoded using the following format: + /// + /// - `Content-Disposition: form-data; name=#{name}` (HTTP Header) + /// - `Content-Type: #{generated mimeType}` (HTTP Header) + /// - Encoded data + /// - Multipart form boundary + /// + /// - parameter data: The data to encode into the multipart form data. + /// - parameter name: The name to associate with the data in the `Content-Disposition` HTTP header. + /// - parameter mimeType: The MIME type to associate with the data content type in the `Content-Type` HTTP header. + public func append(_ data: Data, withName name: String, mimeType: String) { + let headers = contentHeaders(withName: name, mimeType: mimeType) + let stream = InputStream(data: data) + let length = UInt64(data.count) + + append(stream, withLength: length, headers: headers) + } + + /// Creates a body part from the data and appends it to the multipart form data object. + /// + /// The body part data will be encoded using the following format: + /// + /// - `Content-Disposition: form-data; name=#{name}; filename=#{filename}` (HTTP Header) + /// - `Content-Type: #{mimeType}` (HTTP Header) + /// - Encoded file data + /// - Multipart form boundary + /// + /// - parameter data: The data to encode into the multipart form data. + /// - parameter name: The name to associate with the data in the `Content-Disposition` HTTP header. + /// - parameter fileName: The filename to associate with the data in the `Content-Disposition` HTTP header. + /// - parameter mimeType: The MIME type to associate with the data in the `Content-Type` HTTP header. + public func append(_ data: Data, withName name: String, fileName: String, mimeType: String) { + let headers = contentHeaders(withName: name, fileName: fileName, mimeType: mimeType) + let stream = InputStream(data: data) + let length = UInt64(data.count) + + append(stream, withLength: length, headers: headers) + } + + /// Creates a body part from the file and appends it to the multipart form data object. + /// + /// The body part data will be encoded using the following format: + /// + /// - `Content-Disposition: form-data; name=#{name}; filename=#{generated filename}` (HTTP Header) + /// - `Content-Type: #{generated mimeType}` (HTTP Header) + /// - Encoded file data + /// - Multipart form boundary + /// + /// The filename in the `Content-Disposition` HTTP header is generated from the last path component of the + /// `fileURL`. The `Content-Type` HTTP header MIME type is generated by mapping the `fileURL` extension to the + /// system associated MIME type. + /// + /// - parameter fileURL: The URL of the file whose content will be encoded into the multipart form data. + /// - parameter name: The name to associate with the file content in the `Content-Disposition` HTTP header. + public func append(_ fileURL: URL, withName name: String) { + let fileName = fileURL.lastPathComponent + let pathExtension = fileURL.pathExtension + + if !fileName.isEmpty && !pathExtension.isEmpty { + let mime = mimeType(forPathExtension: pathExtension) + append(fileURL, withName: name, fileName: fileName, mimeType: mime) + } else { + setBodyPartError(withReason: .bodyPartFilenameInvalid(in: fileURL)) + } + } + + /// Creates a body part from the file and appends it to the multipart form data object. + /// + /// The body part data will be encoded using the following format: + /// + /// - Content-Disposition: form-data; name=#{name}; filename=#{filename} (HTTP Header) + /// - Content-Type: #{mimeType} (HTTP Header) + /// - Encoded file data + /// - Multipart form boundary + /// + /// - parameter fileURL: The URL of the file whose content will be encoded into the multipart form data. + /// - parameter name: The name to associate with the file content in the `Content-Disposition` HTTP header. + /// - parameter fileName: The filename to associate with the file content in the `Content-Disposition` HTTP header. + /// - parameter mimeType: The MIME type to associate with the file content in the `Content-Type` HTTP header. + public func append(_ fileURL: URL, withName name: String, fileName: String, mimeType: String) { + let headers = contentHeaders(withName: name, fileName: fileName, mimeType: mimeType) + + //============================================================ + // Check 1 - is file URL? + //============================================================ + + guard fileURL.isFileURL else { + setBodyPartError(withReason: .bodyPartURLInvalid(url: fileURL)) + return + } + + //============================================================ + // Check 2 - is file URL reachable? + //============================================================ + + do { + let isReachable = try fileURL.checkPromisedItemIsReachable() + guard isReachable else { + setBodyPartError(withReason: .bodyPartFileNotReachable(at: fileURL)) + return + } + } catch { + setBodyPartError(withReason: .bodyPartFileNotReachableWithError(atURL: fileURL, error: error)) + return + } + + //============================================================ + // Check 3 - is file URL a directory? + //============================================================ + + var isDirectory: ObjCBool = false + let path = fileURL.path + + guard FileManager.default.fileExists(atPath: path, isDirectory: &isDirectory) && !isDirectory.boolValue else + { + setBodyPartError(withReason: .bodyPartFileIsDirectory(at: fileURL)) + return + } + + //============================================================ + // Check 4 - can the file size be extracted? + //============================================================ + + let bodyContentLength: UInt64 + + do { + guard let fileSize = try FileManager.default.attributesOfItem(atPath: path)[.size] as? NSNumber else { + setBodyPartError(withReason: .bodyPartFileSizeNotAvailable(at: fileURL)) + return + } + + bodyContentLength = fileSize.uint64Value + } + catch { + setBodyPartError(withReason: .bodyPartFileSizeQueryFailedWithError(forURL: fileURL, error: error)) + return + } + + //============================================================ + // Check 5 - can a stream be created from file URL? + //============================================================ + + guard let stream = InputStream(url: fileURL) else { + setBodyPartError(withReason: .bodyPartInputStreamCreationFailed(for: fileURL)) + return + } + + append(stream, withLength: bodyContentLength, headers: headers) + } + + /// Creates a body part from the stream and appends it to the multipart form data object. + /// + /// The body part data will be encoded using the following format: + /// + /// - `Content-Disposition: form-data; name=#{name}; filename=#{filename}` (HTTP Header) + /// - `Content-Type: #{mimeType}` (HTTP Header) + /// - Encoded stream data + /// - Multipart form boundary + /// + /// - parameter stream: The input stream to encode in the multipart form data. + /// - parameter length: The content length of the stream. + /// - parameter name: The name to associate with the stream content in the `Content-Disposition` HTTP header. + /// - parameter fileName: The filename to associate with the stream content in the `Content-Disposition` HTTP header. + /// - parameter mimeType: The MIME type to associate with the stream content in the `Content-Type` HTTP header. + public func append( + _ stream: InputStream, + withLength length: UInt64, + name: String, + fileName: String, + mimeType: String) + { + let headers = contentHeaders(withName: name, fileName: fileName, mimeType: mimeType) + append(stream, withLength: length, headers: headers) + } + + /// Creates a body part with the headers, stream and length and appends it to the multipart form data object. + /// + /// The body part data will be encoded using the following format: + /// + /// - HTTP headers + /// - Encoded stream data + /// - Multipart form boundary + /// + /// - parameter stream: The input stream to encode in the multipart form data. + /// - parameter length: The content length of the stream. + /// - parameter headers: The HTTP headers for the body part. + public func append(_ stream: InputStream, withLength length: UInt64, headers: HTTPHeaders) { + let bodyPart = BodyPart(headers: headers, bodyStream: stream, bodyContentLength: length) + bodyParts.append(bodyPart) + } + + // MARK: - Data Encoding + + /// Encodes all the appended body parts into a single `Data` value. + /// + /// It is important to note that this method will load all the appended body parts into memory all at the same + /// time. This method should only be used when the encoded data will have a small memory footprint. For large data + /// cases, please use the `writeEncodedDataToDisk(fileURL:completionHandler:)` method. + /// + /// - throws: An `AFError` if encoding encounters an error. + /// + /// - returns: The encoded `Data` if encoding is successful. + public func encode() throws -> Data { + if let bodyPartError = bodyPartError { + throw bodyPartError + } + + var encoded = Data() + + bodyParts.first?.hasInitialBoundary = true + bodyParts.last?.hasFinalBoundary = true + + for bodyPart in bodyParts { + let encodedData = try encode(bodyPart) + encoded.append(encodedData) + } + + return encoded + } + + /// Writes the appended body parts into the given file URL. + /// + /// This process is facilitated by reading and writing with input and output streams, respectively. Thus, + /// this approach is very memory efficient and should be used for large body part data. + /// + /// - parameter fileURL: The file URL to write the multipart form data into. + /// + /// - throws: An `AFError` if encoding encounters an error. + public func writeEncodedData(to fileURL: URL) throws { + if let bodyPartError = bodyPartError { + throw bodyPartError + } + + if FileManager.default.fileExists(atPath: fileURL.path) { + throw AFError.multipartEncodingFailed(reason: .outputStreamFileAlreadyExists(at: fileURL)) + } else if !fileURL.isFileURL { + throw AFError.multipartEncodingFailed(reason: .outputStreamURLInvalid(url: fileURL)) + } + + guard let outputStream = OutputStream(url: fileURL, append: false) else { + throw AFError.multipartEncodingFailed(reason: .outputStreamCreationFailed(for: fileURL)) + } + + outputStream.open() + defer { outputStream.close() } + + self.bodyParts.first?.hasInitialBoundary = true + self.bodyParts.last?.hasFinalBoundary = true + + for bodyPart in self.bodyParts { + try write(bodyPart, to: outputStream) + } + } + + // MARK: - Private - Body Part Encoding + + private func encode(_ bodyPart: BodyPart) throws -> Data { + var encoded = Data() + + let initialData = bodyPart.hasInitialBoundary ? initialBoundaryData() : encapsulatedBoundaryData() + encoded.append(initialData) + + let headerData = encodeHeaders(for: bodyPart) + encoded.append(headerData) + + let bodyStreamData = try encodeBodyStream(for: bodyPart) + encoded.append(bodyStreamData) + + if bodyPart.hasFinalBoundary { + encoded.append(finalBoundaryData()) + } + + return encoded + } + + private func encodeHeaders(for bodyPart: BodyPart) -> Data { + var headerText = "" + + for (key, value) in bodyPart.headers { + headerText += "\(key): \(value)\(EncodingCharacters.crlf)" + } + headerText += EncodingCharacters.crlf + + return headerText.data(using: String.Encoding.utf8, allowLossyConversion: false)! + } + + private func encodeBodyStream(for bodyPart: BodyPart) throws -> Data { + let inputStream = bodyPart.bodyStream + inputStream.open() + defer { inputStream.close() } + + var encoded = Data() + + while inputStream.hasBytesAvailable { + var buffer = [UInt8](repeating: 0, count: streamBufferSize) + let bytesRead = inputStream.read(&buffer, maxLength: streamBufferSize) + + if let error = inputStream.streamError { + throw AFError.multipartEncodingFailed(reason: .inputStreamReadFailed(error: error)) + } + + if bytesRead > 0 { + encoded.append(buffer, count: bytesRead) + } else { + break + } + } + + return encoded + } + + // MARK: - Private - Writing Body Part to Output Stream + + private func write(_ bodyPart: BodyPart, to outputStream: OutputStream) throws { + try writeInitialBoundaryData(for: bodyPart, to: outputStream) + try writeHeaderData(for: bodyPart, to: outputStream) + try writeBodyStream(for: bodyPart, to: outputStream) + try writeFinalBoundaryData(for: bodyPart, to: outputStream) + } + + private func writeInitialBoundaryData(for bodyPart: BodyPart, to outputStream: OutputStream) throws { + let initialData = bodyPart.hasInitialBoundary ? initialBoundaryData() : encapsulatedBoundaryData() + return try write(initialData, to: outputStream) + } + + private func writeHeaderData(for bodyPart: BodyPart, to outputStream: OutputStream) throws { + let headerData = encodeHeaders(for: bodyPart) + return try write(headerData, to: outputStream) + } + + private func writeBodyStream(for bodyPart: BodyPart, to outputStream: OutputStream) throws { + let inputStream = bodyPart.bodyStream + + inputStream.open() + defer { inputStream.close() } + + while inputStream.hasBytesAvailable { + var buffer = [UInt8](repeating: 0, count: streamBufferSize) + let bytesRead = inputStream.read(&buffer, maxLength: streamBufferSize) + + if let streamError = inputStream.streamError { + throw AFError.multipartEncodingFailed(reason: .inputStreamReadFailed(error: streamError)) + } + + if bytesRead > 0 { + if buffer.count != bytesRead { + buffer = Array(buffer[0.. 0, outputStream.hasSpaceAvailable { + let bytesWritten = outputStream.write(buffer, maxLength: bytesToWrite) + + if let error = outputStream.streamError { + throw AFError.multipartEncodingFailed(reason: .outputStreamWriteFailed(error: error)) + } + + bytesToWrite -= bytesWritten + + if bytesToWrite > 0 { + buffer = Array(buffer[bytesWritten.. String { + if + let id = UTTypeCreatePreferredIdentifierForTag(kUTTagClassFilenameExtension, pathExtension as CFString, nil)?.takeRetainedValue(), + let contentType = UTTypeCopyPreferredTagWithClass(id, kUTTagClassMIMEType)?.takeRetainedValue() + { + return contentType as String + } + + return "application/octet-stream" + } + + // MARK: - Private - Content Headers + + private func contentHeaders(withName name: String, fileName: String? = nil, mimeType: String? = nil) -> [String: String] { + var disposition = "form-data; name=\"\(name)\"" + if let fileName = fileName { disposition += "; filename=\"\(fileName)\"" } + + var headers = ["Content-Disposition": disposition] + if let mimeType = mimeType { headers["Content-Type"] = mimeType } + + return headers + } + + // MARK: - Private - Boundary Encoding + + private func initialBoundaryData() -> Data { + return BoundaryGenerator.boundaryData(forBoundaryType: .initial, boundary: boundary) + } + + private func encapsulatedBoundaryData() -> Data { + return BoundaryGenerator.boundaryData(forBoundaryType: .encapsulated, boundary: boundary) + } + + private func finalBoundaryData() -> Data { + return BoundaryGenerator.boundaryData(forBoundaryType: .final, boundary: boundary) + } + + // MARK: - Private - Errors + + private func setBodyPartError(withReason reason: AFError.MultipartEncodingFailureReason) { + guard bodyPartError == nil else { return } + bodyPartError = AFError.multipartEncodingFailed(reason: reason) + } +} diff --git a/Pods/Alamofire/Source/NetworkReachabilityManager.swift b/Pods/Alamofire/Source/NetworkReachabilityManager.swift new file mode 100644 index 0000000..888818d --- /dev/null +++ b/Pods/Alamofire/Source/NetworkReachabilityManager.swift @@ -0,0 +1,230 @@ +// +// NetworkReachabilityManager.swift +// +// Copyright (c) 2014-2016 Alamofire Software Foundation (http://alamofire.org/) +// +// Permission is hereby granted, free of charge, to any person obtaining a copy +// of this software and associated documentation files (the "Software"), to deal +// in the Software without restriction, including without limitation the rights +// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +// copies of the Software, and to permit persons to whom the Software is +// furnished to do so, subject to the following conditions: +// +// The above copyright notice and this permission notice shall be included in +// all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN +// THE SOFTWARE. +// + +#if !os(watchOS) + +import Foundation +import SystemConfiguration + +/// The `NetworkReachabilityManager` class listens for reachability changes of hosts and addresses for both WWAN and +/// WiFi network interfaces. +/// +/// Reachability can be used to determine background information about why a network operation failed, or to retry +/// network requests when a connection is established. It should not be used to prevent a user from initiating a network +/// request, as it's possible that an initial request may be required to establish reachability. +public class NetworkReachabilityManager { + /// Defines the various states of network reachability. + /// + /// - unknown: It is unknown whether the network is reachable. + /// - notReachable: The network is not reachable. + /// - reachable: The network is reachable. + public enum NetworkReachabilityStatus { + case unknown + case notReachable + case reachable(ConnectionType) + } + + /// Defines the various connection types detected by reachability flags. + /// + /// - ethernetOrWiFi: The connection type is either over Ethernet or WiFi. + /// - wwan: The connection type is a WWAN connection. + public enum ConnectionType { + case ethernetOrWiFi + case wwan + } + + /// A closure executed when the network reachability status changes. The closure takes a single argument: the + /// network reachability status. + public typealias Listener = (NetworkReachabilityStatus) -> Void + + // MARK: - Properties + + /// Whether the network is currently reachable. + public var isReachable: Bool { return isReachableOnWWAN || isReachableOnEthernetOrWiFi } + + /// Whether the network is currently reachable over the WWAN interface. + public var isReachableOnWWAN: Bool { return networkReachabilityStatus == .reachable(.wwan) } + + /// Whether the network is currently reachable over Ethernet or WiFi interface. + public var isReachableOnEthernetOrWiFi: Bool { return networkReachabilityStatus == .reachable(.ethernetOrWiFi) } + + /// The current network reachability status. + public var networkReachabilityStatus: NetworkReachabilityStatus { + guard let flags = self.flags else { return .unknown } + return networkReachabilityStatusForFlags(flags) + } + + /// The dispatch queue to execute the `listener` closure on. + public var listenerQueue: DispatchQueue = DispatchQueue.main + + /// A closure executed when the network reachability status changes. + public var listener: Listener? + + private var flags: SCNetworkReachabilityFlags? { + var flags = SCNetworkReachabilityFlags() + + if SCNetworkReachabilityGetFlags(reachability, &flags) { + return flags + } + + return nil + } + + private let reachability: SCNetworkReachability + private var previousFlags: SCNetworkReachabilityFlags + + // MARK: - Initialization + + /// Creates a `NetworkReachabilityManager` instance with the specified host. + /// + /// - parameter host: The host used to evaluate network reachability. + /// + /// - returns: The new `NetworkReachabilityManager` instance. + public convenience init?(host: String) { + guard let reachability = SCNetworkReachabilityCreateWithName(nil, host) else { return nil } + self.init(reachability: reachability) + } + + /// Creates a `NetworkReachabilityManager` instance that monitors the address 0.0.0.0. + /// + /// Reachability treats the 0.0.0.0 address as a special token that causes it to monitor the general routing + /// status of the device, both IPv4 and IPv6. + /// + /// - returns: The new `NetworkReachabilityManager` instance. + public convenience init?() { + var address = sockaddr_in() + address.sin_len = UInt8(MemoryLayout.size) + address.sin_family = sa_family_t(AF_INET) + + guard let reachability = withUnsafePointer(to: &address, { pointer in + return pointer.withMemoryRebound(to: sockaddr.self, capacity: MemoryLayout.size) { + return SCNetworkReachabilityCreateWithAddress(nil, $0) + } + }) else { return nil } + + self.init(reachability: reachability) + } + + private init(reachability: SCNetworkReachability) { + self.reachability = reachability + self.previousFlags = SCNetworkReachabilityFlags() + } + + deinit { + stopListening() + } + + // MARK: - Listening + + /// Starts listening for changes in network reachability status. + /// + /// - returns: `true` if listening was started successfully, `false` otherwise. + @discardableResult + public func startListening() -> Bool { + var context = SCNetworkReachabilityContext(version: 0, info: nil, retain: nil, release: nil, copyDescription: nil) + context.info = Unmanaged.passUnretained(self).toOpaque() + + let callbackEnabled = SCNetworkReachabilitySetCallback( + reachability, + { (_, flags, info) in + let reachability = Unmanaged.fromOpaque(info!).takeUnretainedValue() + reachability.notifyListener(flags) + }, + &context + ) + + let queueEnabled = SCNetworkReachabilitySetDispatchQueue(reachability, listenerQueue) + + listenerQueue.async { + self.previousFlags = SCNetworkReachabilityFlags() + self.notifyListener(self.flags ?? SCNetworkReachabilityFlags()) + } + + return callbackEnabled && queueEnabled + } + + /// Stops listening for changes in network reachability status. + public func stopListening() { + SCNetworkReachabilitySetCallback(reachability, nil, nil) + SCNetworkReachabilitySetDispatchQueue(reachability, nil) + } + + // MARK: - Internal - Listener Notification + + func notifyListener(_ flags: SCNetworkReachabilityFlags) { + guard previousFlags != flags else { return } + previousFlags = flags + + listener?(networkReachabilityStatusForFlags(flags)) + } + + // MARK: - Internal - Network Reachability Status + + func networkReachabilityStatusForFlags(_ flags: SCNetworkReachabilityFlags) -> NetworkReachabilityStatus { + guard flags.contains(.reachable) else { return .notReachable } + + var networkStatus: NetworkReachabilityStatus = .notReachable + + if !flags.contains(.connectionRequired) { networkStatus = .reachable(.ethernetOrWiFi) } + + if flags.contains(.connectionOnDemand) || flags.contains(.connectionOnTraffic) { + if !flags.contains(.interventionRequired) { networkStatus = .reachable(.ethernetOrWiFi) } + } + + #if os(iOS) + if flags.contains(.isWWAN) { networkStatus = .reachable(.wwan) } + #endif + + return networkStatus + } +} + +// MARK: - + +extension NetworkReachabilityManager.NetworkReachabilityStatus: Equatable {} + +/// Returns whether the two network reachability status values are equal. +/// +/// - parameter lhs: The left-hand side value to compare. +/// - parameter rhs: The right-hand side value to compare. +/// +/// - returns: `true` if the two values are equal, `false` otherwise. +public func ==( + lhs: NetworkReachabilityManager.NetworkReachabilityStatus, + rhs: NetworkReachabilityManager.NetworkReachabilityStatus) + -> Bool +{ + switch (lhs, rhs) { + case (.unknown, .unknown): + return true + case (.notReachable, .notReachable): + return true + case let (.reachable(lhsConnectionType), .reachable(rhsConnectionType)): + return lhsConnectionType == rhsConnectionType + default: + return false + } +} + +#endif diff --git a/Pods/Alamofire/Source/Notifications.swift b/Pods/Alamofire/Source/Notifications.swift new file mode 100644 index 0000000..81f6e37 --- /dev/null +++ b/Pods/Alamofire/Source/Notifications.swift @@ -0,0 +1,52 @@ +// +// Notifications.swift +// +// Copyright (c) 2014-2016 Alamofire Software Foundation (http://alamofire.org/) +// +// Permission is hereby granted, free of charge, to any person obtaining a copy +// of this software and associated documentation files (the "Software"), to deal +// in the Software without restriction, including without limitation the rights +// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +// copies of the Software, and to permit persons to whom the Software is +// furnished to do so, subject to the following conditions: +// +// The above copyright notice and this permission notice shall be included in +// all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN +// THE SOFTWARE. +// + +import Foundation + +extension Notification.Name { + /// Used as a namespace for all `URLSessionTask` related notifications. + public struct Task { + /// Posted when a `URLSessionTask` is resumed. The notification `object` contains the resumed `URLSessionTask`. + public static let DidResume = Notification.Name(rawValue: "org.alamofire.notification.name.task.didResume") + + /// Posted when a `URLSessionTask` is suspended. The notification `object` contains the suspended `URLSessionTask`. + public static let DidSuspend = Notification.Name(rawValue: "org.alamofire.notification.name.task.didSuspend") + + /// Posted when a `URLSessionTask` is cancelled. The notification `object` contains the cancelled `URLSessionTask`. + public static let DidCancel = Notification.Name(rawValue: "org.alamofire.notification.name.task.didCancel") + + /// Posted when a `URLSessionTask` is completed. The notification `object` contains the completed `URLSessionTask`. + public static let DidComplete = Notification.Name(rawValue: "org.alamofire.notification.name.task.didComplete") + } +} + +// MARK: - + +extension Notification { + /// Used as a namespace for all `Notification` user info dictionary keys. + public struct Key { + /// User info dictionary key representing the `URLSessionTask` associated with the notification. + public static let Task = "org.alamofire.notification.key.task" + } +} diff --git a/Pods/Alamofire/Source/ParameterEncoding.swift b/Pods/Alamofire/Source/ParameterEncoding.swift new file mode 100644 index 0000000..242f6a8 --- /dev/null +++ b/Pods/Alamofire/Source/ParameterEncoding.swift @@ -0,0 +1,433 @@ +// +// ParameterEncoding.swift +// +// Copyright (c) 2014-2016 Alamofire Software Foundation (http://alamofire.org/) +// +// Permission is hereby granted, free of charge, to any person obtaining a copy +// of this software and associated documentation files (the "Software"), to deal +// in the Software without restriction, including without limitation the rights +// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +// copies of the Software, and to permit persons to whom the Software is +// furnished to do so, subject to the following conditions: +// +// The above copyright notice and this permission notice shall be included in +// all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN +// THE SOFTWARE. +// + +import Foundation + +/// HTTP method definitions. +/// +/// See https://tools.ietf.org/html/rfc7231#section-4.3 +public enum HTTPMethod: String { + case options = "OPTIONS" + case get = "GET" + case head = "HEAD" + case post = "POST" + case put = "PUT" + case patch = "PATCH" + case delete = "DELETE" + case trace = "TRACE" + case connect = "CONNECT" +} + +// MARK: - + +/// A dictionary of parameters to apply to a `URLRequest`. +public typealias Parameters = [String: Any] + +/// A type used to define how a set of parameters are applied to a `URLRequest`. +public protocol ParameterEncoding { + /// Creates a URL request by encoding parameters and applying them onto an existing request. + /// + /// - parameter urlRequest: The request to have parameters applied. + /// - parameter parameters: The parameters to apply. + /// + /// - throws: An `AFError.parameterEncodingFailed` error if encoding fails. + /// + /// - returns: The encoded request. + func encode(_ urlRequest: URLRequestConvertible, with parameters: Parameters?) throws -> URLRequest +} + +// MARK: - + +/// Creates a url-encoded query string to be set as or appended to any existing URL query string or set as the HTTP +/// body of the URL request. Whether the query string is set or appended to any existing URL query string or set as +/// the HTTP body depends on the destination of the encoding. +/// +/// The `Content-Type` HTTP header field of an encoded request with HTTP body is set to +/// `application/x-www-form-urlencoded; charset=utf-8`. Since there is no published specification for how to encode +/// collection types, the convention of appending `[]` to the key for array values (`foo[]=1&foo[]=2`), and appending +/// the key surrounded by square brackets for nested dictionary values (`foo[bar]=baz`). +public struct URLEncoding: ParameterEncoding { + + // MARK: Helper Types + + /// Defines whether the url-encoded query string is applied to the existing query string or HTTP body of the + /// resulting URL request. + /// + /// - methodDependent: Applies encoded query string result to existing query string for `GET`, `HEAD` and `DELETE` + /// requests and sets as the HTTP body for requests with any other HTTP method. + /// - queryString: Sets or appends encoded query string result to existing query string. + /// - httpBody: Sets encoded query string result as the HTTP body of the URL request. + public enum Destination { + case methodDependent, queryString, httpBody + } + + // MARK: Properties + + /// Returns a default `URLEncoding` instance. + public static var `default`: URLEncoding { return URLEncoding() } + + /// Returns a `URLEncoding` instance with a `.methodDependent` destination. + public static var methodDependent: URLEncoding { return URLEncoding() } + + /// Returns a `URLEncoding` instance with a `.queryString` destination. + public static var queryString: URLEncoding { return URLEncoding(destination: .queryString) } + + /// Returns a `URLEncoding` instance with an `.httpBody` destination. + public static var httpBody: URLEncoding { return URLEncoding(destination: .httpBody) } + + /// The destination defining where the encoded query string is to be applied to the URL request. + public let destination: Destination + + // MARK: Initialization + + /// Creates a `URLEncoding` instance using the specified destination. + /// + /// - parameter destination: The destination defining where the encoded query string is to be applied. + /// + /// - returns: The new `URLEncoding` instance. + public init(destination: Destination = .methodDependent) { + self.destination = destination + } + + // MARK: Encoding + + /// Creates a URL request by encoding parameters and applying them onto an existing request. + /// + /// - parameter urlRequest: The request to have parameters applied. + /// - parameter parameters: The parameters to apply. + /// + /// - throws: An `Error` if the encoding process encounters an error. + /// + /// - returns: The encoded request. + public func encode(_ urlRequest: URLRequestConvertible, with parameters: Parameters?) throws -> URLRequest { + var urlRequest = try urlRequest.asURLRequest() + + guard let parameters = parameters else { return urlRequest } + + if let method = HTTPMethod(rawValue: urlRequest.httpMethod ?? "GET"), encodesParametersInURL(with: method) { + guard let url = urlRequest.url else { + throw AFError.parameterEncodingFailed(reason: .missingURL) + } + + if var urlComponents = URLComponents(url: url, resolvingAgainstBaseURL: false), !parameters.isEmpty { + let percentEncodedQuery = (urlComponents.percentEncodedQuery.map { $0 + "&" } ?? "") + query(parameters) + urlComponents.percentEncodedQuery = percentEncodedQuery + urlRequest.url = urlComponents.url + } + } else { + if urlRequest.value(forHTTPHeaderField: "Content-Type") == nil { + urlRequest.setValue("application/x-www-form-urlencoded; charset=utf-8", forHTTPHeaderField: "Content-Type") + } + + urlRequest.httpBody = query(parameters).data(using: .utf8, allowLossyConversion: false) + } + + return urlRequest + } + + /// Creates percent-escaped, URL encoded query string components from the given key-value pair using recursion. + /// + /// - parameter key: The key of the query component. + /// - parameter value: The value of the query component. + /// + /// - returns: The percent-escaped, URL encoded query string components. + public func queryComponents(fromKey key: String, value: Any) -> [(String, String)] { + var components: [(String, String)] = [] + + if let dictionary = value as? [String: Any] { + for (nestedKey, value) in dictionary { + components += queryComponents(fromKey: "\(key)[\(nestedKey)]", value: value) + } + } else if let array = value as? [Any] { + for value in array { + components += queryComponents(fromKey: "\(key)[]", value: value) + } + } else if let value = value as? NSNumber { + if value.isBool { + components.append((escape(key), escape((value.boolValue ? "1" : "0")))) + } else { + components.append((escape(key), escape("\(value)"))) + } + } else if let bool = value as? Bool { + components.append((escape(key), escape((bool ? "1" : "0")))) + } else { + components.append((escape(key), escape("\(value)"))) + } + + return components + } + + /// Returns a percent-escaped string following RFC 3986 for a query string key or value. + /// + /// RFC 3986 states that the following characters are "reserved" characters. + /// + /// - General Delimiters: ":", "#", "[", "]", "@", "?", "/" + /// - Sub-Delimiters: "!", "$", "&", "'", "(", ")", "*", "+", ",", ";", "=" + /// + /// In RFC 3986 - Section 3.4, it states that the "?" and "/" characters should not be escaped to allow + /// query strings to include a URL. Therefore, all "reserved" characters with the exception of "?" and "/" + /// should be percent-escaped in the query string. + /// + /// - parameter string: The string to be percent-escaped. + /// + /// - returns: The percent-escaped string. + public func escape(_ string: String) -> String { + let generalDelimitersToEncode = ":#[]@" // does not include "?" or "/" due to RFC 3986 - Section 3.4 + let subDelimitersToEncode = "!$&'()*+,;=" + + var allowedCharacterSet = CharacterSet.urlQueryAllowed + allowedCharacterSet.remove(charactersIn: "\(generalDelimitersToEncode)\(subDelimitersToEncode)") + + var escaped = "" + + //========================================================================================================== + // + // Batching is required for escaping due to an internal bug in iOS 8.1 and 8.2. Encoding more than a few + // hundred Chinese characters causes various malloc error crashes. To avoid this issue until iOS 8 is no + // longer supported, batching MUST be used for encoding. This introduces roughly a 20% overhead. For more + // info, please refer to: + // + // - https://github.com/Alamofire/Alamofire/issues/206 + // + //========================================================================================================== + + if #available(iOS 8.3, *) { + escaped = string.addingPercentEncoding(withAllowedCharacters: allowedCharacterSet) ?? string + } else { + let batchSize = 50 + var index = string.startIndex + + while index != string.endIndex { + let startIndex = index + let endIndex = string.index(index, offsetBy: batchSize, limitedBy: string.endIndex) ?? string.endIndex + let range = startIndex.. String { + var components: [(String, String)] = [] + + for key in parameters.keys.sorted(by: <) { + let value = parameters[key]! + components += queryComponents(fromKey: key, value: value) + } + + return components.map { "\($0)=\($1)" }.joined(separator: "&") + } + + private func encodesParametersInURL(with method: HTTPMethod) -> Bool { + switch destination { + case .queryString: + return true + case .httpBody: + return false + default: + break + } + + switch method { + case .get, .head, .delete: + return true + default: + return false + } + } +} + +// MARK: - + +/// Uses `JSONSerialization` to create a JSON representation of the parameters object, which is set as the body of the +/// request. The `Content-Type` HTTP header field of an encoded request is set to `application/json`. +public struct JSONEncoding: ParameterEncoding { + + // MARK: Properties + + /// Returns a `JSONEncoding` instance with default writing options. + public static var `default`: JSONEncoding { return JSONEncoding() } + + /// Returns a `JSONEncoding` instance with `.prettyPrinted` writing options. + public static var prettyPrinted: JSONEncoding { return JSONEncoding(options: .prettyPrinted) } + + /// The options for writing the parameters as JSON data. + public let options: JSONSerialization.WritingOptions + + // MARK: Initialization + + /// Creates a `JSONEncoding` instance using the specified options. + /// + /// - parameter options: The options for writing the parameters as JSON data. + /// + /// - returns: The new `JSONEncoding` instance. + public init(options: JSONSerialization.WritingOptions = []) { + self.options = options + } + + // MARK: Encoding + + /// Creates a URL request by encoding parameters and applying them onto an existing request. + /// + /// - parameter urlRequest: The request to have parameters applied. + /// - parameter parameters: The parameters to apply. + /// + /// - throws: An `Error` if the encoding process encounters an error. + /// + /// - returns: The encoded request. + public func encode(_ urlRequest: URLRequestConvertible, with parameters: Parameters?) throws -> URLRequest { + var urlRequest = try urlRequest.asURLRequest() + + guard let parameters = parameters else { return urlRequest } + + do { + let data = try JSONSerialization.data(withJSONObject: parameters, options: options) + + if urlRequest.value(forHTTPHeaderField: "Content-Type") == nil { + urlRequest.setValue("application/json", forHTTPHeaderField: "Content-Type") + } + + urlRequest.httpBody = data + } catch { + throw AFError.parameterEncodingFailed(reason: .jsonEncodingFailed(error: error)) + } + + return urlRequest + } + + /// Creates a URL request by encoding the JSON object and setting the resulting data on the HTTP body. + /// + /// - parameter urlRequest: The request to apply the JSON object to. + /// - parameter jsonObject: The JSON object to apply to the request. + /// + /// - throws: An `Error` if the encoding process encounters an error. + /// + /// - returns: The encoded request. + public func encode(_ urlRequest: URLRequestConvertible, withJSONObject jsonObject: Any? = nil) throws -> URLRequest { + var urlRequest = try urlRequest.asURLRequest() + + guard let jsonObject = jsonObject else { return urlRequest } + + do { + let data = try JSONSerialization.data(withJSONObject: jsonObject, options: options) + + if urlRequest.value(forHTTPHeaderField: "Content-Type") == nil { + urlRequest.setValue("application/json", forHTTPHeaderField: "Content-Type") + } + + urlRequest.httpBody = data + } catch { + throw AFError.parameterEncodingFailed(reason: .jsonEncodingFailed(error: error)) + } + + return urlRequest + } +} + +// MARK: - + +/// Uses `PropertyListSerialization` to create a plist representation of the parameters object, according to the +/// associated format and write options values, which is set as the body of the request. The `Content-Type` HTTP header +/// field of an encoded request is set to `application/x-plist`. +public struct PropertyListEncoding: ParameterEncoding { + + // MARK: Properties + + /// Returns a default `PropertyListEncoding` instance. + public static var `default`: PropertyListEncoding { return PropertyListEncoding() } + + /// Returns a `PropertyListEncoding` instance with xml formatting and default writing options. + public static var xml: PropertyListEncoding { return PropertyListEncoding(format: .xml) } + + /// Returns a `PropertyListEncoding` instance with binary formatting and default writing options. + public static var binary: PropertyListEncoding { return PropertyListEncoding(format: .binary) } + + /// The property list serialization format. + public let format: PropertyListSerialization.PropertyListFormat + + /// The options for writing the parameters as plist data. + public let options: PropertyListSerialization.WriteOptions + + // MARK: Initialization + + /// Creates a `PropertyListEncoding` instance using the specified format and options. + /// + /// - parameter format: The property list serialization format. + /// - parameter options: The options for writing the parameters as plist data. + /// + /// - returns: The new `PropertyListEncoding` instance. + public init( + format: PropertyListSerialization.PropertyListFormat = .xml, + options: PropertyListSerialization.WriteOptions = 0) + { + self.format = format + self.options = options + } + + // MARK: Encoding + + /// Creates a URL request by encoding parameters and applying them onto an existing request. + /// + /// - parameter urlRequest: The request to have parameters applied. + /// - parameter parameters: The parameters to apply. + /// + /// - throws: An `Error` if the encoding process encounters an error. + /// + /// - returns: The encoded request. + public func encode(_ urlRequest: URLRequestConvertible, with parameters: Parameters?) throws -> URLRequest { + var urlRequest = try urlRequest.asURLRequest() + + guard let parameters = parameters else { return urlRequest } + + do { + let data = try PropertyListSerialization.data( + fromPropertyList: parameters, + format: format, + options: options + ) + + if urlRequest.value(forHTTPHeaderField: "Content-Type") == nil { + urlRequest.setValue("application/x-plist", forHTTPHeaderField: "Content-Type") + } + + urlRequest.httpBody = data + } catch { + throw AFError.parameterEncodingFailed(reason: .propertyListEncodingFailed(error: error)) + } + + return urlRequest + } +} + +// MARK: - + +extension NSNumber { + fileprivate var isBool: Bool { return CFBooleanGetTypeID() == CFGetTypeID(self) } +} diff --git a/Pods/Alamofire/Source/Request.swift b/Pods/Alamofire/Source/Request.swift new file mode 100644 index 0000000..7886495 --- /dev/null +++ b/Pods/Alamofire/Source/Request.swift @@ -0,0 +1,647 @@ +// +// Request.swift +// +// Copyright (c) 2014-2016 Alamofire Software Foundation (http://alamofire.org/) +// +// Permission is hereby granted, free of charge, to any person obtaining a copy +// of this software and associated documentation files (the "Software"), to deal +// in the Software without restriction, including without limitation the rights +// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +// copies of the Software, and to permit persons to whom the Software is +// furnished to do so, subject to the following conditions: +// +// The above copyright notice and this permission notice shall be included in +// all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN +// THE SOFTWARE. +// + +import Foundation + +/// A type that can inspect and optionally adapt a `URLRequest` in some manner if necessary. +public protocol RequestAdapter { + /// Inspects and adapts the specified `URLRequest` in some manner if necessary and returns the result. + /// + /// - parameter urlRequest: The URL request to adapt. + /// + /// - throws: An `Error` if the adaptation encounters an error. + /// + /// - returns: The adapted `URLRequest`. + func adapt(_ urlRequest: URLRequest) throws -> URLRequest +} + +// MARK: - + +/// A closure executed when the `RequestRetrier` determines whether a `Request` should be retried or not. +public typealias RequestRetryCompletion = (_ shouldRetry: Bool, _ timeDelay: TimeInterval) -> Void + +/// A type that determines whether a request should be retried after being executed by the specified session manager +/// and encountering an error. +public protocol RequestRetrier { + /// Determines whether the `Request` should be retried by calling the `completion` closure. + /// + /// This operation is fully asychronous. Any amount of time can be taken to determine whether the request needs + /// to be retried. The one requirement is that the completion closure is called to ensure the request is properly + /// cleaned up after. + /// + /// - parameter manager: The session manager the request was executed on. + /// - parameter request: The request that failed due to the encountered error. + /// - parameter error: The error encountered when executing the request. + /// - parameter completion: The completion closure to be executed when retry decision has been determined. + func should(_ manager: SessionManager, retry request: Request, with error: Error, completion: @escaping RequestRetryCompletion) +} + +// MARK: - + +protocol TaskConvertible { + func task(session: URLSession, adapter: RequestAdapter?, queue: DispatchQueue) throws -> URLSessionTask +} + +/// A dictionary of headers to apply to a `URLRequest`. +public typealias HTTPHeaders = [String: String] + +// MARK: - + +/// Responsible for sending a request and receiving the response and associated data from the server, as well as +/// managing its underlying `URLSessionTask`. +open class Request { + + // MARK: Helper Types + + /// A closure executed when monitoring upload or download progress of a request. + public typealias ProgressHandler = (Progress) -> Void + + enum RequestTask { + case data(TaskConvertible?, URLSessionTask?) + case download(TaskConvertible?, URLSessionTask?) + case upload(TaskConvertible?, URLSessionTask?) + case stream(TaskConvertible?, URLSessionTask?) + } + + // MARK: Properties + + /// The delegate for the underlying task. + open internal(set) var delegate: TaskDelegate { + get { + taskDelegateLock.lock() ; defer { taskDelegateLock.unlock() } + return taskDelegate + } + set { + taskDelegateLock.lock() ; defer { taskDelegateLock.unlock() } + taskDelegate = newValue + } + } + + /// The underlying task. + open var task: URLSessionTask? { return delegate.task } + + /// The session belonging to the underlying task. + open let session: URLSession + + /// The request sent or to be sent to the server. + open var request: URLRequest? { return task?.originalRequest } + + /// The response received from the server, if any. + open var response: HTTPURLResponse? { return task?.response as? HTTPURLResponse } + + /// The number of times the request has been retried. + open internal(set) var retryCount: UInt = 0 + + let originalTask: TaskConvertible? + + var startTime: CFAbsoluteTime? + var endTime: CFAbsoluteTime? + + var validations: [() -> Void] = [] + + private var taskDelegate: TaskDelegate + private var taskDelegateLock = NSLock() + + // MARK: Lifecycle + + init(session: URLSession, requestTask: RequestTask, error: Error? = nil) { + self.session = session + + switch requestTask { + case .data(let originalTask, let task): + taskDelegate = DataTaskDelegate(task: task) + self.originalTask = originalTask + case .download(let originalTask, let task): + taskDelegate = DownloadTaskDelegate(task: task) + self.originalTask = originalTask + case .upload(let originalTask, let task): + taskDelegate = UploadTaskDelegate(task: task) + self.originalTask = originalTask + case .stream(let originalTask, let task): + taskDelegate = TaskDelegate(task: task) + self.originalTask = originalTask + } + + delegate.error = error + delegate.queue.addOperation { self.endTime = CFAbsoluteTimeGetCurrent() } + } + + // MARK: Authentication + + /// Associates an HTTP Basic credential with the request. + /// + /// - parameter user: The user. + /// - parameter password: The password. + /// - parameter persistence: The URL credential persistence. `.ForSession` by default. + /// + /// - returns: The request. + @discardableResult + open func authenticate( + user: String, + password: String, + persistence: URLCredential.Persistence = .forSession) + -> Self + { + let credential = URLCredential(user: user, password: password, persistence: persistence) + return authenticate(usingCredential: credential) + } + + /// Associates a specified credential with the request. + /// + /// - parameter credential: The credential. + /// + /// - returns: The request. + @discardableResult + open func authenticate(usingCredential credential: URLCredential) -> Self { + delegate.credential = credential + return self + } + + /// Returns a base64 encoded basic authentication credential as an authorization header tuple. + /// + /// - parameter user: The user. + /// - parameter password: The password. + /// + /// - returns: A tuple with Authorization header and credential value if encoding succeeds, `nil` otherwise. + open static func authorizationHeader(user: String, password: String) -> (key: String, value: String)? { + guard let data = "\(user):\(password)".data(using: .utf8) else { return nil } + + let credential = data.base64EncodedString(options: []) + + return (key: "Authorization", value: "Basic \(credential)") + } + + // MARK: State + + /// Resumes the request. + open func resume() { + guard let task = task else { delegate.queue.isSuspended = false ; return } + + if startTime == nil { startTime = CFAbsoluteTimeGetCurrent() } + + task.resume() + + NotificationCenter.default.post( + name: Notification.Name.Task.DidResume, + object: self, + userInfo: [Notification.Key.Task: task] + ) + } + + /// Suspends the request. + open func suspend() { + guard let task = task else { return } + + task.suspend() + + NotificationCenter.default.post( + name: Notification.Name.Task.DidSuspend, + object: self, + userInfo: [Notification.Key.Task: task] + ) + } + + /// Cancels the request. + open func cancel() { + guard let task = task else { return } + + task.cancel() + + NotificationCenter.default.post( + name: Notification.Name.Task.DidCancel, + object: self, + userInfo: [Notification.Key.Task: task] + ) + } +} + +// MARK: - CustomStringConvertible + +extension Request: CustomStringConvertible { + /// The textual representation used when written to an output stream, which includes the HTTP method and URL, as + /// well as the response status code if a response has been received. + open var description: String { + var components: [String] = [] + + if let HTTPMethod = request?.httpMethod { + components.append(HTTPMethod) + } + + if let urlString = request?.url?.absoluteString { + components.append(urlString) + } + + if let response = response { + components.append("(\(response.statusCode))") + } + + return components.joined(separator: " ") + } +} + +// MARK: - CustomDebugStringConvertible + +extension Request: CustomDebugStringConvertible { + /// The textual representation used when written to an output stream, in the form of a cURL command. + open var debugDescription: String { + return cURLRepresentation() + } + + func cURLRepresentation() -> String { + var components = ["$ curl -i"] + + guard let request = self.request, + let url = request.url, + let host = url.host + else { + return "$ curl command could not be created" + } + + if let httpMethod = request.httpMethod, httpMethod != "GET" { + components.append("-X \(httpMethod)") + } + + if let credentialStorage = self.session.configuration.urlCredentialStorage { + let protectionSpace = URLProtectionSpace( + host: host, + port: url.port ?? 0, + protocol: url.scheme, + realm: host, + authenticationMethod: NSURLAuthenticationMethodHTTPBasic + ) + + if let credentials = credentialStorage.credentials(for: protectionSpace)?.values { + for credential in credentials { + components.append("-u \(credential.user!):\(credential.password!)") + } + } else { + if let credential = delegate.credential { + components.append("-u \(credential.user!):\(credential.password!)") + } + } + } + + if session.configuration.httpShouldSetCookies { + if + let cookieStorage = session.configuration.httpCookieStorage, + let cookies = cookieStorage.cookies(for: url), !cookies.isEmpty + { + let string = cookies.reduce("") { $0 + "\($1.name)=\($1.value);" } + components.append("-b \"\(string.substring(to: string.characters.index(before: string.endIndex)))\"") + } + } + + var headers: [AnyHashable: Any] = [:] + + if let additionalHeaders = session.configuration.httpAdditionalHeaders { + for (field, value) in additionalHeaders where field != AnyHashable("Cookie") { + headers[field] = value + } + } + + if let headerFields = request.allHTTPHeaderFields { + for (field, value) in headerFields where field != "Cookie" { + headers[field] = value + } + } + + for (field, value) in headers { + components.append("-H \"\(field): \(value)\"") + } + + if let httpBodyData = request.httpBody, let httpBody = String(data: httpBodyData, encoding: .utf8) { + var escapedBody = httpBody.replacingOccurrences(of: "\\\"", with: "\\\\\"") + escapedBody = escapedBody.replacingOccurrences(of: "\"", with: "\\\"") + + components.append("-d \"\(escapedBody)\"") + } + + components.append("\"\(url.absoluteString)\"") + + return components.joined(separator: " \\\n\t") + } +} + +// MARK: - + +/// Specific type of `Request` that manages an underlying `URLSessionDataTask`. +open class DataRequest: Request { + + // MARK: Helper Types + + struct Requestable: TaskConvertible { + let urlRequest: URLRequest + + func task(session: URLSession, adapter: RequestAdapter?, queue: DispatchQueue) throws -> URLSessionTask { + do { + let urlRequest = try self.urlRequest.adapt(using: adapter) + return queue.sync { session.dataTask(with: urlRequest) } + } catch { + throw AdaptError(error: error) + } + } + } + + // MARK: Properties + + /// The request sent or to be sent to the server. + open override var request: URLRequest? { + if let request = super.request { return request } + if let requestable = originalTask as? Requestable { return requestable.urlRequest } + + return nil + } + + /// The progress of fetching the response data from the server for the request. + open var progress: Progress { return dataDelegate.progress } + + var dataDelegate: DataTaskDelegate { return delegate as! DataTaskDelegate } + + // MARK: Stream + + /// Sets a closure to be called periodically during the lifecycle of the request as data is read from the server. + /// + /// This closure returns the bytes most recently received from the server, not including data from previous calls. + /// If this closure is set, data will only be available within this closure, and will not be saved elsewhere. It is + /// also important to note that the server data in any `Response` object will be `nil`. + /// + /// - parameter closure: The code to be executed periodically during the lifecycle of the request. + /// + /// - returns: The request. + @discardableResult + open func stream(closure: ((Data) -> Void)? = nil) -> Self { + dataDelegate.dataStream = closure + return self + } + + // MARK: Progress + + /// Sets a closure to be called periodically during the lifecycle of the `Request` as data is read from the server. + /// + /// - parameter queue: The dispatch queue to execute the closure on. + /// - parameter closure: The code to be executed periodically as data is read from the server. + /// + /// - returns: The request. + @discardableResult + open func downloadProgress(queue: DispatchQueue = DispatchQueue.main, closure: @escaping ProgressHandler) -> Self { + dataDelegate.progressHandler = (closure, queue) + return self + } +} + +// MARK: - + +/// Specific type of `Request` that manages an underlying `URLSessionDownloadTask`. +open class DownloadRequest: Request { + + // MARK: Helper Types + + /// A collection of options to be executed prior to moving a downloaded file from the temporary URL to the + /// destination URL. + public struct DownloadOptions: OptionSet { + /// Returns the raw bitmask value of the option and satisfies the `RawRepresentable` protocol. + public let rawValue: UInt + + /// A `DownloadOptions` flag that creates intermediate directories for the destination URL if specified. + public static let createIntermediateDirectories = DownloadOptions(rawValue: 1 << 0) + + /// A `DownloadOptions` flag that removes a previous file from the destination URL if specified. + public static let removePreviousFile = DownloadOptions(rawValue: 1 << 1) + + /// Creates a `DownloadFileDestinationOptions` instance with the specified raw value. + /// + /// - parameter rawValue: The raw bitmask value for the option. + /// + /// - returns: A new log level instance. + public init(rawValue: UInt) { + self.rawValue = rawValue + } + } + + /// A closure executed once a download request has successfully completed in order to determine where to move the + /// temporary file written to during the download process. The closure takes two arguments: the temporary file URL + /// and the URL response, and returns a two arguments: the file URL where the temporary file should be moved and + /// the options defining how the file should be moved. + public typealias DownloadFileDestination = ( + _ temporaryURL: URL, + _ response: HTTPURLResponse) + -> (destinationURL: URL, options: DownloadOptions) + + enum Downloadable: TaskConvertible { + case request(URLRequest) + case resumeData(Data) + + func task(session: URLSession, adapter: RequestAdapter?, queue: DispatchQueue) throws -> URLSessionTask { + do { + let task: URLSessionTask + + switch self { + case let .request(urlRequest): + let urlRequest = try urlRequest.adapt(using: adapter) + task = queue.sync { session.downloadTask(with: urlRequest) } + case let .resumeData(resumeData): + task = queue.sync { session.downloadTask(withResumeData: resumeData) } + } + + return task + } catch { + throw AdaptError(error: error) + } + } + } + + // MARK: Properties + + /// The request sent or to be sent to the server. + open override var request: URLRequest? { + if let request = super.request { return request } + + if let downloadable = originalTask as? Downloadable, case let .request(urlRequest) = downloadable { + return urlRequest + } + + return nil + } + + /// The resume data of the underlying download task if available after a failure. + open var resumeData: Data? { return downloadDelegate.resumeData } + + /// The progress of downloading the response data from the server for the request. + open var progress: Progress { return downloadDelegate.progress } + + var downloadDelegate: DownloadTaskDelegate { return delegate as! DownloadTaskDelegate } + + // MARK: State + + /// Cancels the request. + open override func cancel() { + downloadDelegate.downloadTask.cancel { self.downloadDelegate.resumeData = $0 } + + NotificationCenter.default.post( + name: Notification.Name.Task.DidCancel, + object: self, + userInfo: [Notification.Key.Task: task as Any] + ) + } + + // MARK: Progress + + /// Sets a closure to be called periodically during the lifecycle of the `Request` as data is read from the server. + /// + /// - parameter queue: The dispatch queue to execute the closure on. + /// - parameter closure: The code to be executed periodically as data is read from the server. + /// + /// - returns: The request. + @discardableResult + open func downloadProgress(queue: DispatchQueue = DispatchQueue.main, closure: @escaping ProgressHandler) -> Self { + downloadDelegate.progressHandler = (closure, queue) + return self + } + + // MARK: Destination + + /// Creates a download file destination closure which uses the default file manager to move the temporary file to a + /// file URL in the first available directory with the specified search path directory and search path domain mask. + /// + /// - parameter directory: The search path directory. `.DocumentDirectory` by default. + /// - parameter domain: The search path domain mask. `.UserDomainMask` by default. + /// + /// - returns: A download file destination closure. + open class func suggestedDownloadDestination( + for directory: FileManager.SearchPathDirectory = .documentDirectory, + in domain: FileManager.SearchPathDomainMask = .userDomainMask) + -> DownloadFileDestination + { + return { temporaryURL, response in + let directoryURLs = FileManager.default.urls(for: directory, in: domain) + + if !directoryURLs.isEmpty { + return (directoryURLs[0].appendingPathComponent(response.suggestedFilename!), []) + } + + return (temporaryURL, []) + } + } +} + +// MARK: - + +/// Specific type of `Request` that manages an underlying `URLSessionUploadTask`. +open class UploadRequest: DataRequest { + + // MARK: Helper Types + + enum Uploadable: TaskConvertible { + case data(Data, URLRequest) + case file(URL, URLRequest) + case stream(InputStream, URLRequest) + + func task(session: URLSession, adapter: RequestAdapter?, queue: DispatchQueue) throws -> URLSessionTask { + do { + let task: URLSessionTask + + switch self { + case let .data(data, urlRequest): + let urlRequest = try urlRequest.adapt(using: adapter) + task = queue.sync { session.uploadTask(with: urlRequest, from: data) } + case let .file(url, urlRequest): + let urlRequest = try urlRequest.adapt(using: adapter) + task = queue.sync { session.uploadTask(with: urlRequest, fromFile: url) } + case let .stream(_, urlRequest): + let urlRequest = try urlRequest.adapt(using: adapter) + task = queue.sync { session.uploadTask(withStreamedRequest: urlRequest) } + } + + return task + } catch { + throw AdaptError(error: error) + } + } + } + + // MARK: Properties + + /// The request sent or to be sent to the server. + open override var request: URLRequest? { + if let request = super.request { return request } + + guard let uploadable = originalTask as? Uploadable else { return nil } + + switch uploadable { + case .data(_, let urlRequest), .file(_, let urlRequest), .stream(_, let urlRequest): + return urlRequest + } + } + + /// The progress of uploading the payload to the server for the upload request. + open var uploadProgress: Progress { return uploadDelegate.uploadProgress } + + var uploadDelegate: UploadTaskDelegate { return delegate as! UploadTaskDelegate } + + // MARK: Upload Progress + + /// Sets a closure to be called periodically during the lifecycle of the `UploadRequest` as data is sent to + /// the server. + /// + /// After the data is sent to the server, the `progress(queue:closure:)` APIs can be used to monitor the progress + /// of data being read from the server. + /// + /// - parameter queue: The dispatch queue to execute the closure on. + /// - parameter closure: The code to be executed periodically as data is sent to the server. + /// + /// - returns: The request. + @discardableResult + open func uploadProgress(queue: DispatchQueue = DispatchQueue.main, closure: @escaping ProgressHandler) -> Self { + uploadDelegate.uploadProgressHandler = (closure, queue) + return self + } +} + +// MARK: - + +#if !os(watchOS) + +/// Specific type of `Request` that manages an underlying `URLSessionStreamTask`. +@available(iOS 9.0, macOS 10.11, tvOS 9.0, *) +open class StreamRequest: Request { + enum Streamable: TaskConvertible { + case stream(hostName: String, port: Int) + case netService(NetService) + + func task(session: URLSession, adapter: RequestAdapter?, queue: DispatchQueue) throws -> URLSessionTask { + let task: URLSessionTask + + switch self { + case let .stream(hostName, port): + task = queue.sync { session.streamTask(withHostName: hostName, port: port) } + case let .netService(netService): + task = queue.sync { session.streamTask(with: netService) } + } + + return task + } + } +} + +#endif diff --git a/Pods/Alamofire/Source/Response.swift b/Pods/Alamofire/Source/Response.swift new file mode 100644 index 0000000..318596d --- /dev/null +++ b/Pods/Alamofire/Source/Response.swift @@ -0,0 +1,345 @@ +// +// Response.swift +// +// Copyright (c) 2014-2016 Alamofire Software Foundation (http://alamofire.org/) +// +// Permission is hereby granted, free of charge, to any person obtaining a copy +// of this software and associated documentation files (the "Software"), to deal +// in the Software without restriction, including without limitation the rights +// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +// copies of the Software, and to permit persons to whom the Software is +// furnished to do so, subject to the following conditions: +// +// The above copyright notice and this permission notice shall be included in +// all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN +// THE SOFTWARE. +// + +import Foundation + +/// Used to store all data associated with an non-serialized response of a data or upload request. +public struct DefaultDataResponse { + /// The URL request sent to the server. + public let request: URLRequest? + + /// The server's response to the URL request. + public let response: HTTPURLResponse? + + /// The data returned by the server. + public let data: Data? + + /// The error encountered while executing or validating the request. + public let error: Error? + + /// The timeline of the complete lifecycle of the request. + public let timeline: Timeline + + var _metrics: AnyObject? + + /// Creates a `DefaultDataResponse` instance from the specified parameters. + /// + /// - Parameters: + /// - request: The URL request sent to the server. + /// - response: The server's response to the URL request. + /// - data: The data returned by the server. + /// - error: The error encountered while executing or validating the request. + /// - timeline: The timeline of the complete lifecycle of the request. `Timeline()` by default. + /// - metrics: The task metrics containing the request / response statistics. `nil` by default. + public init( + request: URLRequest?, + response: HTTPURLResponse?, + data: Data?, + error: Error?, + timeline: Timeline = Timeline(), + metrics: AnyObject? = nil) + { + self.request = request + self.response = response + self.data = data + self.error = error + self.timeline = timeline + } +} + +// MARK: - + +/// Used to store all data associated with a serialized response of a data or upload request. +public struct DataResponse { + /// The URL request sent to the server. + public let request: URLRequest? + + /// The server's response to the URL request. + public let response: HTTPURLResponse? + + /// The data returned by the server. + public let data: Data? + + /// The result of response serialization. + public let result: Result + + /// The timeline of the complete lifecycle of the request. + public let timeline: Timeline + + /// Returns the associated value of the result if it is a success, `nil` otherwise. + public var value: Value? { return result.value } + + /// Returns the associated error value if the result if it is a failure, `nil` otherwise. + public var error: Error? { return result.error } + + var _metrics: AnyObject? + + /// Creates a `DataResponse` instance with the specified parameters derived from response serialization. + /// + /// - parameter request: The URL request sent to the server. + /// - parameter response: The server's response to the URL request. + /// - parameter data: The data returned by the server. + /// - parameter result: The result of response serialization. + /// - parameter timeline: The timeline of the complete lifecycle of the `Request`. Defaults to `Timeline()`. + /// + /// - returns: The new `DataResponse` instance. + public init( + request: URLRequest?, + response: HTTPURLResponse?, + data: Data?, + result: Result, + timeline: Timeline = Timeline()) + { + self.request = request + self.response = response + self.data = data + self.result = result + self.timeline = timeline + } +} + +// MARK: - + +extension DataResponse: CustomStringConvertible, CustomDebugStringConvertible { + /// The textual representation used when written to an output stream, which includes whether the result was a + /// success or failure. + public var description: String { + return result.debugDescription + } + + /// The debug textual representation used when written to an output stream, which includes the URL request, the URL + /// response, the server data, the response serialization result and the timeline. + public var debugDescription: String { + var output: [String] = [] + + output.append(request != nil ? "[Request]: \(request!.httpMethod ?? "GET") \(request!)" : "[Request]: nil") + output.append(response != nil ? "[Response]: \(response!)" : "[Response]: nil") + output.append("[Data]: \(data?.count ?? 0) bytes") + output.append("[Result]: \(result.debugDescription)") + output.append("[Timeline]: \(timeline.debugDescription)") + + return output.joined(separator: "\n") + } +} + +// MARK: - + +/// Used to store all data associated with an non-serialized response of a download request. +public struct DefaultDownloadResponse { + /// The URL request sent to the server. + public let request: URLRequest? + + /// The server's response to the URL request. + public let response: HTTPURLResponse? + + /// The temporary destination URL of the data returned from the server. + public let temporaryURL: URL? + + /// The final destination URL of the data returned from the server if it was moved. + public let destinationURL: URL? + + /// The resume data generated if the request was cancelled. + public let resumeData: Data? + + /// The error encountered while executing or validating the request. + public let error: Error? + + /// The timeline of the complete lifecycle of the request. + public let timeline: Timeline + + var _metrics: AnyObject? + + /// Creates a `DefaultDownloadResponse` instance from the specified parameters. + /// + /// - Parameters: + /// - request: The URL request sent to the server. + /// - response: The server's response to the URL request. + /// - temporaryURL: The temporary destination URL of the data returned from the server. + /// - destinationURL: The final destination URL of the data returned from the server if it was moved. + /// - resumeData: The resume data generated if the request was cancelled. + /// - error: The error encountered while executing or validating the request. + /// - timeline: The timeline of the complete lifecycle of the request. `Timeline()` by default. + /// - metrics: The task metrics containing the request / response statistics. `nil` by default. + public init( + request: URLRequest?, + response: HTTPURLResponse?, + temporaryURL: URL?, + destinationURL: URL?, + resumeData: Data?, + error: Error?, + timeline: Timeline = Timeline(), + metrics: AnyObject? = nil) + { + self.request = request + self.response = response + self.temporaryURL = temporaryURL + self.destinationURL = destinationURL + self.resumeData = resumeData + self.error = error + self.timeline = timeline + } +} + +// MARK: - + +/// Used to store all data associated with a serialized response of a download request. +public struct DownloadResponse { + /// The URL request sent to the server. + public let request: URLRequest? + + /// The server's response to the URL request. + public let response: HTTPURLResponse? + + /// The temporary destination URL of the data returned from the server. + public let temporaryURL: URL? + + /// The final destination URL of the data returned from the server if it was moved. + public let destinationURL: URL? + + /// The resume data generated if the request was cancelled. + public let resumeData: Data? + + /// The result of response serialization. + public let result: Result + + /// The timeline of the complete lifecycle of the request. + public let timeline: Timeline + + /// Returns the associated value of the result if it is a success, `nil` otherwise. + public var value: Value? { return result.value } + + /// Returns the associated error value if the result if it is a failure, `nil` otherwise. + public var error: Error? { return result.error } + + var _metrics: AnyObject? + + /// Creates a `DownloadResponse` instance with the specified parameters derived from response serialization. + /// + /// - parameter request: The URL request sent to the server. + /// - parameter response: The server's response to the URL request. + /// - parameter temporaryURL: The temporary destination URL of the data returned from the server. + /// - parameter destinationURL: The final destination URL of the data returned from the server if it was moved. + /// - parameter resumeData: The resume data generated if the request was cancelled. + /// - parameter result: The result of response serialization. + /// - parameter timeline: The timeline of the complete lifecycle of the `Request`. Defaults to `Timeline()`. + /// + /// - returns: The new `DownloadResponse` instance. + public init( + request: URLRequest?, + response: HTTPURLResponse?, + temporaryURL: URL?, + destinationURL: URL?, + resumeData: Data?, + result: Result, + timeline: Timeline = Timeline()) + { + self.request = request + self.response = response + self.temporaryURL = temporaryURL + self.destinationURL = destinationURL + self.resumeData = resumeData + self.result = result + self.timeline = timeline + } +} + +// MARK: - + +extension DownloadResponse: CustomStringConvertible, CustomDebugStringConvertible { + /// The textual representation used when written to an output stream, which includes whether the result was a + /// success or failure. + public var description: String { + return result.debugDescription + } + + /// The debug textual representation used when written to an output stream, which includes the URL request, the URL + /// response, the temporary and destination URLs, the resume data, the response serialization result and the + /// timeline. + public var debugDescription: String { + var output: [String] = [] + + output.append(request != nil ? "[Request]: \(request!.httpMethod ?? "GET") \(request!)" : "[Request]: nil") + output.append(response != nil ? "[Response]: \(response!)" : "[Response]: nil") + output.append("[TemporaryURL]: \(temporaryURL?.path ?? "nil")") + output.append("[DestinationURL]: \(destinationURL?.path ?? "nil")") + output.append("[ResumeData]: \(resumeData?.count ?? 0) bytes") + output.append("[Result]: \(result.debugDescription)") + output.append("[Timeline]: \(timeline.debugDescription)") + + return output.joined(separator: "\n") + } +} + +// MARK: - + +protocol Response { + /// The task metrics containing the request / response statistics. + var _metrics: AnyObject? { get set } + mutating func add(_ metrics: AnyObject?) +} + +extension Response { + mutating func add(_ metrics: AnyObject?) { + #if !os(watchOS) + guard #available(iOS 10.0, macOS 10.12, tvOS 10.0, *) else { return } + guard let metrics = metrics as? URLSessionTaskMetrics else { return } + + _metrics = metrics + #endif + } +} + +// MARK: - + +@available(iOS 10.0, macOS 10.12, tvOS 10.0, *) +extension DefaultDataResponse: Response { +#if !os(watchOS) + /// The task metrics containing the request / response statistics. + public var metrics: URLSessionTaskMetrics? { return _metrics as? URLSessionTaskMetrics } +#endif +} + +@available(iOS 10.0, macOS 10.12, tvOS 10.0, *) +extension DataResponse: Response { +#if !os(watchOS) + /// The task metrics containing the request / response statistics. + public var metrics: URLSessionTaskMetrics? { return _metrics as? URLSessionTaskMetrics } +#endif +} + +@available(iOS 10.0, macOS 10.12, tvOS 10.0, *) +extension DefaultDownloadResponse: Response { +#if !os(watchOS) + /// The task metrics containing the request / response statistics. + public var metrics: URLSessionTaskMetrics? { return _metrics as? URLSessionTaskMetrics } +#endif +} + +@available(iOS 10.0, macOS 10.12, tvOS 10.0, *) +extension DownloadResponse: Response { +#if !os(watchOS) + /// The task metrics containing the request / response statistics. + public var metrics: URLSessionTaskMetrics? { return _metrics as? URLSessionTaskMetrics } +#endif +} diff --git a/Pods/Alamofire/Source/ResponseSerialization.swift b/Pods/Alamofire/Source/ResponseSerialization.swift new file mode 100644 index 0000000..47780fd --- /dev/null +++ b/Pods/Alamofire/Source/ResponseSerialization.swift @@ -0,0 +1,714 @@ +// +// ResponseSerialization.swift +// +// Copyright (c) 2014-2016 Alamofire Software Foundation (http://alamofire.org/) +// +// Permission is hereby granted, free of charge, to any person obtaining a copy +// of this software and associated documentation files (the "Software"), to deal +// in the Software without restriction, including without limitation the rights +// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +// copies of the Software, and to permit persons to whom the Software is +// furnished to do so, subject to the following conditions: +// +// The above copyright notice and this permission notice shall be included in +// all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN +// THE SOFTWARE. +// + +import Foundation + +/// The type in which all data response serializers must conform to in order to serialize a response. +public protocol DataResponseSerializerProtocol { + /// The type of serialized object to be created by this `DataResponseSerializerType`. + associatedtype SerializedObject + + /// A closure used by response handlers that takes a request, response, data and error and returns a result. + var serializeResponse: (URLRequest?, HTTPURLResponse?, Data?, Error?) -> Result { get } +} + +// MARK: - + +/// A generic `DataResponseSerializerType` used to serialize a request, response, and data into a serialized object. +public struct DataResponseSerializer: DataResponseSerializerProtocol { + /// The type of serialized object to be created by this `DataResponseSerializer`. + public typealias SerializedObject = Value + + /// A closure used by response handlers that takes a request, response, data and error and returns a result. + public var serializeResponse: (URLRequest?, HTTPURLResponse?, Data?, Error?) -> Result + + /// Initializes the `ResponseSerializer` instance with the given serialize response closure. + /// + /// - parameter serializeResponse: The closure used to serialize the response. + /// + /// - returns: The new generic response serializer instance. + public init(serializeResponse: @escaping (URLRequest?, HTTPURLResponse?, Data?, Error?) -> Result) { + self.serializeResponse = serializeResponse + } +} + +// MARK: - + +/// The type in which all download response serializers must conform to in order to serialize a response. +public protocol DownloadResponseSerializerProtocol { + /// The type of serialized object to be created by this `DownloadResponseSerializerType`. + associatedtype SerializedObject + + /// A closure used by response handlers that takes a request, response, url and error and returns a result. + var serializeResponse: (URLRequest?, HTTPURLResponse?, URL?, Error?) -> Result { get } +} + +// MARK: - + +/// A generic `DownloadResponseSerializerType` used to serialize a request, response, and data into a serialized object. +public struct DownloadResponseSerializer: DownloadResponseSerializerProtocol { + /// The type of serialized object to be created by this `DownloadResponseSerializer`. + public typealias SerializedObject = Value + + /// A closure used by response handlers that takes a request, response, url and error and returns a result. + public var serializeResponse: (URLRequest?, HTTPURLResponse?, URL?, Error?) -> Result + + /// Initializes the `ResponseSerializer` instance with the given serialize response closure. + /// + /// - parameter serializeResponse: The closure used to serialize the response. + /// + /// - returns: The new generic response serializer instance. + public init(serializeResponse: @escaping (URLRequest?, HTTPURLResponse?, URL?, Error?) -> Result) { + self.serializeResponse = serializeResponse + } +} + +// MARK: - Timeline + +extension Request { + var timeline: Timeline { + let requestCompletedTime = self.endTime ?? CFAbsoluteTimeGetCurrent() + let initialResponseTime = self.delegate.initialResponseTime ?? requestCompletedTime + + return Timeline( + requestStartTime: self.startTime ?? CFAbsoluteTimeGetCurrent(), + initialResponseTime: initialResponseTime, + requestCompletedTime: requestCompletedTime, + serializationCompletedTime: CFAbsoluteTimeGetCurrent() + ) + } +} + +// MARK: - Default + +extension DataRequest { + /// Adds a handler to be called once the request has finished. + /// + /// - parameter queue: The queue on which the completion handler is dispatched. + /// - parameter completionHandler: The code to be executed once the request has finished. + /// + /// - returns: The request. + @discardableResult + public func response(queue: DispatchQueue? = nil, completionHandler: @escaping (DefaultDataResponse) -> Void) -> Self { + delegate.queue.addOperation { + (queue ?? DispatchQueue.main).async { + var dataResponse = DefaultDataResponse( + request: self.request, + response: self.response, + data: self.delegate.data, + error: self.delegate.error, + timeline: self.timeline + ) + + dataResponse.add(self.delegate.metrics) + + completionHandler(dataResponse) + } + } + + return self + } + + /// Adds a handler to be called once the request has finished. + /// + /// - parameter queue: The queue on which the completion handler is dispatched. + /// - parameter responseSerializer: The response serializer responsible for serializing the request, response, + /// and data. + /// - parameter completionHandler: The code to be executed once the request has finished. + /// + /// - returns: The request. + @discardableResult + public func response( + queue: DispatchQueue? = nil, + responseSerializer: T, + completionHandler: @escaping (DataResponse) -> Void) + -> Self + { + delegate.queue.addOperation { + let result = responseSerializer.serializeResponse( + self.request, + self.response, + self.delegate.data, + self.delegate.error + ) + + var dataResponse = DataResponse( + request: self.request, + response: self.response, + data: self.delegate.data, + result: result, + timeline: self.timeline + ) + + dataResponse.add(self.delegate.metrics) + + (queue ?? DispatchQueue.main).async { completionHandler(dataResponse) } + } + + return self + } +} + +extension DownloadRequest { + /// Adds a handler to be called once the request has finished. + /// + /// - parameter queue: The queue on which the completion handler is dispatched. + /// - parameter completionHandler: The code to be executed once the request has finished. + /// + /// - returns: The request. + @discardableResult + public func response( + queue: DispatchQueue? = nil, + completionHandler: @escaping (DefaultDownloadResponse) -> Void) + -> Self + { + delegate.queue.addOperation { + (queue ?? DispatchQueue.main).async { + var downloadResponse = DefaultDownloadResponse( + request: self.request, + response: self.response, + temporaryURL: self.downloadDelegate.temporaryURL, + destinationURL: self.downloadDelegate.destinationURL, + resumeData: self.downloadDelegate.resumeData, + error: self.downloadDelegate.error, + timeline: self.timeline + ) + + downloadResponse.add(self.delegate.metrics) + + completionHandler(downloadResponse) + } + } + + return self + } + + /// Adds a handler to be called once the request has finished. + /// + /// - parameter queue: The queue on which the completion handler is dispatched. + /// - parameter responseSerializer: The response serializer responsible for serializing the request, response, + /// and data contained in the destination url. + /// - parameter completionHandler: The code to be executed once the request has finished. + /// + /// - returns: The request. + @discardableResult + public func response( + queue: DispatchQueue? = nil, + responseSerializer: T, + completionHandler: @escaping (DownloadResponse) -> Void) + -> Self + { + delegate.queue.addOperation { + let result = responseSerializer.serializeResponse( + self.request, + self.response, + self.downloadDelegate.fileURL, + self.downloadDelegate.error + ) + + var downloadResponse = DownloadResponse( + request: self.request, + response: self.response, + temporaryURL: self.downloadDelegate.temporaryURL, + destinationURL: self.downloadDelegate.destinationURL, + resumeData: self.downloadDelegate.resumeData, + result: result, + timeline: self.timeline + ) + + downloadResponse.add(self.delegate.metrics) + + (queue ?? DispatchQueue.main).async { completionHandler(downloadResponse) } + } + + return self + } +} + +// MARK: - Data + +extension Request { + /// Returns a result data type that contains the response data as-is. + /// + /// - parameter response: The response from the server. + /// - parameter data: The data returned from the server. + /// - parameter error: The error already encountered if it exists. + /// + /// - returns: The result data type. + public static func serializeResponseData(response: HTTPURLResponse?, data: Data?, error: Error?) -> Result { + guard error == nil else { return .failure(error!) } + + if let response = response, emptyDataStatusCodes.contains(response.statusCode) { return .success(Data()) } + + guard let validData = data else { + return .failure(AFError.responseSerializationFailed(reason: .inputDataNil)) + } + + return .success(validData) + } +} + +extension DataRequest { + /// Creates a response serializer that returns the associated data as-is. + /// + /// - returns: A data response serializer. + public static func dataResponseSerializer() -> DataResponseSerializer { + return DataResponseSerializer { _, response, data, error in + return Request.serializeResponseData(response: response, data: data, error: error) + } + } + + /// Adds a handler to be called once the request has finished. + /// + /// - parameter completionHandler: The code to be executed once the request has finished. + /// + /// - returns: The request. + @discardableResult + public func responseData( + queue: DispatchQueue? = nil, + completionHandler: @escaping (DataResponse) -> Void) + -> Self + { + return response( + queue: queue, + responseSerializer: DataRequest.dataResponseSerializer(), + completionHandler: completionHandler + ) + } +} + +extension DownloadRequest { + /// Creates a response serializer that returns the associated data as-is. + /// + /// - returns: A data response serializer. + public static func dataResponseSerializer() -> DownloadResponseSerializer { + return DownloadResponseSerializer { _, response, fileURL, error in + guard error == nil else { return .failure(error!) } + + guard let fileURL = fileURL else { + return .failure(AFError.responseSerializationFailed(reason: .inputFileNil)) + } + + do { + let data = try Data(contentsOf: fileURL) + return Request.serializeResponseData(response: response, data: data, error: error) + } catch { + return .failure(AFError.responseSerializationFailed(reason: .inputFileReadFailed(at: fileURL))) + } + } + } + + /// Adds a handler to be called once the request has finished. + /// + /// - parameter completionHandler: The code to be executed once the request has finished. + /// + /// - returns: The request. + @discardableResult + public func responseData( + queue: DispatchQueue? = nil, + completionHandler: @escaping (DownloadResponse) -> Void) + -> Self + { + return response( + queue: queue, + responseSerializer: DownloadRequest.dataResponseSerializer(), + completionHandler: completionHandler + ) + } +} + +// MARK: - String + +extension Request { + /// Returns a result string type initialized from the response data with the specified string encoding. + /// + /// - parameter encoding: The string encoding. If `nil`, the string encoding will be determined from the server + /// response, falling back to the default HTTP default character set, ISO-8859-1. + /// - parameter response: The response from the server. + /// - parameter data: The data returned from the server. + /// - parameter error: The error already encountered if it exists. + /// + /// - returns: The result data type. + public static func serializeResponseString( + encoding: String.Encoding?, + response: HTTPURLResponse?, + data: Data?, + error: Error?) + -> Result + { + guard error == nil else { return .failure(error!) } + + if let response = response, emptyDataStatusCodes.contains(response.statusCode) { return .success("") } + + guard let validData = data else { + return .failure(AFError.responseSerializationFailed(reason: .inputDataNil)) + } + + var convertedEncoding = encoding + + if let encodingName = response?.textEncodingName as CFString!, convertedEncoding == nil { + convertedEncoding = String.Encoding(rawValue: CFStringConvertEncodingToNSStringEncoding( + CFStringConvertIANACharSetNameToEncoding(encodingName)) + ) + } + + let actualEncoding = convertedEncoding ?? String.Encoding.isoLatin1 + + if let string = String(data: validData, encoding: actualEncoding) { + return .success(string) + } else { + return .failure(AFError.responseSerializationFailed(reason: .stringSerializationFailed(encoding: actualEncoding))) + } + } +} + +extension DataRequest { + /// Creates a response serializer that returns a result string type initialized from the response data with + /// the specified string encoding. + /// + /// - parameter encoding: The string encoding. If `nil`, the string encoding will be determined from the server + /// response, falling back to the default HTTP default character set, ISO-8859-1. + /// + /// - returns: A string response serializer. + public static func stringResponseSerializer(encoding: String.Encoding? = nil) -> DataResponseSerializer { + return DataResponseSerializer { _, response, data, error in + return Request.serializeResponseString(encoding: encoding, response: response, data: data, error: error) + } + } + + /// Adds a handler to be called once the request has finished. + /// + /// - parameter encoding: The string encoding. If `nil`, the string encoding will be determined from the + /// server response, falling back to the default HTTP default character set, + /// ISO-8859-1. + /// - parameter completionHandler: A closure to be executed once the request has finished. + /// + /// - returns: The request. + @discardableResult + public func responseString( + queue: DispatchQueue? = nil, + encoding: String.Encoding? = nil, + completionHandler: @escaping (DataResponse) -> Void) + -> Self + { + return response( + queue: queue, + responseSerializer: DataRequest.stringResponseSerializer(encoding: encoding), + completionHandler: completionHandler + ) + } +} + +extension DownloadRequest { + /// Creates a response serializer that returns a result string type initialized from the response data with + /// the specified string encoding. + /// + /// - parameter encoding: The string encoding. If `nil`, the string encoding will be determined from the server + /// response, falling back to the default HTTP default character set, ISO-8859-1. + /// + /// - returns: A string response serializer. + public static func stringResponseSerializer(encoding: String.Encoding? = nil) -> DownloadResponseSerializer { + return DownloadResponseSerializer { _, response, fileURL, error in + guard error == nil else { return .failure(error!) } + + guard let fileURL = fileURL else { + return .failure(AFError.responseSerializationFailed(reason: .inputFileNil)) + } + + do { + let data = try Data(contentsOf: fileURL) + return Request.serializeResponseString(encoding: encoding, response: response, data: data, error: error) + } catch { + return .failure(AFError.responseSerializationFailed(reason: .inputFileReadFailed(at: fileURL))) + } + } + } + + /// Adds a handler to be called once the request has finished. + /// + /// - parameter encoding: The string encoding. If `nil`, the string encoding will be determined from the + /// server response, falling back to the default HTTP default character set, + /// ISO-8859-1. + /// - parameter completionHandler: A closure to be executed once the request has finished. + /// + /// - returns: The request. + @discardableResult + public func responseString( + queue: DispatchQueue? = nil, + encoding: String.Encoding? = nil, + completionHandler: @escaping (DownloadResponse) -> Void) + -> Self + { + return response( + queue: queue, + responseSerializer: DownloadRequest.stringResponseSerializer(encoding: encoding), + completionHandler: completionHandler + ) + } +} + +// MARK: - JSON + +extension Request { + /// Returns a JSON object contained in a result type constructed from the response data using `JSONSerialization` + /// with the specified reading options. + /// + /// - parameter options: The JSON serialization reading options. Defaults to `.allowFragments`. + /// - parameter response: The response from the server. + /// - parameter data: The data returned from the server. + /// - parameter error: The error already encountered if it exists. + /// + /// - returns: The result data type. + public static func serializeResponseJSON( + options: JSONSerialization.ReadingOptions, + response: HTTPURLResponse?, + data: Data?, + error: Error?) + -> Result + { + guard error == nil else { return .failure(error!) } + + if let response = response, emptyDataStatusCodes.contains(response.statusCode) { return .success(NSNull()) } + + guard let validData = data, validData.count > 0 else { + return .failure(AFError.responseSerializationFailed(reason: .inputDataNilOrZeroLength)) + } + + do { + let json = try JSONSerialization.jsonObject(with: validData, options: options) + return .success(json) + } catch { + return .failure(AFError.responseSerializationFailed(reason: .jsonSerializationFailed(error: error))) + } + } +} + +extension DataRequest { + /// Creates a response serializer that returns a JSON object result type constructed from the response data using + /// `JSONSerialization` with the specified reading options. + /// + /// - parameter options: The JSON serialization reading options. Defaults to `.allowFragments`. + /// + /// - returns: A JSON object response serializer. + public static func jsonResponseSerializer( + options: JSONSerialization.ReadingOptions = .allowFragments) + -> DataResponseSerializer + { + return DataResponseSerializer { _, response, data, error in + return Request.serializeResponseJSON(options: options, response: response, data: data, error: error) + } + } + + /// Adds a handler to be called once the request has finished. + /// + /// - parameter options: The JSON serialization reading options. Defaults to `.allowFragments`. + /// - parameter completionHandler: A closure to be executed once the request has finished. + /// + /// - returns: The request. + @discardableResult + public func responseJSON( + queue: DispatchQueue? = nil, + options: JSONSerialization.ReadingOptions = .allowFragments, + completionHandler: @escaping (DataResponse) -> Void) + -> Self + { + return response( + queue: queue, + responseSerializer: DataRequest.jsonResponseSerializer(options: options), + completionHandler: completionHandler + ) + } +} + +extension DownloadRequest { + /// Creates a response serializer that returns a JSON object result type constructed from the response data using + /// `JSONSerialization` with the specified reading options. + /// + /// - parameter options: The JSON serialization reading options. Defaults to `.allowFragments`. + /// + /// - returns: A JSON object response serializer. + public static func jsonResponseSerializer( + options: JSONSerialization.ReadingOptions = .allowFragments) + -> DownloadResponseSerializer + { + return DownloadResponseSerializer { _, response, fileURL, error in + guard error == nil else { return .failure(error!) } + + guard let fileURL = fileURL else { + return .failure(AFError.responseSerializationFailed(reason: .inputFileNil)) + } + + do { + let data = try Data(contentsOf: fileURL) + return Request.serializeResponseJSON(options: options, response: response, data: data, error: error) + } catch { + return .failure(AFError.responseSerializationFailed(reason: .inputFileReadFailed(at: fileURL))) + } + } + } + + /// Adds a handler to be called once the request has finished. + /// + /// - parameter options: The JSON serialization reading options. Defaults to `.allowFragments`. + /// - parameter completionHandler: A closure to be executed once the request has finished. + /// + /// - returns: The request. + @discardableResult + public func responseJSON( + queue: DispatchQueue? = nil, + options: JSONSerialization.ReadingOptions = .allowFragments, + completionHandler: @escaping (DownloadResponse) -> Void) + -> Self + { + return response( + queue: queue, + responseSerializer: DownloadRequest.jsonResponseSerializer(options: options), + completionHandler: completionHandler + ) + } +} + +// MARK: - Property List + +extension Request { + /// Returns a plist object contained in a result type constructed from the response data using + /// `PropertyListSerialization` with the specified reading options. + /// + /// - parameter options: The property list reading options. Defaults to `[]`. + /// - parameter response: The response from the server. + /// - parameter data: The data returned from the server. + /// - parameter error: The error already encountered if it exists. + /// + /// - returns: The result data type. + public static func serializeResponsePropertyList( + options: PropertyListSerialization.ReadOptions, + response: HTTPURLResponse?, + data: Data?, + error: Error?) + -> Result + { + guard error == nil else { return .failure(error!) } + + if let response = response, emptyDataStatusCodes.contains(response.statusCode) { return .success(NSNull()) } + + guard let validData = data, validData.count > 0 else { + return .failure(AFError.responseSerializationFailed(reason: .inputDataNilOrZeroLength)) + } + + do { + let plist = try PropertyListSerialization.propertyList(from: validData, options: options, format: nil) + return .success(plist) + } catch { + return .failure(AFError.responseSerializationFailed(reason: .propertyListSerializationFailed(error: error))) + } + } +} + +extension DataRequest { + /// Creates a response serializer that returns an object constructed from the response data using + /// `PropertyListSerialization` with the specified reading options. + /// + /// - parameter options: The property list reading options. Defaults to `[]`. + /// + /// - returns: A property list object response serializer. + public static func propertyListResponseSerializer( + options: PropertyListSerialization.ReadOptions = []) + -> DataResponseSerializer + { + return DataResponseSerializer { _, response, data, error in + return Request.serializeResponsePropertyList(options: options, response: response, data: data, error: error) + } + } + + /// Adds a handler to be called once the request has finished. + /// + /// - parameter options: The property list reading options. Defaults to `[]`. + /// - parameter completionHandler: A closure to be executed once the request has finished. + /// + /// - returns: The request. + @discardableResult + public func responsePropertyList( + queue: DispatchQueue? = nil, + options: PropertyListSerialization.ReadOptions = [], + completionHandler: @escaping (DataResponse) -> Void) + -> Self + { + return response( + queue: queue, + responseSerializer: DataRequest.propertyListResponseSerializer(options: options), + completionHandler: completionHandler + ) + } +} + +extension DownloadRequest { + /// Creates a response serializer that returns an object constructed from the response data using + /// `PropertyListSerialization` with the specified reading options. + /// + /// - parameter options: The property list reading options. Defaults to `[]`. + /// + /// - returns: A property list object response serializer. + public static func propertyListResponseSerializer( + options: PropertyListSerialization.ReadOptions = []) + -> DownloadResponseSerializer + { + return DownloadResponseSerializer { _, response, fileURL, error in + guard error == nil else { return .failure(error!) } + + guard let fileURL = fileURL else { + return .failure(AFError.responseSerializationFailed(reason: .inputFileNil)) + } + + do { + let data = try Data(contentsOf: fileURL) + return Request.serializeResponsePropertyList(options: options, response: response, data: data, error: error) + } catch { + return .failure(AFError.responseSerializationFailed(reason: .inputFileReadFailed(at: fileURL))) + } + } + } + + /// Adds a handler to be called once the request has finished. + /// + /// - parameter options: The property list reading options. Defaults to `[]`. + /// - parameter completionHandler: A closure to be executed once the request has finished. + /// + /// - returns: The request. + @discardableResult + public func responsePropertyList( + queue: DispatchQueue? = nil, + options: PropertyListSerialization.ReadOptions = [], + completionHandler: @escaping (DownloadResponse) -> Void) + -> Self + { + return response( + queue: queue, + responseSerializer: DownloadRequest.propertyListResponseSerializer(options: options), + completionHandler: completionHandler + ) + } +} + +/// A set of HTTP response status code that do not contain response data. +private let emptyDataStatusCodes: Set = [204, 205] diff --git a/Pods/Alamofire/Source/Result.swift b/Pods/Alamofire/Source/Result.swift new file mode 100644 index 0000000..2293308 --- /dev/null +++ b/Pods/Alamofire/Source/Result.swift @@ -0,0 +1,102 @@ +// +// Result.swift +// +// Copyright (c) 2014-2016 Alamofire Software Foundation (http://alamofire.org/) +// +// Permission is hereby granted, free of charge, to any person obtaining a copy +// of this software and associated documentation files (the "Software"), to deal +// in the Software without restriction, including without limitation the rights +// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +// copies of the Software, and to permit persons to whom the Software is +// furnished to do so, subject to the following conditions: +// +// The above copyright notice and this permission notice shall be included in +// all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN +// THE SOFTWARE. +// + +import Foundation + +/// Used to represent whether a request was successful or encountered an error. +/// +/// - success: The request and all post processing operations were successful resulting in the serialization of the +/// provided associated value. +/// +/// - failure: The request encountered an error resulting in a failure. The associated values are the original data +/// provided by the server as well as the error that caused the failure. +public enum Result { + case success(Value) + case failure(Error) + + /// Returns `true` if the result is a success, `false` otherwise. + public var isSuccess: Bool { + switch self { + case .success: + return true + case .failure: + return false + } + } + + /// Returns `true` if the result is a failure, `false` otherwise. + public var isFailure: Bool { + return !isSuccess + } + + /// Returns the associated value if the result is a success, `nil` otherwise. + public var value: Value? { + switch self { + case .success(let value): + return value + case .failure: + return nil + } + } + + /// Returns the associated error value if the result is a failure, `nil` otherwise. + public var error: Error? { + switch self { + case .success: + return nil + case .failure(let error): + return error + } + } +} + +// MARK: - CustomStringConvertible + +extension Result: CustomStringConvertible { + /// The textual representation used when written to an output stream, which includes whether the result was a + /// success or failure. + public var description: String { + switch self { + case .success: + return "SUCCESS" + case .failure: + return "FAILURE" + } + } +} + +// MARK: - CustomDebugStringConvertible + +extension Result: CustomDebugStringConvertible { + /// The debug textual representation used when written to an output stream, which includes whether the result was a + /// success or failure in addition to the value or error. + public var debugDescription: String { + switch self { + case .success(let value): + return "SUCCESS: \(value)" + case .failure(let error): + return "FAILURE: \(error)" + } + } +} diff --git a/Pods/Alamofire/Source/ServerTrustPolicy.swift b/Pods/Alamofire/Source/ServerTrustPolicy.swift new file mode 100644 index 0000000..9c0e7c8 --- /dev/null +++ b/Pods/Alamofire/Source/ServerTrustPolicy.swift @@ -0,0 +1,307 @@ +// +// ServerTrustPolicy.swift +// +// Copyright (c) 2014-2016 Alamofire Software Foundation (http://alamofire.org/) +// +// Permission is hereby granted, free of charge, to any person obtaining a copy +// of this software and associated documentation files (the "Software"), to deal +// in the Software without restriction, including without limitation the rights +// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +// copies of the Software, and to permit persons to whom the Software is +// furnished to do so, subject to the following conditions: +// +// The above copyright notice and this permission notice shall be included in +// all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN +// THE SOFTWARE. +// + +import Foundation + +/// Responsible for managing the mapping of `ServerTrustPolicy` objects to a given host. +open class ServerTrustPolicyManager { + /// The dictionary of policies mapped to a particular host. + open let policies: [String: ServerTrustPolicy] + + /// Initializes the `ServerTrustPolicyManager` instance with the given policies. + /// + /// Since different servers and web services can have different leaf certificates, intermediate and even root + /// certficates, it is important to have the flexibility to specify evaluation policies on a per host basis. This + /// allows for scenarios such as using default evaluation for host1, certificate pinning for host2, public key + /// pinning for host3 and disabling evaluation for host4. + /// + /// - parameter policies: A dictionary of all policies mapped to a particular host. + /// + /// - returns: The new `ServerTrustPolicyManager` instance. + public init(policies: [String: ServerTrustPolicy]) { + self.policies = policies + } + + /// Returns the `ServerTrustPolicy` for the given host if applicable. + /// + /// By default, this method will return the policy that perfectly matches the given host. Subclasses could override + /// this method and implement more complex mapping implementations such as wildcards. + /// + /// - parameter host: The host to use when searching for a matching policy. + /// + /// - returns: The server trust policy for the given host if found. + open func serverTrustPolicy(forHost host: String) -> ServerTrustPolicy? { + return policies[host] + } +} + +// MARK: - + +extension URLSession { + private struct AssociatedKeys { + static var managerKey = "URLSession.ServerTrustPolicyManager" + } + + var serverTrustPolicyManager: ServerTrustPolicyManager? { + get { + return objc_getAssociatedObject(self, &AssociatedKeys.managerKey) as? ServerTrustPolicyManager + } + set (manager) { + objc_setAssociatedObject(self, &AssociatedKeys.managerKey, manager, .OBJC_ASSOCIATION_RETAIN_NONATOMIC) + } + } +} + +// MARK: - ServerTrustPolicy + +/// The `ServerTrustPolicy` evaluates the server trust generally provided by an `NSURLAuthenticationChallenge` when +/// connecting to a server over a secure HTTPS connection. The policy configuration then evaluates the server trust +/// with a given set of criteria to determine whether the server trust is valid and the connection should be made. +/// +/// Using pinned certificates or public keys for evaluation helps prevent man-in-the-middle (MITM) attacks and other +/// vulnerabilities. Applications dealing with sensitive customer data or financial information are strongly encouraged +/// to route all communication over an HTTPS connection with pinning enabled. +/// +/// - performDefaultEvaluation: Uses the default server trust evaluation while allowing you to control whether to +/// validate the host provided by the challenge. Applications are encouraged to always +/// validate the host in production environments to guarantee the validity of the server's +/// certificate chain. +/// +/// - performRevokedEvaluation: Uses the default and revoked server trust evaluations allowing you to control whether to +/// validate the host provided by the challenge as well as specify the revocation flags for +/// testing for revoked certificates. Apple platforms did not start testing for revoked +/// certificates automatically until iOS 10.1, macOS 10.12 and tvOS 10.1 which is +/// demonstrated in our TLS tests. Applications are encouraged to always validate the host +/// in production environments to guarantee the validity of the server's certificate chain. +/// +/// - pinCertificates: Uses the pinned certificates to validate the server trust. The server trust is +/// considered valid if one of the pinned certificates match one of the server certificates. +/// By validating both the certificate chain and host, certificate pinning provides a very +/// secure form of server trust validation mitigating most, if not all, MITM attacks. +/// Applications are encouraged to always validate the host and require a valid certificate +/// chain in production environments. +/// +/// - pinPublicKeys: Uses the pinned public keys to validate the server trust. The server trust is considered +/// valid if one of the pinned public keys match one of the server certificate public keys. +/// By validating both the certificate chain and host, public key pinning provides a very +/// secure form of server trust validation mitigating most, if not all, MITM attacks. +/// Applications are encouraged to always validate the host and require a valid certificate +/// chain in production environments. +/// +/// - disableEvaluation: Disables all evaluation which in turn will always consider any server trust as valid. +/// +/// - customEvaluation: Uses the associated closure to evaluate the validity of the server trust. +public enum ServerTrustPolicy { + case performDefaultEvaluation(validateHost: Bool) + case performRevokedEvaluation(validateHost: Bool, revocationFlags: CFOptionFlags) + case pinCertificates(certificates: [SecCertificate], validateCertificateChain: Bool, validateHost: Bool) + case pinPublicKeys(publicKeys: [SecKey], validateCertificateChain: Bool, validateHost: Bool) + case disableEvaluation + case customEvaluation((_ serverTrust: SecTrust, _ host: String) -> Bool) + + // MARK: - Bundle Location + + /// Returns all certificates within the given bundle with a `.cer` file extension. + /// + /// - parameter bundle: The bundle to search for all `.cer` files. + /// + /// - returns: All certificates within the given bundle. + public static func certificates(in bundle: Bundle = Bundle.main) -> [SecCertificate] { + var certificates: [SecCertificate] = [] + + let paths = Set([".cer", ".CER", ".crt", ".CRT", ".der", ".DER"].map { fileExtension in + bundle.paths(forResourcesOfType: fileExtension, inDirectory: nil) + }.joined()) + + for path in paths { + if + let certificateData = try? Data(contentsOf: URL(fileURLWithPath: path)) as CFData, + let certificate = SecCertificateCreateWithData(nil, certificateData) + { + certificates.append(certificate) + } + } + + return certificates + } + + /// Returns all public keys within the given bundle with a `.cer` file extension. + /// + /// - parameter bundle: The bundle to search for all `*.cer` files. + /// + /// - returns: All public keys within the given bundle. + public static func publicKeys(in bundle: Bundle = Bundle.main) -> [SecKey] { + var publicKeys: [SecKey] = [] + + for certificate in certificates(in: bundle) { + if let publicKey = publicKey(for: certificate) { + publicKeys.append(publicKey) + } + } + + return publicKeys + } + + // MARK: - Evaluation + + /// Evaluates whether the server trust is valid for the given host. + /// + /// - parameter serverTrust: The server trust to evaluate. + /// - parameter host: The host of the challenge protection space. + /// + /// - returns: Whether the server trust is valid. + public func evaluate(_ serverTrust: SecTrust, forHost host: String) -> Bool { + var serverTrustIsValid = false + + switch self { + case let .performDefaultEvaluation(validateHost): + let policy = SecPolicyCreateSSL(true, validateHost ? host as CFString : nil) + SecTrustSetPolicies(serverTrust, policy) + + serverTrustIsValid = trustIsValid(serverTrust) + case let .performRevokedEvaluation(validateHost, revocationFlags): + let defaultPolicy = SecPolicyCreateSSL(true, validateHost ? host as CFString : nil) + let revokedPolicy = SecPolicyCreateRevocation(revocationFlags) + SecTrustSetPolicies(serverTrust, [defaultPolicy, revokedPolicy] as CFTypeRef) + + serverTrustIsValid = trustIsValid(serverTrust) + case let .pinCertificates(pinnedCertificates, validateCertificateChain, validateHost): + if validateCertificateChain { + let policy = SecPolicyCreateSSL(true, validateHost ? host as CFString : nil) + SecTrustSetPolicies(serverTrust, policy) + + SecTrustSetAnchorCertificates(serverTrust, pinnedCertificates as CFArray) + SecTrustSetAnchorCertificatesOnly(serverTrust, true) + + serverTrustIsValid = trustIsValid(serverTrust) + } else { + let serverCertificatesDataArray = certificateData(for: serverTrust) + let pinnedCertificatesDataArray = certificateData(for: pinnedCertificates) + + outerLoop: for serverCertificateData in serverCertificatesDataArray { + for pinnedCertificateData in pinnedCertificatesDataArray { + if serverCertificateData == pinnedCertificateData { + serverTrustIsValid = true + break outerLoop + } + } + } + } + case let .pinPublicKeys(pinnedPublicKeys, validateCertificateChain, validateHost): + var certificateChainEvaluationPassed = true + + if validateCertificateChain { + let policy = SecPolicyCreateSSL(true, validateHost ? host as CFString : nil) + SecTrustSetPolicies(serverTrust, policy) + + certificateChainEvaluationPassed = trustIsValid(serverTrust) + } + + if certificateChainEvaluationPassed { + outerLoop: for serverPublicKey in ServerTrustPolicy.publicKeys(for: serverTrust) as [AnyObject] { + for pinnedPublicKey in pinnedPublicKeys as [AnyObject] { + if serverPublicKey.isEqual(pinnedPublicKey) { + serverTrustIsValid = true + break outerLoop + } + } + } + } + case .disableEvaluation: + serverTrustIsValid = true + case let .customEvaluation(closure): + serverTrustIsValid = closure(serverTrust, host) + } + + return serverTrustIsValid + } + + // MARK: - Private - Trust Validation + + private func trustIsValid(_ trust: SecTrust) -> Bool { + var isValid = false + + var result = SecTrustResultType.invalid + let status = SecTrustEvaluate(trust, &result) + + if status == errSecSuccess { + let unspecified = SecTrustResultType.unspecified + let proceed = SecTrustResultType.proceed + + + isValid = result == unspecified || result == proceed + } + + return isValid + } + + // MARK: - Private - Certificate Data + + private func certificateData(for trust: SecTrust) -> [Data] { + var certificates: [SecCertificate] = [] + + for index in 0.. [Data] { + return certificates.map { SecCertificateCopyData($0) as Data } + } + + // MARK: - Private - Public Key Extraction + + private static func publicKeys(for trust: SecTrust) -> [SecKey] { + var publicKeys: [SecKey] = [] + + for index in 0.. SecKey? { + var publicKey: SecKey? + + let policy = SecPolicyCreateBasicX509() + var trust: SecTrust? + let trustCreationStatus = SecTrustCreateWithCertificates(certificate, policy, &trust) + + if let trust = trust, trustCreationStatus == errSecSuccess { + publicKey = SecTrustCopyPublicKey(trust) + } + + return publicKey + } +} diff --git a/Pods/Alamofire/Source/SessionDelegate.swift b/Pods/Alamofire/Source/SessionDelegate.swift new file mode 100644 index 0000000..15268c3 --- /dev/null +++ b/Pods/Alamofire/Source/SessionDelegate.swift @@ -0,0 +1,721 @@ +// +// SessionDelegate.swift +// +// Copyright (c) 2014-2016 Alamofire Software Foundation (http://alamofire.org/) +// +// Permission is hereby granted, free of charge, to any person obtaining a copy +// of this software and associated documentation files (the "Software"), to deal +// in the Software without restriction, including without limitation the rights +// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +// copies of the Software, and to permit persons to whom the Software is +// furnished to do so, subject to the following conditions: +// +// The above copyright notice and this permission notice shall be included in +// all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN +// THE SOFTWARE. +// + +import Foundation + +/// Responsible for handling all delegate callbacks for the underlying session. +open class SessionDelegate: NSObject { + + // MARK: URLSessionDelegate Overrides + + /// Overrides default behavior for URLSessionDelegate method `urlSession(_:didBecomeInvalidWithError:)`. + open var sessionDidBecomeInvalidWithError: ((URLSession, Error?) -> Void)? + + /// Overrides default behavior for URLSessionDelegate method `urlSession(_:didReceive:completionHandler:)`. + open var sessionDidReceiveChallenge: ((URLSession, URLAuthenticationChallenge) -> (URLSession.AuthChallengeDisposition, URLCredential?))? + + /// Overrides all behavior for URLSessionDelegate method `urlSession(_:didReceive:completionHandler:)` and requires the caller to call the `completionHandler`. + open var sessionDidReceiveChallengeWithCompletion: ((URLSession, URLAuthenticationChallenge, (URLSession.AuthChallengeDisposition, URLCredential?) -> Void) -> Void)? + + /// Overrides default behavior for URLSessionDelegate method `urlSessionDidFinishEvents(forBackgroundURLSession:)`. + open var sessionDidFinishEventsForBackgroundURLSession: ((URLSession) -> Void)? + + // MARK: URLSessionTaskDelegate Overrides + + /// Overrides default behavior for URLSessionTaskDelegate method `urlSession(_:task:willPerformHTTPRedirection:newRequest:completionHandler:)`. + open var taskWillPerformHTTPRedirection: ((URLSession, URLSessionTask, HTTPURLResponse, URLRequest) -> URLRequest?)? + + /// Overrides all behavior for URLSessionTaskDelegate method `urlSession(_:task:willPerformHTTPRedirection:newRequest:completionHandler:)` and + /// requires the caller to call the `completionHandler`. + open var taskWillPerformHTTPRedirectionWithCompletion: ((URLSession, URLSessionTask, HTTPURLResponse, URLRequest, (URLRequest?) -> Void) -> Void)? + + /// Overrides default behavior for URLSessionTaskDelegate method `urlSession(_:task:didReceive:completionHandler:)`. + open var taskDidReceiveChallenge: ((URLSession, URLSessionTask, URLAuthenticationChallenge) -> (URLSession.AuthChallengeDisposition, URLCredential?))? + + /// Overrides all behavior for URLSessionTaskDelegate method `urlSession(_:task:didReceive:completionHandler:)` and + /// requires the caller to call the `completionHandler`. + open var taskDidReceiveChallengeWithCompletion: ((URLSession, URLSessionTask, URLAuthenticationChallenge, (URLSession.AuthChallengeDisposition, URLCredential?) -> Void) -> Void)? + + /// Overrides default behavior for URLSessionTaskDelegate method `urlSession(_:task:needNewBodyStream:)`. + open var taskNeedNewBodyStream: ((URLSession, URLSessionTask) -> InputStream?)? + + /// Overrides all behavior for URLSessionTaskDelegate method `urlSession(_:task:needNewBodyStream:)` and + /// requires the caller to call the `completionHandler`. + open var taskNeedNewBodyStreamWithCompletion: ((URLSession, URLSessionTask, (InputStream?) -> Void) -> Void)? + + /// Overrides default behavior for URLSessionTaskDelegate method `urlSession(_:task:didSendBodyData:totalBytesSent:totalBytesExpectedToSend:)`. + open var taskDidSendBodyData: ((URLSession, URLSessionTask, Int64, Int64, Int64) -> Void)? + + /// Overrides default behavior for URLSessionTaskDelegate method `urlSession(_:task:didCompleteWithError:)`. + open var taskDidComplete: ((URLSession, URLSessionTask, Error?) -> Void)? + + // MARK: URLSessionDataDelegate Overrides + + /// Overrides default behavior for URLSessionDataDelegate method `urlSession(_:dataTask:didReceive:completionHandler:)`. + open var dataTaskDidReceiveResponse: ((URLSession, URLSessionDataTask, URLResponse) -> URLSession.ResponseDisposition)? + + /// Overrides all behavior for URLSessionDataDelegate method `urlSession(_:dataTask:didReceive:completionHandler:)` and + /// requires caller to call the `completionHandler`. + open var dataTaskDidReceiveResponseWithCompletion: ((URLSession, URLSessionDataTask, URLResponse, (URLSession.ResponseDisposition) -> Void) -> Void)? + + /// Overrides default behavior for URLSessionDataDelegate method `urlSession(_:dataTask:didBecome:)`. + open var dataTaskDidBecomeDownloadTask: ((URLSession, URLSessionDataTask, URLSessionDownloadTask) -> Void)? + + /// Overrides default behavior for URLSessionDataDelegate method `urlSession(_:dataTask:didReceive:)`. + open var dataTaskDidReceiveData: ((URLSession, URLSessionDataTask, Data) -> Void)? + + /// Overrides default behavior for URLSessionDataDelegate method `urlSession(_:dataTask:willCacheResponse:completionHandler:)`. + open var dataTaskWillCacheResponse: ((URLSession, URLSessionDataTask, CachedURLResponse) -> CachedURLResponse?)? + + /// Overrides all behavior for URLSessionDataDelegate method `urlSession(_:dataTask:willCacheResponse:completionHandler:)` and + /// requires caller to call the `completionHandler`. + open var dataTaskWillCacheResponseWithCompletion: ((URLSession, URLSessionDataTask, CachedURLResponse, (CachedURLResponse?) -> Void) -> Void)? + + // MARK: URLSessionDownloadDelegate Overrides + + /// Overrides default behavior for URLSessionDownloadDelegate method `urlSession(_:downloadTask:didFinishDownloadingTo:)`. + open var downloadTaskDidFinishDownloadingToURL: ((URLSession, URLSessionDownloadTask, URL) -> Void)? + + /// Overrides default behavior for URLSessionDownloadDelegate method `urlSession(_:downloadTask:didWriteData:totalBytesWritten:totalBytesExpectedToWrite:)`. + open var downloadTaskDidWriteData: ((URLSession, URLSessionDownloadTask, Int64, Int64, Int64) -> Void)? + + /// Overrides default behavior for URLSessionDownloadDelegate method `urlSession(_:downloadTask:didResumeAtOffset:expectedTotalBytes:)`. + open var downloadTaskDidResumeAtOffset: ((URLSession, URLSessionDownloadTask, Int64, Int64) -> Void)? + + // MARK: URLSessionStreamDelegate Overrides + +#if !os(watchOS) + + /// Overrides default behavior for URLSessionStreamDelegate method `urlSession(_:readClosedFor:)`. + @available(iOS 9.0, macOS 10.11, tvOS 9.0, *) + open var streamTaskReadClosed: ((URLSession, URLSessionStreamTask) -> Void)? { + get { + return _streamTaskReadClosed as? (URLSession, URLSessionStreamTask) -> Void + } + set { + _streamTaskReadClosed = newValue + } + } + + /// Overrides default behavior for URLSessionStreamDelegate method `urlSession(_:writeClosedFor:)`. + @available(iOS 9.0, macOS 10.11, tvOS 9.0, *) + open var streamTaskWriteClosed: ((URLSession, URLSessionStreamTask) -> Void)? { + get { + return _streamTaskWriteClosed as? (URLSession, URLSessionStreamTask) -> Void + } + set { + _streamTaskWriteClosed = newValue + } + } + + /// Overrides default behavior for URLSessionStreamDelegate method `urlSession(_:betterRouteDiscoveredFor:)`. + @available(iOS 9.0, macOS 10.11, tvOS 9.0, *) + open var streamTaskBetterRouteDiscovered: ((URLSession, URLSessionStreamTask) -> Void)? { + get { + return _streamTaskBetterRouteDiscovered as? (URLSession, URLSessionStreamTask) -> Void + } + set { + _streamTaskBetterRouteDiscovered = newValue + } + } + + /// Overrides default behavior for URLSessionStreamDelegate method `urlSession(_:streamTask:didBecome:outputStream:)`. + @available(iOS 9.0, macOS 10.11, tvOS 9.0, *) + open var streamTaskDidBecomeInputAndOutputStreams: ((URLSession, URLSessionStreamTask, InputStream, OutputStream) -> Void)? { + get { + return _streamTaskDidBecomeInputStream as? (URLSession, URLSessionStreamTask, InputStream, OutputStream) -> Void + } + set { + _streamTaskDidBecomeInputStream = newValue + } + } + + var _streamTaskReadClosed: Any? + var _streamTaskWriteClosed: Any? + var _streamTaskBetterRouteDiscovered: Any? + var _streamTaskDidBecomeInputStream: Any? + +#endif + + // MARK: Properties + + var retrier: RequestRetrier? + weak var sessionManager: SessionManager? + + private var requests: [Int: Request] = [:] + private let lock = NSLock() + + /// Access the task delegate for the specified task in a thread-safe manner. + open subscript(task: URLSessionTask) -> Request? { + get { + lock.lock() ; defer { lock.unlock() } + return requests[task.taskIdentifier] + } + set { + lock.lock() ; defer { lock.unlock() } + requests[task.taskIdentifier] = newValue + } + } + + // MARK: Lifecycle + + /// Initializes the `SessionDelegate` instance. + /// + /// - returns: The new `SessionDelegate` instance. + public override init() { + super.init() + } + + // MARK: NSObject Overrides + + /// Returns a `Bool` indicating whether the `SessionDelegate` implements or inherits a method that can respond + /// to a specified message. + /// + /// - parameter selector: A selector that identifies a message. + /// + /// - returns: `true` if the receiver implements or inherits a method that can respond to selector, otherwise `false`. + open override func responds(to selector: Selector) -> Bool { + #if !os(macOS) + if selector == #selector(URLSessionDelegate.urlSessionDidFinishEvents(forBackgroundURLSession:)) { + return sessionDidFinishEventsForBackgroundURLSession != nil + } + #endif + + #if !os(watchOS) + if #available(iOS 9.0, macOS 10.11, tvOS 9.0, *) { + switch selector { + case #selector(URLSessionStreamDelegate.urlSession(_:readClosedFor:)): + return streamTaskReadClosed != nil + case #selector(URLSessionStreamDelegate.urlSession(_:writeClosedFor:)): + return streamTaskWriteClosed != nil + case #selector(URLSessionStreamDelegate.urlSession(_:betterRouteDiscoveredFor:)): + return streamTaskBetterRouteDiscovered != nil + case #selector(URLSessionStreamDelegate.urlSession(_:streamTask:didBecome:outputStream:)): + return streamTaskDidBecomeInputAndOutputStreams != nil + default: + break + } + } + #endif + + switch selector { + case #selector(URLSessionDelegate.urlSession(_:didBecomeInvalidWithError:)): + return sessionDidBecomeInvalidWithError != nil + case #selector(URLSessionDelegate.urlSession(_:didReceive:completionHandler:)): + return (sessionDidReceiveChallenge != nil || sessionDidReceiveChallengeWithCompletion != nil) + case #selector(URLSessionTaskDelegate.urlSession(_:task:willPerformHTTPRedirection:newRequest:completionHandler:)): + return (taskWillPerformHTTPRedirection != nil || taskWillPerformHTTPRedirectionWithCompletion != nil) + case #selector(URLSessionDataDelegate.urlSession(_:dataTask:didReceive:completionHandler:)): + return (dataTaskDidReceiveResponse != nil || dataTaskDidReceiveResponseWithCompletion != nil) + default: + return type(of: self).instancesRespond(to: selector) + } + } +} + +// MARK: - URLSessionDelegate + +extension SessionDelegate: URLSessionDelegate { + /// Tells the delegate that the session has been invalidated. + /// + /// - parameter session: The session object that was invalidated. + /// - parameter error: The error that caused invalidation, or nil if the invalidation was explicit. + open func urlSession(_ session: URLSession, didBecomeInvalidWithError error: Error?) { + sessionDidBecomeInvalidWithError?(session, error) + } + + /// Requests credentials from the delegate in response to a session-level authentication request from the + /// remote server. + /// + /// - parameter session: The session containing the task that requested authentication. + /// - parameter challenge: An object that contains the request for authentication. + /// - parameter completionHandler: A handler that your delegate method must call providing the disposition + /// and credential. + open func urlSession( + _ session: URLSession, + didReceive challenge: URLAuthenticationChallenge, + completionHandler: @escaping (URLSession.AuthChallengeDisposition, URLCredential?) -> Void) + { + guard sessionDidReceiveChallengeWithCompletion == nil else { + sessionDidReceiveChallengeWithCompletion?(session, challenge, completionHandler) + return + } + + var disposition: URLSession.AuthChallengeDisposition = .performDefaultHandling + var credential: URLCredential? + + if let sessionDidReceiveChallenge = sessionDidReceiveChallenge { + (disposition, credential) = sessionDidReceiveChallenge(session, challenge) + } else if challenge.protectionSpace.authenticationMethod == NSURLAuthenticationMethodServerTrust { + let host = challenge.protectionSpace.host + + if + let serverTrustPolicy = session.serverTrustPolicyManager?.serverTrustPolicy(forHost: host), + let serverTrust = challenge.protectionSpace.serverTrust + { + if serverTrustPolicy.evaluate(serverTrust, forHost: host) { + disposition = .useCredential + credential = URLCredential(trust: serverTrust) + } else { + disposition = .cancelAuthenticationChallenge + } + } + } + + completionHandler(disposition, credential) + } + +#if !os(macOS) + + /// Tells the delegate that all messages enqueued for a session have been delivered. + /// + /// - parameter session: The session that no longer has any outstanding requests. + open func urlSessionDidFinishEvents(forBackgroundURLSession session: URLSession) { + sessionDidFinishEventsForBackgroundURLSession?(session) + } + +#endif +} + +// MARK: - URLSessionTaskDelegate + +extension SessionDelegate: URLSessionTaskDelegate { + /// Tells the delegate that the remote server requested an HTTP redirect. + /// + /// - parameter session: The session containing the task whose request resulted in a redirect. + /// - parameter task: The task whose request resulted in a redirect. + /// - parameter response: An object containing the server’s response to the original request. + /// - parameter request: A URL request object filled out with the new location. + /// - parameter completionHandler: A closure that your handler should call with either the value of the request + /// parameter, a modified URL request object, or NULL to refuse the redirect and + /// return the body of the redirect response. + open func urlSession( + _ session: URLSession, + task: URLSessionTask, + willPerformHTTPRedirection response: HTTPURLResponse, + newRequest request: URLRequest, + completionHandler: @escaping (URLRequest?) -> Void) + { + guard taskWillPerformHTTPRedirectionWithCompletion == nil else { + taskWillPerformHTTPRedirectionWithCompletion?(session, task, response, request, completionHandler) + return + } + + var redirectRequest: URLRequest? = request + + if let taskWillPerformHTTPRedirection = taskWillPerformHTTPRedirection { + redirectRequest = taskWillPerformHTTPRedirection(session, task, response, request) + } + + completionHandler(redirectRequest) + } + + /// Requests credentials from the delegate in response to an authentication request from the remote server. + /// + /// - parameter session: The session containing the task whose request requires authentication. + /// - parameter task: The task whose request requires authentication. + /// - parameter challenge: An object that contains the request for authentication. + /// - parameter completionHandler: A handler that your delegate method must call providing the disposition + /// and credential. + open func urlSession( + _ session: URLSession, + task: URLSessionTask, + didReceive challenge: URLAuthenticationChallenge, + completionHandler: @escaping (URLSession.AuthChallengeDisposition, URLCredential?) -> Void) + { + guard taskDidReceiveChallengeWithCompletion == nil else { + taskDidReceiveChallengeWithCompletion?(session, task, challenge, completionHandler) + return + } + + if let taskDidReceiveChallenge = taskDidReceiveChallenge { + let result = taskDidReceiveChallenge(session, task, challenge) + completionHandler(result.0, result.1) + } else if let delegate = self[task]?.delegate { + delegate.urlSession( + session, + task: task, + didReceive: challenge, + completionHandler: completionHandler + ) + } else { + urlSession(session, didReceive: challenge, completionHandler: completionHandler) + } + } + + /// Tells the delegate when a task requires a new request body stream to send to the remote server. + /// + /// - parameter session: The session containing the task that needs a new body stream. + /// - parameter task: The task that needs a new body stream. + /// - parameter completionHandler: A completion handler that your delegate method should call with the new body stream. + open func urlSession( + _ session: URLSession, + task: URLSessionTask, + needNewBodyStream completionHandler: @escaping (InputStream?) -> Void) + { + guard taskNeedNewBodyStreamWithCompletion == nil else { + taskNeedNewBodyStreamWithCompletion?(session, task, completionHandler) + return + } + + if let taskNeedNewBodyStream = taskNeedNewBodyStream { + completionHandler(taskNeedNewBodyStream(session, task)) + } else if let delegate = self[task]?.delegate { + delegate.urlSession(session, task: task, needNewBodyStream: completionHandler) + } + } + + /// Periodically informs the delegate of the progress of sending body content to the server. + /// + /// - parameter session: The session containing the data task. + /// - parameter task: The data task. + /// - parameter bytesSent: The number of bytes sent since the last time this delegate method was called. + /// - parameter totalBytesSent: The total number of bytes sent so far. + /// - parameter totalBytesExpectedToSend: The expected length of the body data. + open func urlSession( + _ session: URLSession, + task: URLSessionTask, + didSendBodyData bytesSent: Int64, + totalBytesSent: Int64, + totalBytesExpectedToSend: Int64) + { + if let taskDidSendBodyData = taskDidSendBodyData { + taskDidSendBodyData(session, task, bytesSent, totalBytesSent, totalBytesExpectedToSend) + } else if let delegate = self[task]?.delegate as? UploadTaskDelegate { + delegate.URLSession( + session, + task: task, + didSendBodyData: bytesSent, + totalBytesSent: totalBytesSent, + totalBytesExpectedToSend: totalBytesExpectedToSend + ) + } + } + +#if !os(watchOS) + + /// Tells the delegate that the session finished collecting metrics for the task. + /// + /// - parameter session: The session collecting the metrics. + /// - parameter task: The task whose metrics have been collected. + /// - parameter metrics: The collected metrics. + @available(iOS 10.0, macOS 10.12, tvOS 10.0, *) + @objc(URLSession:task:didFinishCollectingMetrics:) + open func urlSession(_ session: URLSession, task: URLSessionTask, didFinishCollecting metrics: URLSessionTaskMetrics) { + self[task]?.delegate.metrics = metrics + } + +#endif + + /// Tells the delegate that the task finished transferring data. + /// + /// - parameter session: The session containing the task whose request finished transferring data. + /// - parameter task: The task whose request finished transferring data. + /// - parameter error: If an error occurred, an error object indicating how the transfer failed, otherwise nil. + open func urlSession(_ session: URLSession, task: URLSessionTask, didCompleteWithError error: Error?) { + /// Executed after it is determined that the request is not going to be retried + let completeTask: (URLSession, URLSessionTask, Error?) -> Void = { [weak self] session, task, error in + guard let strongSelf = self else { return } + + if let taskDidComplete = strongSelf.taskDidComplete { + taskDidComplete(session, task, error) + } else if let delegate = strongSelf[task]?.delegate { + delegate.urlSession(session, task: task, didCompleteWithError: error) + } + + NotificationCenter.default.post( + name: Notification.Name.Task.DidComplete, + object: strongSelf, + userInfo: [Notification.Key.Task: task] + ) + + strongSelf[task] = nil + } + + guard let request = self[task], let sessionManager = sessionManager else { + completeTask(session, task, error) + return + } + + // Run all validations on the request before checking if an error occurred + request.validations.forEach { $0() } + + // Determine whether an error has occurred + var error: Error? = error + + if let taskDelegate = self[task]?.delegate, taskDelegate.error != nil { + error = taskDelegate.error + } + + /// If an error occurred and the retrier is set, asynchronously ask the retrier if the request + /// should be retried. Otherwise, complete the task by notifying the task delegate. + if let retrier = retrier, let error = error { + retrier.should(sessionManager, retry: request, with: error) { [weak self] shouldRetry, timeDelay in + guard shouldRetry else { completeTask(session, task, error) ; return } + + DispatchQueue.utility.after(timeDelay) { [weak self] in + guard let strongSelf = self else { return } + + let retrySucceeded = strongSelf.sessionManager?.retry(request) ?? false + + if retrySucceeded, let task = request.task { + strongSelf[task] = request + return + } else { + completeTask(session, task, error) + } + } + } + } else { + completeTask(session, task, error) + } + } +} + +// MARK: - URLSessionDataDelegate + +extension SessionDelegate: URLSessionDataDelegate { + /// Tells the delegate that the data task received the initial reply (headers) from the server. + /// + /// - parameter session: The session containing the data task that received an initial reply. + /// - parameter dataTask: The data task that received an initial reply. + /// - parameter response: A URL response object populated with headers. + /// - parameter completionHandler: A completion handler that your code calls to continue the transfer, passing a + /// constant to indicate whether the transfer should continue as a data task or + /// should become a download task. + open func urlSession( + _ session: URLSession, + dataTask: URLSessionDataTask, + didReceive response: URLResponse, + completionHandler: @escaping (URLSession.ResponseDisposition) -> Void) + { + guard dataTaskDidReceiveResponseWithCompletion == nil else { + dataTaskDidReceiveResponseWithCompletion?(session, dataTask, response, completionHandler) + return + } + + var disposition: URLSession.ResponseDisposition = .allow + + if let dataTaskDidReceiveResponse = dataTaskDidReceiveResponse { + disposition = dataTaskDidReceiveResponse(session, dataTask, response) + } + + completionHandler(disposition) + } + + /// Tells the delegate that the data task was changed to a download task. + /// + /// - parameter session: The session containing the task that was replaced by a download task. + /// - parameter dataTask: The data task that was replaced by a download task. + /// - parameter downloadTask: The new download task that replaced the data task. + open func urlSession( + _ session: URLSession, + dataTask: URLSessionDataTask, + didBecome downloadTask: URLSessionDownloadTask) + { + if let dataTaskDidBecomeDownloadTask = dataTaskDidBecomeDownloadTask { + dataTaskDidBecomeDownloadTask(session, dataTask, downloadTask) + } else { + self[downloadTask]?.delegate = DownloadTaskDelegate(task: downloadTask) + } + } + + /// Tells the delegate that the data task has received some of the expected data. + /// + /// - parameter session: The session containing the data task that provided data. + /// - parameter dataTask: The data task that provided data. + /// - parameter data: A data object containing the transferred data. + open func urlSession(_ session: URLSession, dataTask: URLSessionDataTask, didReceive data: Data) { + if let dataTaskDidReceiveData = dataTaskDidReceiveData { + dataTaskDidReceiveData(session, dataTask, data) + } else if let delegate = self[dataTask]?.delegate as? DataTaskDelegate { + delegate.urlSession(session, dataTask: dataTask, didReceive: data) + } + } + + /// Asks the delegate whether the data (or upload) task should store the response in the cache. + /// + /// - parameter session: The session containing the data (or upload) task. + /// - parameter dataTask: The data (or upload) task. + /// - parameter proposedResponse: The default caching behavior. This behavior is determined based on the current + /// caching policy and the values of certain received headers, such as the Pragma + /// and Cache-Control headers. + /// - parameter completionHandler: A block that your handler must call, providing either the original proposed + /// response, a modified version of that response, or NULL to prevent caching the + /// response. If your delegate implements this method, it must call this completion + /// handler; otherwise, your app leaks memory. + open func urlSession( + _ session: URLSession, + dataTask: URLSessionDataTask, + willCacheResponse proposedResponse: CachedURLResponse, + completionHandler: @escaping (CachedURLResponse?) -> Void) + { + guard dataTaskWillCacheResponseWithCompletion == nil else { + dataTaskWillCacheResponseWithCompletion?(session, dataTask, proposedResponse, completionHandler) + return + } + + if let dataTaskWillCacheResponse = dataTaskWillCacheResponse { + completionHandler(dataTaskWillCacheResponse(session, dataTask, proposedResponse)) + } else if let delegate = self[dataTask]?.delegate as? DataTaskDelegate { + delegate.urlSession( + session, + dataTask: dataTask, + willCacheResponse: proposedResponse, + completionHandler: completionHandler + ) + } else { + completionHandler(proposedResponse) + } + } +} + +// MARK: - URLSessionDownloadDelegate + +extension SessionDelegate: URLSessionDownloadDelegate { + /// Tells the delegate that a download task has finished downloading. + /// + /// - parameter session: The session containing the download task that finished. + /// - parameter downloadTask: The download task that finished. + /// - parameter location: A file URL for the temporary file. Because the file is temporary, you must either + /// open the file for reading or move it to a permanent location in your app’s sandbox + /// container directory before returning from this delegate method. + open func urlSession( + _ session: URLSession, + downloadTask: URLSessionDownloadTask, + didFinishDownloadingTo location: URL) + { + if let downloadTaskDidFinishDownloadingToURL = downloadTaskDidFinishDownloadingToURL { + downloadTaskDidFinishDownloadingToURL(session, downloadTask, location) + } else if let delegate = self[downloadTask]?.delegate as? DownloadTaskDelegate { + delegate.urlSession(session, downloadTask: downloadTask, didFinishDownloadingTo: location) + } + } + + /// Periodically informs the delegate about the download’s progress. + /// + /// - parameter session: The session containing the download task. + /// - parameter downloadTask: The download task. + /// - parameter bytesWritten: The number of bytes transferred since the last time this delegate + /// method was called. + /// - parameter totalBytesWritten: The total number of bytes transferred so far. + /// - parameter totalBytesExpectedToWrite: The expected length of the file, as provided by the Content-Length + /// header. If this header was not provided, the value is + /// `NSURLSessionTransferSizeUnknown`. + open func urlSession( + _ session: URLSession, + downloadTask: URLSessionDownloadTask, + didWriteData bytesWritten: Int64, + totalBytesWritten: Int64, + totalBytesExpectedToWrite: Int64) + { + if let downloadTaskDidWriteData = downloadTaskDidWriteData { + downloadTaskDidWriteData(session, downloadTask, bytesWritten, totalBytesWritten, totalBytesExpectedToWrite) + } else if let delegate = self[downloadTask]?.delegate as? DownloadTaskDelegate { + delegate.urlSession( + session, + downloadTask: downloadTask, + didWriteData: bytesWritten, + totalBytesWritten: totalBytesWritten, + totalBytesExpectedToWrite: totalBytesExpectedToWrite + ) + } + } + + /// Tells the delegate that the download task has resumed downloading. + /// + /// - parameter session: The session containing the download task that finished. + /// - parameter downloadTask: The download task that resumed. See explanation in the discussion. + /// - parameter fileOffset: If the file's cache policy or last modified date prevents reuse of the + /// existing content, then this value is zero. Otherwise, this value is an + /// integer representing the number of bytes on disk that do not need to be + /// retrieved again. + /// - parameter expectedTotalBytes: The expected length of the file, as provided by the Content-Length header. + /// If this header was not provided, the value is NSURLSessionTransferSizeUnknown. + open func urlSession( + _ session: URLSession, + downloadTask: URLSessionDownloadTask, + didResumeAtOffset fileOffset: Int64, + expectedTotalBytes: Int64) + { + if let downloadTaskDidResumeAtOffset = downloadTaskDidResumeAtOffset { + downloadTaskDidResumeAtOffset(session, downloadTask, fileOffset, expectedTotalBytes) + } else if let delegate = self[downloadTask]?.delegate as? DownloadTaskDelegate { + delegate.urlSession( + session, + downloadTask: downloadTask, + didResumeAtOffset: fileOffset, + expectedTotalBytes: expectedTotalBytes + ) + } + } +} + +// MARK: - URLSessionStreamDelegate + +#if !os(watchOS) + +@available(iOS 9.0, macOS 10.11, tvOS 9.0, *) +extension SessionDelegate: URLSessionStreamDelegate { + /// Tells the delegate that the read side of the connection has been closed. + /// + /// - parameter session: The session. + /// - parameter streamTask: The stream task. + open func urlSession(_ session: URLSession, readClosedFor streamTask: URLSessionStreamTask) { + streamTaskReadClosed?(session, streamTask) + } + + /// Tells the delegate that the write side of the connection has been closed. + /// + /// - parameter session: The session. + /// - parameter streamTask: The stream task. + open func urlSession(_ session: URLSession, writeClosedFor streamTask: URLSessionStreamTask) { + streamTaskWriteClosed?(session, streamTask) + } + + /// Tells the delegate that the system has determined that a better route to the host is available. + /// + /// - parameter session: The session. + /// - parameter streamTask: The stream task. + open func urlSession(_ session: URLSession, betterRouteDiscoveredFor streamTask: URLSessionStreamTask) { + streamTaskBetterRouteDiscovered?(session, streamTask) + } + + /// Tells the delegate that the stream task has been completed and provides the unopened stream objects. + /// + /// - parameter session: The session. + /// - parameter streamTask: The stream task. + /// - parameter inputStream: The new input stream. + /// - parameter outputStream: The new output stream. + open func urlSession( + _ session: URLSession, + streamTask: URLSessionStreamTask, + didBecome inputStream: InputStream, + outputStream: OutputStream) + { + streamTaskDidBecomeInputAndOutputStreams?(session, streamTask, inputStream, outputStream) + } +} + +#endif diff --git a/Pods/Alamofire/Source/SessionManager.swift b/Pods/Alamofire/Source/SessionManager.swift new file mode 100644 index 0000000..450f750 --- /dev/null +++ b/Pods/Alamofire/Source/SessionManager.swift @@ -0,0 +1,891 @@ +// +// SessionManager.swift +// +// Copyright (c) 2014-2016 Alamofire Software Foundation (http://alamofire.org/) +// +// Permission is hereby granted, free of charge, to any person obtaining a copy +// of this software and associated documentation files (the "Software"), to deal +// in the Software without restriction, including without limitation the rights +// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +// copies of the Software, and to permit persons to whom the Software is +// furnished to do so, subject to the following conditions: +// +// The above copyright notice and this permission notice shall be included in +// all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN +// THE SOFTWARE. +// + +import Foundation + +/// Responsible for creating and managing `Request` objects, as well as their underlying `NSURLSession`. +open class SessionManager { + + // MARK: - Helper Types + + /// Defines whether the `MultipartFormData` encoding was successful and contains result of the encoding as + /// associated values. + /// + /// - Success: Represents a successful `MultipartFormData` encoding and contains the new `UploadRequest` along with + /// streaming information. + /// - Failure: Used to represent a failure in the `MultipartFormData` encoding and also contains the encoding + /// error. + public enum MultipartFormDataEncodingResult { + case success(request: UploadRequest, streamingFromDisk: Bool, streamFileURL: URL?) + case failure(Error) + } + + // MARK: - Properties + + /// A default instance of `SessionManager`, used by top-level Alamofire request methods, and suitable for use + /// directly for any ad hoc requests. + open static let `default`: SessionManager = { + let configuration = URLSessionConfiguration.default + configuration.httpAdditionalHeaders = SessionManager.defaultHTTPHeaders + + return SessionManager(configuration: configuration) + }() + + /// Creates default values for the "Accept-Encoding", "Accept-Language" and "User-Agent" headers. + open static let defaultHTTPHeaders: HTTPHeaders = { + // Accept-Encoding HTTP Header; see https://tools.ietf.org/html/rfc7230#section-4.2.3 + let acceptEncoding: String = "gzip;q=1.0, compress;q=0.5" + + // Accept-Language HTTP Header; see https://tools.ietf.org/html/rfc7231#section-5.3.5 + let acceptLanguage = Locale.preferredLanguages.prefix(6).enumerated().map { index, languageCode in + let quality = 1.0 - (Double(index) * 0.1) + return "\(languageCode);q=\(quality)" + }.joined(separator: ", ") + + // User-Agent Header; see https://tools.ietf.org/html/rfc7231#section-5.5.3 + // Example: `iOS Example/1.0 (org.alamofire.iOS-Example; build:1; iOS 10.0.0) Alamofire/4.0.0` + let userAgent: String = { + if let info = Bundle.main.infoDictionary { + let executable = info[kCFBundleExecutableKey as String] as? String ?? "Unknown" + let bundle = info[kCFBundleIdentifierKey as String] as? String ?? "Unknown" + let appVersion = info["CFBundleShortVersionString"] as? String ?? "Unknown" + let appBuild = info[kCFBundleVersionKey as String] as? String ?? "Unknown" + + let osNameVersion: String = { + let version = ProcessInfo.processInfo.operatingSystemVersion + let versionString = "\(version.majorVersion).\(version.minorVersion).\(version.patchVersion)" + + let osName: String = { + #if os(iOS) + return "iOS" + #elseif os(watchOS) + return "watchOS" + #elseif os(tvOS) + return "tvOS" + #elseif os(macOS) + return "OS X" + #elseif os(Linux) + return "Linux" + #else + return "Unknown" + #endif + }() + + return "\(osName) \(versionString)" + }() + + let alamofireVersion: String = { + guard + let afInfo = Bundle(for: SessionManager.self).infoDictionary, + let build = afInfo["CFBundleShortVersionString"] + else { return "Unknown" } + + return "Alamofire/\(build)" + }() + + return "\(executable)/\(appVersion) (\(bundle); build:\(appBuild); \(osNameVersion)) \(alamofireVersion)" + } + + return "Alamofire" + }() + + return [ + "Accept-Encoding": acceptEncoding, + "Accept-Language": acceptLanguage, + "User-Agent": userAgent + ] + }() + + /// Default memory threshold used when encoding `MultipartFormData` in bytes. + open static let multipartFormDataEncodingMemoryThreshold: UInt64 = 10_000_000 + + /// The underlying session. + open let session: URLSession + + /// The session delegate handling all the task and session delegate callbacks. + open let delegate: SessionDelegate + + /// Whether to start requests immediately after being constructed. `true` by default. + open var startRequestsImmediately: Bool = true + + /// The request adapter called each time a new request is created. + open var adapter: RequestAdapter? + + /// The request retrier called each time a request encounters an error to determine whether to retry the request. + open var retrier: RequestRetrier? { + get { return delegate.retrier } + set { delegate.retrier = newValue } + } + + /// The background completion handler closure provided by the UIApplicationDelegate + /// `application:handleEventsForBackgroundURLSession:completionHandler:` method. By setting the background + /// completion handler, the SessionDelegate `sessionDidFinishEventsForBackgroundURLSession` closure implementation + /// will automatically call the handler. + /// + /// If you need to handle your own events before the handler is called, then you need to override the + /// SessionDelegate `sessionDidFinishEventsForBackgroundURLSession` and manually call the handler when finished. + /// + /// `nil` by default. + open var backgroundCompletionHandler: (() -> Void)? + + let queue = DispatchQueue(label: "org.alamofire.session-manager." + UUID().uuidString) + + // MARK: - Lifecycle + + /// Creates an instance with the specified `configuration`, `delegate` and `serverTrustPolicyManager`. + /// + /// - parameter configuration: The configuration used to construct the managed session. + /// `URLSessionConfiguration.default` by default. + /// - parameter delegate: The delegate used when initializing the session. `SessionDelegate()` by + /// default. + /// - parameter serverTrustPolicyManager: The server trust policy manager to use for evaluating all server trust + /// challenges. `nil` by default. + /// + /// - returns: The new `SessionManager` instance. + public init( + configuration: URLSessionConfiguration = URLSessionConfiguration.default, + delegate: SessionDelegate = SessionDelegate(), + serverTrustPolicyManager: ServerTrustPolicyManager? = nil) + { + self.delegate = delegate + self.session = URLSession(configuration: configuration, delegate: delegate, delegateQueue: nil) + + commonInit(serverTrustPolicyManager: serverTrustPolicyManager) + } + + /// Creates an instance with the specified `session`, `delegate` and `serverTrustPolicyManager`. + /// + /// - parameter session: The URL session. + /// - parameter delegate: The delegate of the URL session. Must equal the URL session's delegate. + /// - parameter serverTrustPolicyManager: The server trust policy manager to use for evaluating all server trust + /// challenges. `nil` by default. + /// + /// - returns: The new `SessionManager` instance if the URL session's delegate matches; `nil` otherwise. + public init?( + session: URLSession, + delegate: SessionDelegate, + serverTrustPolicyManager: ServerTrustPolicyManager? = nil) + { + guard delegate === session.delegate else { return nil } + + self.delegate = delegate + self.session = session + + commonInit(serverTrustPolicyManager: serverTrustPolicyManager) + } + + private func commonInit(serverTrustPolicyManager: ServerTrustPolicyManager?) { + session.serverTrustPolicyManager = serverTrustPolicyManager + + delegate.sessionManager = self + + delegate.sessionDidFinishEventsForBackgroundURLSession = { [weak self] session in + guard let strongSelf = self else { return } + DispatchQueue.main.async { strongSelf.backgroundCompletionHandler?() } + } + } + + deinit { + session.invalidateAndCancel() + } + + // MARK: - Data Request + + /// Creates a `DataRequest` to retrieve the contents of the specified `url`, `method`, `parameters`, `encoding` + /// and `headers`. + /// + /// - parameter url: The URL. + /// - parameter method: The HTTP method. `.get` by default. + /// - parameter parameters: The parameters. `nil` by default. + /// - parameter encoding: The parameter encoding. `URLEncoding.default` by default. + /// - parameter headers: The HTTP headers. `nil` by default. + /// + /// - returns: The created `DataRequest`. + @discardableResult + open func request( + _ url: URLConvertible, + method: HTTPMethod = .get, + parameters: Parameters? = nil, + encoding: ParameterEncoding = URLEncoding.default, + headers: HTTPHeaders? = nil) + -> DataRequest + { + var originalRequest: URLRequest? + + do { + originalRequest = try URLRequest(url: url, method: method, headers: headers) + let encodedURLRequest = try encoding.encode(originalRequest!, with: parameters) + return request(encodedURLRequest) + } catch { + return request(originalRequest, failedWith: error) + } + } + + /// Creates a `DataRequest` to retrieve the contents of a URL based on the specified `urlRequest`. + /// + /// If `startRequestsImmediately` is `true`, the request will have `resume()` called before being returned. + /// + /// - parameter urlRequest: The URL request. + /// + /// - returns: The created `DataRequest`. + open func request(_ urlRequest: URLRequestConvertible) -> DataRequest { + var originalRequest: URLRequest? + + do { + originalRequest = try urlRequest.asURLRequest() + let originalTask = DataRequest.Requestable(urlRequest: originalRequest!) + + let task = try originalTask.task(session: session, adapter: adapter, queue: queue) + let request = DataRequest(session: session, requestTask: .data(originalTask, task)) + + delegate[task] = request + + if startRequestsImmediately { request.resume() } + + return request + } catch { + return request(originalRequest, failedWith: error) + } + } + + // MARK: Private - Request Implementation + + private func request(_ urlRequest: URLRequest?, failedWith error: Error) -> DataRequest { + var requestTask: Request.RequestTask = .data(nil, nil) + + if let urlRequest = urlRequest { + let originalTask = DataRequest.Requestable(urlRequest: urlRequest) + requestTask = .data(originalTask, nil) + } + + let underlyingError = error.underlyingAdaptError ?? error + let request = DataRequest(session: session, requestTask: requestTask, error: underlyingError) + + if let retrier = retrier, error is AdaptError { + allowRetrier(retrier, toRetry: request, with: underlyingError) + } else { + if startRequestsImmediately { request.resume() } + } + + return request + } + + // MARK: - Download Request + + // MARK: URL Request + + /// Creates a `DownloadRequest` to retrieve the contents the specified `url`, `method`, `parameters`, `encoding`, + /// `headers` and save them to the `destination`. + /// + /// If `destination` is not specified, the contents will remain in the temporary location determined by the + /// underlying URL session. + /// + /// If `startRequestsImmediately` is `true`, the request will have `resume()` called before being returned. + /// + /// - parameter url: The URL. + /// - parameter method: The HTTP method. `.get` by default. + /// - parameter parameters: The parameters. `nil` by default. + /// - parameter encoding: The parameter encoding. `URLEncoding.default` by default. + /// - parameter headers: The HTTP headers. `nil` by default. + /// - parameter destination: The closure used to determine the destination of the downloaded file. `nil` by default. + /// + /// - returns: The created `DownloadRequest`. + @discardableResult + open func download( + _ url: URLConvertible, + method: HTTPMethod = .get, + parameters: Parameters? = nil, + encoding: ParameterEncoding = URLEncoding.default, + headers: HTTPHeaders? = nil, + to destination: DownloadRequest.DownloadFileDestination? = nil) + -> DownloadRequest + { + do { + let urlRequest = try URLRequest(url: url, method: method, headers: headers) + let encodedURLRequest = try encoding.encode(urlRequest, with: parameters) + return download(encodedURLRequest, to: destination) + } catch { + return download(nil, to: destination, failedWith: error) + } + } + + /// Creates a `DownloadRequest` to retrieve the contents of a URL based on the specified `urlRequest` and save + /// them to the `destination`. + /// + /// If `destination` is not specified, the contents will remain in the temporary location determined by the + /// underlying URL session. + /// + /// If `startRequestsImmediately` is `true`, the request will have `resume()` called before being returned. + /// + /// - parameter urlRequest: The URL request + /// - parameter destination: The closure used to determine the destination of the downloaded file. `nil` by default. + /// + /// - returns: The created `DownloadRequest`. + @discardableResult + open func download( + _ urlRequest: URLRequestConvertible, + to destination: DownloadRequest.DownloadFileDestination? = nil) + -> DownloadRequest + { + do { + let urlRequest = try urlRequest.asURLRequest() + return download(.request(urlRequest), to: destination) + } catch { + return download(nil, to: destination, failedWith: error) + } + } + + // MARK: Resume Data + + /// Creates a `DownloadRequest` from the `resumeData` produced from a previous request cancellation to retrieve + /// the contents of the original request and save them to the `destination`. + /// + /// If `destination` is not specified, the contents will remain in the temporary location determined by the + /// underlying URL session. + /// + /// If `startRequestsImmediately` is `true`, the request will have `resume()` called before being returned. + /// + /// On the latest release of all the Apple platforms (iOS 10, macOS 10.12, tvOS 10, watchOS 3), `resumeData` is broken + /// on background URL session configurations. There's an underlying bug in the `resumeData` generation logic where the + /// data is written incorrectly and will always fail to resume the download. For more information about the bug and + /// possible workarounds, please refer to the following Stack Overflow post: + /// + /// - http://stackoverflow.com/a/39347461/1342462 + /// + /// - parameter resumeData: The resume data. This is an opaque data blob produced by `URLSessionDownloadTask` + /// when a task is cancelled. See `URLSession -downloadTask(withResumeData:)` for + /// additional information. + /// - parameter destination: The closure used to determine the destination of the downloaded file. `nil` by default. + /// + /// - returns: The created `DownloadRequest`. + @discardableResult + open func download( + resumingWith resumeData: Data, + to destination: DownloadRequest.DownloadFileDestination? = nil) + -> DownloadRequest + { + return download(.resumeData(resumeData), to: destination) + } + + // MARK: Private - Download Implementation + + private func download( + _ downloadable: DownloadRequest.Downloadable, + to destination: DownloadRequest.DownloadFileDestination?) + -> DownloadRequest + { + do { + let task = try downloadable.task(session: session, adapter: adapter, queue: queue) + let download = DownloadRequest(session: session, requestTask: .download(downloadable, task)) + + download.downloadDelegate.destination = destination + + delegate[task] = download + + if startRequestsImmediately { download.resume() } + + return download + } catch { + return download(downloadable, to: destination, failedWith: error) + } + } + + private func download( + _ downloadable: DownloadRequest.Downloadable?, + to destination: DownloadRequest.DownloadFileDestination?, + failedWith error: Error) + -> DownloadRequest + { + var downloadTask: Request.RequestTask = .download(nil, nil) + + if let downloadable = downloadable { + downloadTask = .download(downloadable, nil) + } + + let underlyingError = error.underlyingAdaptError ?? error + + let download = DownloadRequest(session: session, requestTask: downloadTask, error: underlyingError) + download.downloadDelegate.destination = destination + + if let retrier = retrier, error is AdaptError { + allowRetrier(retrier, toRetry: download, with: underlyingError) + } else { + if startRequestsImmediately { download.resume() } + } + + return download + } + + // MARK: - Upload Request + + // MARK: File + + /// Creates an `UploadRequest` from the specified `url`, `method` and `headers` for uploading the `file`. + /// + /// If `startRequestsImmediately` is `true`, the request will have `resume()` called before being returned. + /// + /// - parameter file: The file to upload. + /// - parameter url: The URL. + /// - parameter method: The HTTP method. `.post` by default. + /// - parameter headers: The HTTP headers. `nil` by default. + /// + /// - returns: The created `UploadRequest`. + @discardableResult + open func upload( + _ fileURL: URL, + to url: URLConvertible, + method: HTTPMethod = .post, + headers: HTTPHeaders? = nil) + -> UploadRequest + { + do { + let urlRequest = try URLRequest(url: url, method: method, headers: headers) + return upload(fileURL, with: urlRequest) + } catch { + return upload(nil, failedWith: error) + } + } + + /// Creates a `UploadRequest` from the specified `urlRequest` for uploading the `file`. + /// + /// If `startRequestsImmediately` is `true`, the request will have `resume()` called before being returned. + /// + /// - parameter file: The file to upload. + /// - parameter urlRequest: The URL request. + /// + /// - returns: The created `UploadRequest`. + @discardableResult + open func upload(_ fileURL: URL, with urlRequest: URLRequestConvertible) -> UploadRequest { + do { + let urlRequest = try urlRequest.asURLRequest() + return upload(.file(fileURL, urlRequest)) + } catch { + return upload(nil, failedWith: error) + } + } + + // MARK: Data + + /// Creates an `UploadRequest` from the specified `url`, `method` and `headers` for uploading the `data`. + /// + /// If `startRequestsImmediately` is `true`, the request will have `resume()` called before being returned. + /// + /// - parameter data: The data to upload. + /// - parameter url: The URL. + /// - parameter method: The HTTP method. `.post` by default. + /// - parameter headers: The HTTP headers. `nil` by default. + /// + /// - returns: The created `UploadRequest`. + @discardableResult + open func upload( + _ data: Data, + to url: URLConvertible, + method: HTTPMethod = .post, + headers: HTTPHeaders? = nil) + -> UploadRequest + { + do { + let urlRequest = try URLRequest(url: url, method: method, headers: headers) + return upload(data, with: urlRequest) + } catch { + return upload(nil, failedWith: error) + } + } + + /// Creates an `UploadRequest` from the specified `urlRequest` for uploading the `data`. + /// + /// If `startRequestsImmediately` is `true`, the request will have `resume()` called before being returned. + /// + /// - parameter data: The data to upload. + /// - parameter urlRequest: The URL request. + /// + /// - returns: The created `UploadRequest`. + @discardableResult + open func upload(_ data: Data, with urlRequest: URLRequestConvertible) -> UploadRequest { + do { + let urlRequest = try urlRequest.asURLRequest() + return upload(.data(data, urlRequest)) + } catch { + return upload(nil, failedWith: error) + } + } + + // MARK: InputStream + + /// Creates an `UploadRequest` from the specified `url`, `method` and `headers` for uploading the `stream`. + /// + /// If `startRequestsImmediately` is `true`, the request will have `resume()` called before being returned. + /// + /// - parameter stream: The stream to upload. + /// - parameter url: The URL. + /// - parameter method: The HTTP method. `.post` by default. + /// - parameter headers: The HTTP headers. `nil` by default. + /// + /// - returns: The created `UploadRequest`. + @discardableResult + open func upload( + _ stream: InputStream, + to url: URLConvertible, + method: HTTPMethod = .post, + headers: HTTPHeaders? = nil) + -> UploadRequest + { + do { + let urlRequest = try URLRequest(url: url, method: method, headers: headers) + return upload(stream, with: urlRequest) + } catch { + return upload(nil, failedWith: error) + } + } + + /// Creates an `UploadRequest` from the specified `urlRequest` for uploading the `stream`. + /// + /// If `startRequestsImmediately` is `true`, the request will have `resume()` called before being returned. + /// + /// - parameter stream: The stream to upload. + /// - parameter urlRequest: The URL request. + /// + /// - returns: The created `UploadRequest`. + @discardableResult + open func upload(_ stream: InputStream, with urlRequest: URLRequestConvertible) -> UploadRequest { + do { + let urlRequest = try urlRequest.asURLRequest() + return upload(.stream(stream, urlRequest)) + } catch { + return upload(nil, failedWith: error) + } + } + + // MARK: MultipartFormData + + /// Encodes `multipartFormData` using `encodingMemoryThreshold` and calls `encodingCompletion` with new + /// `UploadRequest` using the `url`, `method` and `headers`. + /// + /// It is important to understand the memory implications of uploading `MultipartFormData`. If the cummulative + /// payload is small, encoding the data in-memory and directly uploading to a server is the by far the most + /// efficient approach. However, if the payload is too large, encoding the data in-memory could cause your app to + /// be terminated. Larger payloads must first be written to disk using input and output streams to keep the memory + /// footprint low, then the data can be uploaded as a stream from the resulting file. Streaming from disk MUST be + /// used for larger payloads such as video content. + /// + /// The `encodingMemoryThreshold` parameter allows Alamofire to automatically determine whether to encode in-memory + /// or stream from disk. If the content length of the `MultipartFormData` is below the `encodingMemoryThreshold`, + /// encoding takes place in-memory. If the content length exceeds the threshold, the data is streamed to disk + /// during the encoding process. Then the result is uploaded as data or as a stream depending on which encoding + /// technique was used. + /// + /// If `startRequestsImmediately` is `true`, the request will have `resume()` called before being returned. + /// + /// - parameter multipartFormData: The closure used to append body parts to the `MultipartFormData`. + /// - parameter encodingMemoryThreshold: The encoding memory threshold in bytes. + /// `multipartFormDataEncodingMemoryThreshold` by default. + /// - parameter url: The URL. + /// - parameter method: The HTTP method. `.post` by default. + /// - parameter headers: The HTTP headers. `nil` by default. + /// - parameter encodingCompletion: The closure called when the `MultipartFormData` encoding is complete. + open func upload( + multipartFormData: @escaping (MultipartFormData) -> Void, + usingThreshold encodingMemoryThreshold: UInt64 = SessionManager.multipartFormDataEncodingMemoryThreshold, + to url: URLConvertible, + method: HTTPMethod = .post, + headers: HTTPHeaders? = nil, + encodingCompletion: ((MultipartFormDataEncodingResult) -> Void)?) + { + do { + let urlRequest = try URLRequest(url: url, method: method, headers: headers) + + return upload( + multipartFormData: multipartFormData, + usingThreshold: encodingMemoryThreshold, + with: urlRequest, + encodingCompletion: encodingCompletion + ) + } catch { + DispatchQueue.main.async { encodingCompletion?(.failure(error)) } + } + } + + /// Encodes `multipartFormData` using `encodingMemoryThreshold` and calls `encodingCompletion` with new + /// `UploadRequest` using the `urlRequest`. + /// + /// It is important to understand the memory implications of uploading `MultipartFormData`. If the cummulative + /// payload is small, encoding the data in-memory and directly uploading to a server is the by far the most + /// efficient approach. However, if the payload is too large, encoding the data in-memory could cause your app to + /// be terminated. Larger payloads must first be written to disk using input and output streams to keep the memory + /// footprint low, then the data can be uploaded as a stream from the resulting file. Streaming from disk MUST be + /// used for larger payloads such as video content. + /// + /// The `encodingMemoryThreshold` parameter allows Alamofire to automatically determine whether to encode in-memory + /// or stream from disk. If the content length of the `MultipartFormData` is below the `encodingMemoryThreshold`, + /// encoding takes place in-memory. If the content length exceeds the threshold, the data is streamed to disk + /// during the encoding process. Then the result is uploaded as data or as a stream depending on which encoding + /// technique was used. + /// + /// If `startRequestsImmediately` is `true`, the request will have `resume()` called before being returned. + /// + /// - parameter multipartFormData: The closure used to append body parts to the `MultipartFormData`. + /// - parameter encodingMemoryThreshold: The encoding memory threshold in bytes. + /// `multipartFormDataEncodingMemoryThreshold` by default. + /// - parameter urlRequest: The URL request. + /// - parameter encodingCompletion: The closure called when the `MultipartFormData` encoding is complete. + open func upload( + multipartFormData: @escaping (MultipartFormData) -> Void, + usingThreshold encodingMemoryThreshold: UInt64 = SessionManager.multipartFormDataEncodingMemoryThreshold, + with urlRequest: URLRequestConvertible, + encodingCompletion: ((MultipartFormDataEncodingResult) -> Void)?) + { + DispatchQueue.global(qos: .utility).async { + let formData = MultipartFormData() + multipartFormData(formData) + + var tempFileURL: URL? + + do { + var urlRequestWithContentType = try urlRequest.asURLRequest() + urlRequestWithContentType.setValue(formData.contentType, forHTTPHeaderField: "Content-Type") + + let isBackgroundSession = self.session.configuration.identifier != nil + + if formData.contentLength < encodingMemoryThreshold && !isBackgroundSession { + let data = try formData.encode() + + let encodingResult = MultipartFormDataEncodingResult.success( + request: self.upload(data, with: urlRequestWithContentType), + streamingFromDisk: false, + streamFileURL: nil + ) + + DispatchQueue.main.async { encodingCompletion?(encodingResult) } + } else { + let fileManager = FileManager.default + let tempDirectoryURL = URL(fileURLWithPath: NSTemporaryDirectory()) + let directoryURL = tempDirectoryURL.appendingPathComponent("org.alamofire.manager/multipart.form.data") + let fileName = UUID().uuidString + let fileURL = directoryURL.appendingPathComponent(fileName) + + tempFileURL = fileURL + + var directoryError: Error? + + // Create directory inside serial queue to ensure two threads don't do this in parallel + self.queue.sync { + do { + try fileManager.createDirectory(at: directoryURL, withIntermediateDirectories: true, attributes: nil) + } catch { + directoryError = error + } + } + + if let directoryError = directoryError { throw directoryError } + + try formData.writeEncodedData(to: fileURL) + + let upload = self.upload(fileURL, with: urlRequestWithContentType) + + // Cleanup the temp file once the upload is complete + upload.delegate.queue.addOperation { + do { + try FileManager.default.removeItem(at: fileURL) + } catch { + // No-op + } + } + + DispatchQueue.main.async { + let encodingResult = MultipartFormDataEncodingResult.success( + request: upload, + streamingFromDisk: true, + streamFileURL: fileURL + ) + + encodingCompletion?(encodingResult) + } + } + } catch { + // Cleanup the temp file in the event that the multipart form data encoding failed + if let tempFileURL = tempFileURL { + do { + try FileManager.default.removeItem(at: tempFileURL) + } catch { + // No-op + } + } + + DispatchQueue.main.async { encodingCompletion?(.failure(error)) } + } + } + } + + // MARK: Private - Upload Implementation + + private func upload(_ uploadable: UploadRequest.Uploadable) -> UploadRequest { + do { + let task = try uploadable.task(session: session, adapter: adapter, queue: queue) + let upload = UploadRequest(session: session, requestTask: .upload(uploadable, task)) + + if case let .stream(inputStream, _) = uploadable { + upload.delegate.taskNeedNewBodyStream = { _, _ in inputStream } + } + + delegate[task] = upload + + if startRequestsImmediately { upload.resume() } + + return upload + } catch { + return upload(uploadable, failedWith: error) + } + } + + private func upload(_ uploadable: UploadRequest.Uploadable?, failedWith error: Error) -> UploadRequest { + var uploadTask: Request.RequestTask = .upload(nil, nil) + + if let uploadable = uploadable { + uploadTask = .upload(uploadable, nil) + } + + let underlyingError = error.underlyingAdaptError ?? error + let upload = UploadRequest(session: session, requestTask: uploadTask, error: underlyingError) + + if let retrier = retrier, error is AdaptError { + allowRetrier(retrier, toRetry: upload, with: underlyingError) + } else { + if startRequestsImmediately { upload.resume() } + } + + return upload + } + +#if !os(watchOS) + + // MARK: - Stream Request + + // MARK: Hostname and Port + + /// Creates a `StreamRequest` for bidirectional streaming using the `hostname` and `port`. + /// + /// If `startRequestsImmediately` is `true`, the request will have `resume()` called before being returned. + /// + /// - parameter hostName: The hostname of the server to connect to. + /// - parameter port: The port of the server to connect to. + /// + /// - returns: The created `StreamRequest`. + @discardableResult + @available(iOS 9.0, macOS 10.11, tvOS 9.0, *) + open func stream(withHostName hostName: String, port: Int) -> StreamRequest { + return stream(.stream(hostName: hostName, port: port)) + } + + // MARK: NetService + + /// Creates a `StreamRequest` for bidirectional streaming using the `netService`. + /// + /// If `startRequestsImmediately` is `true`, the request will have `resume()` called before being returned. + /// + /// - parameter netService: The net service used to identify the endpoint. + /// + /// - returns: The created `StreamRequest`. + @discardableResult + @available(iOS 9.0, macOS 10.11, tvOS 9.0, *) + open func stream(with netService: NetService) -> StreamRequest { + return stream(.netService(netService)) + } + + // MARK: Private - Stream Implementation + + @available(iOS 9.0, macOS 10.11, tvOS 9.0, *) + private func stream(_ streamable: StreamRequest.Streamable) -> StreamRequest { + do { + let task = try streamable.task(session: session, adapter: adapter, queue: queue) + let request = StreamRequest(session: session, requestTask: .stream(streamable, task)) + + delegate[task] = request + + if startRequestsImmediately { request.resume() } + + return request + } catch { + return stream(failedWith: error) + } + } + + @available(iOS 9.0, macOS 10.11, tvOS 9.0, *) + private func stream(failedWith error: Error) -> StreamRequest { + let stream = StreamRequest(session: session, requestTask: .stream(nil, nil), error: error) + if startRequestsImmediately { stream.resume() } + return stream + } + +#endif + + // MARK: - Internal - Retry Request + + func retry(_ request: Request) -> Bool { + guard let originalTask = request.originalTask else { return false } + + do { + let task = try originalTask.task(session: session, adapter: adapter, queue: queue) + + request.delegate.task = task // resets all task delegate data + + request.retryCount += 1 + request.startTime = CFAbsoluteTimeGetCurrent() + request.endTime = nil + + task.resume() + + return true + } catch { + request.delegate.error = error.underlyingAdaptError ?? error + return false + } + } + + private func allowRetrier(_ retrier: RequestRetrier, toRetry request: Request, with error: Error) { + DispatchQueue.utility.async { [weak self] in + guard let strongSelf = self else { return } + + retrier.should(strongSelf, retry: request, with: error) { shouldRetry, timeDelay in + guard let strongSelf = self else { return } + + guard shouldRetry else { + if strongSelf.startRequestsImmediately { request.resume() } + return + } + + DispatchQueue.utility.after(timeDelay) { + guard let strongSelf = self else { return } + + let retrySucceeded = strongSelf.retry(request) + + if retrySucceeded, let task = request.task { + strongSelf.delegate[task] = request + } else { + if strongSelf.startRequestsImmediately { request.resume() } + } + } + } + } + } +} diff --git a/Pods/Alamofire/Source/TaskDelegate.swift b/Pods/Alamofire/Source/TaskDelegate.swift new file mode 100644 index 0000000..d4fd216 --- /dev/null +++ b/Pods/Alamofire/Source/TaskDelegate.swift @@ -0,0 +1,453 @@ +// +// TaskDelegate.swift +// +// Copyright (c) 2014-2016 Alamofire Software Foundation (http://alamofire.org/) +// +// Permission is hereby granted, free of charge, to any person obtaining a copy +// of this software and associated documentation files (the "Software"), to deal +// in the Software without restriction, including without limitation the rights +// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +// copies of the Software, and to permit persons to whom the Software is +// furnished to do so, subject to the following conditions: +// +// The above copyright notice and this permission notice shall be included in +// all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN +// THE SOFTWARE. +// + +import Foundation + +/// The task delegate is responsible for handling all delegate callbacks for the underlying task as well as +/// executing all operations attached to the serial operation queue upon task completion. +open class TaskDelegate: NSObject { + + // MARK: Properties + + /// The serial operation queue used to execute all operations after the task completes. + open let queue: OperationQueue + + /// The data returned by the server. + public var data: Data? { return nil } + + /// The error generated throughout the lifecyle of the task. + public var error: Error? + + var task: URLSessionTask? { + didSet { reset() } + } + + var initialResponseTime: CFAbsoluteTime? + var credential: URLCredential? + var metrics: AnyObject? // URLSessionTaskMetrics + + // MARK: Lifecycle + + init(task: URLSessionTask?) { + self.task = task + + self.queue = { + let operationQueue = OperationQueue() + + operationQueue.maxConcurrentOperationCount = 1 + operationQueue.isSuspended = true + operationQueue.qualityOfService = .utility + + return operationQueue + }() + } + + func reset() { + error = nil + initialResponseTime = nil + } + + // MARK: URLSessionTaskDelegate + + var taskWillPerformHTTPRedirection: ((URLSession, URLSessionTask, HTTPURLResponse, URLRequest) -> URLRequest?)? + var taskDidReceiveChallenge: ((URLSession, URLSessionTask, URLAuthenticationChallenge) -> (URLSession.AuthChallengeDisposition, URLCredential?))? + var taskNeedNewBodyStream: ((URLSession, URLSessionTask) -> InputStream?)? + var taskDidCompleteWithError: ((URLSession, URLSessionTask, Error?) -> Void)? + + @objc(URLSession:task:willPerformHTTPRedirection:newRequest:completionHandler:) + func urlSession( + _ session: URLSession, + task: URLSessionTask, + willPerformHTTPRedirection response: HTTPURLResponse, + newRequest request: URLRequest, + completionHandler: @escaping (URLRequest?) -> Void) + { + var redirectRequest: URLRequest? = request + + if let taskWillPerformHTTPRedirection = taskWillPerformHTTPRedirection { + redirectRequest = taskWillPerformHTTPRedirection(session, task, response, request) + } + + completionHandler(redirectRequest) + } + + @objc(URLSession:task:didReceiveChallenge:completionHandler:) + func urlSession( + _ session: URLSession, + task: URLSessionTask, + didReceive challenge: URLAuthenticationChallenge, + completionHandler: @escaping (URLSession.AuthChallengeDisposition, URLCredential?) -> Void) + { + var disposition: URLSession.AuthChallengeDisposition = .performDefaultHandling + var credential: URLCredential? + + if let taskDidReceiveChallenge = taskDidReceiveChallenge { + (disposition, credential) = taskDidReceiveChallenge(session, task, challenge) + } else if challenge.protectionSpace.authenticationMethod == NSURLAuthenticationMethodServerTrust { + let host = challenge.protectionSpace.host + + if + let serverTrustPolicy = session.serverTrustPolicyManager?.serverTrustPolicy(forHost: host), + let serverTrust = challenge.protectionSpace.serverTrust + { + if serverTrustPolicy.evaluate(serverTrust, forHost: host) { + disposition = .useCredential + credential = URLCredential(trust: serverTrust) + } else { + disposition = .cancelAuthenticationChallenge + } + } + } else { + if challenge.previousFailureCount > 0 { + disposition = .rejectProtectionSpace + } else { + credential = self.credential ?? session.configuration.urlCredentialStorage?.defaultCredential(for: challenge.protectionSpace) + + if credential != nil { + disposition = .useCredential + } + } + } + + completionHandler(disposition, credential) + } + + @objc(URLSession:task:needNewBodyStream:) + func urlSession( + _ session: URLSession, + task: URLSessionTask, + needNewBodyStream completionHandler: @escaping (InputStream?) -> Void) + { + var bodyStream: InputStream? + + if let taskNeedNewBodyStream = taskNeedNewBodyStream { + bodyStream = taskNeedNewBodyStream(session, task) + } + + completionHandler(bodyStream) + } + + @objc(URLSession:task:didCompleteWithError:) + func urlSession(_ session: URLSession, task: URLSessionTask, didCompleteWithError error: Error?) { + if let taskDidCompleteWithError = taskDidCompleteWithError { + taskDidCompleteWithError(session, task, error) + } else { + if let error = error { + if self.error == nil { self.error = error } + + if + let downloadDelegate = self as? DownloadTaskDelegate, + let resumeData = (error as NSError).userInfo[NSURLSessionDownloadTaskResumeData] as? Data + { + downloadDelegate.resumeData = resumeData + } + } + + queue.isSuspended = false + } + } +} + +// MARK: - + +class DataTaskDelegate: TaskDelegate, URLSessionDataDelegate { + + // MARK: Properties + + var dataTask: URLSessionDataTask { return task as! URLSessionDataTask } + + override var data: Data? { + if dataStream != nil { + return nil + } else { + return mutableData + } + } + + var progress: Progress + var progressHandler: (closure: Request.ProgressHandler, queue: DispatchQueue)? + + var dataStream: ((_ data: Data) -> Void)? + + private var totalBytesReceived: Int64 = 0 + private var mutableData: Data + + private var expectedContentLength: Int64? + + // MARK: Lifecycle + + override init(task: URLSessionTask?) { + mutableData = Data() + progress = Progress(totalUnitCount: 0) + + super.init(task: task) + } + + override func reset() { + super.reset() + + progress = Progress(totalUnitCount: 0) + totalBytesReceived = 0 + mutableData = Data() + expectedContentLength = nil + } + + // MARK: URLSessionDataDelegate + + var dataTaskDidReceiveResponse: ((URLSession, URLSessionDataTask, URLResponse) -> URLSession.ResponseDisposition)? + var dataTaskDidBecomeDownloadTask: ((URLSession, URLSessionDataTask, URLSessionDownloadTask) -> Void)? + var dataTaskDidReceiveData: ((URLSession, URLSessionDataTask, Data) -> Void)? + var dataTaskWillCacheResponse: ((URLSession, URLSessionDataTask, CachedURLResponse) -> CachedURLResponse?)? + + func urlSession( + _ session: URLSession, + dataTask: URLSessionDataTask, + didReceive response: URLResponse, + completionHandler: @escaping (URLSession.ResponseDisposition) -> Void) + { + var disposition: URLSession.ResponseDisposition = .allow + + expectedContentLength = response.expectedContentLength + + if let dataTaskDidReceiveResponse = dataTaskDidReceiveResponse { + disposition = dataTaskDidReceiveResponse(session, dataTask, response) + } + + completionHandler(disposition) + } + + func urlSession( + _ session: URLSession, + dataTask: URLSessionDataTask, + didBecome downloadTask: URLSessionDownloadTask) + { + dataTaskDidBecomeDownloadTask?(session, dataTask, downloadTask) + } + + func urlSession(_ session: URLSession, dataTask: URLSessionDataTask, didReceive data: Data) { + if initialResponseTime == nil { initialResponseTime = CFAbsoluteTimeGetCurrent() } + + if let dataTaskDidReceiveData = dataTaskDidReceiveData { + dataTaskDidReceiveData(session, dataTask, data) + } else { + if let dataStream = dataStream { + dataStream(data) + } else { + mutableData.append(data) + } + + let bytesReceived = Int64(data.count) + totalBytesReceived += bytesReceived + let totalBytesExpected = dataTask.response?.expectedContentLength ?? NSURLSessionTransferSizeUnknown + + progress.totalUnitCount = totalBytesExpected + progress.completedUnitCount = totalBytesReceived + + if let progressHandler = progressHandler { + progressHandler.queue.async { progressHandler.closure(self.progress) } + } + } + } + + func urlSession( + _ session: URLSession, + dataTask: URLSessionDataTask, + willCacheResponse proposedResponse: CachedURLResponse, + completionHandler: @escaping (CachedURLResponse?) -> Void) + { + var cachedResponse: CachedURLResponse? = proposedResponse + + if let dataTaskWillCacheResponse = dataTaskWillCacheResponse { + cachedResponse = dataTaskWillCacheResponse(session, dataTask, proposedResponse) + } + + completionHandler(cachedResponse) + } +} + +// MARK: - + +class DownloadTaskDelegate: TaskDelegate, URLSessionDownloadDelegate { + + // MARK: Properties + + var downloadTask: URLSessionDownloadTask { return task as! URLSessionDownloadTask } + + var progress: Progress + var progressHandler: (closure: Request.ProgressHandler, queue: DispatchQueue)? + + var resumeData: Data? + override var data: Data? { return resumeData } + + var destination: DownloadRequest.DownloadFileDestination? + + var temporaryURL: URL? + var destinationURL: URL? + + var fileURL: URL? { return destination != nil ? destinationURL : temporaryURL } + + // MARK: Lifecycle + + override init(task: URLSessionTask?) { + progress = Progress(totalUnitCount: 0) + super.init(task: task) + } + + override func reset() { + super.reset() + + progress = Progress(totalUnitCount: 0) + resumeData = nil + } + + // MARK: URLSessionDownloadDelegate + + var downloadTaskDidFinishDownloadingToURL: ((URLSession, URLSessionDownloadTask, URL) -> URL)? + var downloadTaskDidWriteData: ((URLSession, URLSessionDownloadTask, Int64, Int64, Int64) -> Void)? + var downloadTaskDidResumeAtOffset: ((URLSession, URLSessionDownloadTask, Int64, Int64) -> Void)? + + func urlSession( + _ session: URLSession, + downloadTask: URLSessionDownloadTask, + didFinishDownloadingTo location: URL) + { + temporaryURL = location + + guard + let destination = destination, + let response = downloadTask.response as? HTTPURLResponse + else { return } + + let result = destination(location, response) + let destinationURL = result.destinationURL + let options = result.options + + self.destinationURL = destinationURL + + do { + if options.contains(.removePreviousFile), FileManager.default.fileExists(atPath: destinationURL.path) { + try FileManager.default.removeItem(at: destinationURL) + } + + if options.contains(.createIntermediateDirectories) { + let directory = destinationURL.deletingLastPathComponent() + try FileManager.default.createDirectory(at: directory, withIntermediateDirectories: true) + } + + try FileManager.default.moveItem(at: location, to: destinationURL) + } catch { + self.error = error + } + } + + func urlSession( + _ session: URLSession, + downloadTask: URLSessionDownloadTask, + didWriteData bytesWritten: Int64, + totalBytesWritten: Int64, + totalBytesExpectedToWrite: Int64) + { + if initialResponseTime == nil { initialResponseTime = CFAbsoluteTimeGetCurrent() } + + if let downloadTaskDidWriteData = downloadTaskDidWriteData { + downloadTaskDidWriteData( + session, + downloadTask, + bytesWritten, + totalBytesWritten, + totalBytesExpectedToWrite + ) + } else { + progress.totalUnitCount = totalBytesExpectedToWrite + progress.completedUnitCount = totalBytesWritten + + if let progressHandler = progressHandler { + progressHandler.queue.async { progressHandler.closure(self.progress) } + } + } + } + + func urlSession( + _ session: URLSession, + downloadTask: URLSessionDownloadTask, + didResumeAtOffset fileOffset: Int64, + expectedTotalBytes: Int64) + { + if let downloadTaskDidResumeAtOffset = downloadTaskDidResumeAtOffset { + downloadTaskDidResumeAtOffset(session, downloadTask, fileOffset, expectedTotalBytes) + } else { + progress.totalUnitCount = expectedTotalBytes + progress.completedUnitCount = fileOffset + } + } +} + +// MARK: - + +class UploadTaskDelegate: DataTaskDelegate { + + // MARK: Properties + + var uploadTask: URLSessionUploadTask { return task as! URLSessionUploadTask } + + var uploadProgress: Progress + var uploadProgressHandler: (closure: Request.ProgressHandler, queue: DispatchQueue)? + + // MARK: Lifecycle + + override init(task: URLSessionTask?) { + uploadProgress = Progress(totalUnitCount: 0) + super.init(task: task) + } + + override func reset() { + super.reset() + uploadProgress = Progress(totalUnitCount: 0) + } + + // MARK: URLSessionTaskDelegate + + var taskDidSendBodyData: ((URLSession, URLSessionTask, Int64, Int64, Int64) -> Void)? + + func URLSession( + _ session: URLSession, + task: URLSessionTask, + didSendBodyData bytesSent: Int64, + totalBytesSent: Int64, + totalBytesExpectedToSend: Int64) + { + if initialResponseTime == nil { initialResponseTime = CFAbsoluteTimeGetCurrent() } + + if let taskDidSendBodyData = taskDidSendBodyData { + taskDidSendBodyData(session, task, bytesSent, totalBytesSent, totalBytesExpectedToSend) + } else { + uploadProgress.totalUnitCount = totalBytesExpectedToSend + uploadProgress.completedUnitCount = totalBytesSent + + if let uploadProgressHandler = uploadProgressHandler { + uploadProgressHandler.queue.async { uploadProgressHandler.closure(self.uploadProgress) } + } + } + } +} diff --git a/Pods/Alamofire/Source/Timeline.swift b/Pods/Alamofire/Source/Timeline.swift new file mode 100644 index 0000000..1440989 --- /dev/null +++ b/Pods/Alamofire/Source/Timeline.swift @@ -0,0 +1,136 @@ +// +// Timeline.swift +// +// Copyright (c) 2014-2016 Alamofire Software Foundation (http://alamofire.org/) +// +// Permission is hereby granted, free of charge, to any person obtaining a copy +// of this software and associated documentation files (the "Software"), to deal +// in the Software without restriction, including without limitation the rights +// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +// copies of the Software, and to permit persons to whom the Software is +// furnished to do so, subject to the following conditions: +// +// The above copyright notice and this permission notice shall be included in +// all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN +// THE SOFTWARE. +// + +import Foundation + +/// Responsible for computing the timing metrics for the complete lifecycle of a `Request`. +public struct Timeline { + /// The time the request was initialized. + public let requestStartTime: CFAbsoluteTime + + /// The time the first bytes were received from or sent to the server. + public let initialResponseTime: CFAbsoluteTime + + /// The time when the request was completed. + public let requestCompletedTime: CFAbsoluteTime + + /// The time when the response serialization was completed. + public let serializationCompletedTime: CFAbsoluteTime + + /// The time interval in seconds from the time the request started to the initial response from the server. + public let latency: TimeInterval + + /// The time interval in seconds from the time the request started to the time the request completed. + public let requestDuration: TimeInterval + + /// The time interval in seconds from the time the request completed to the time response serialization completed. + public let serializationDuration: TimeInterval + + /// The time interval in seconds from the time the request started to the time response serialization completed. + public let totalDuration: TimeInterval + + /// Creates a new `Timeline` instance with the specified request times. + /// + /// - parameter requestStartTime: The time the request was initialized. Defaults to `0.0`. + /// - parameter initialResponseTime: The time the first bytes were received from or sent to the server. + /// Defaults to `0.0`. + /// - parameter requestCompletedTime: The time when the request was completed. Defaults to `0.0`. + /// - parameter serializationCompletedTime: The time when the response serialization was completed. Defaults + /// to `0.0`. + /// + /// - returns: The new `Timeline` instance. + public init( + requestStartTime: CFAbsoluteTime = 0.0, + initialResponseTime: CFAbsoluteTime = 0.0, + requestCompletedTime: CFAbsoluteTime = 0.0, + serializationCompletedTime: CFAbsoluteTime = 0.0) + { + self.requestStartTime = requestStartTime + self.initialResponseTime = initialResponseTime + self.requestCompletedTime = requestCompletedTime + self.serializationCompletedTime = serializationCompletedTime + + self.latency = initialResponseTime - requestStartTime + self.requestDuration = requestCompletedTime - requestStartTime + self.serializationDuration = serializationCompletedTime - requestCompletedTime + self.totalDuration = serializationCompletedTime - requestStartTime + } +} + +// MARK: - CustomStringConvertible + +extension Timeline: CustomStringConvertible { + /// The textual representation used when written to an output stream, which includes the latency, the request + /// duration and the total duration. + public var description: String { + let latency = String(format: "%.3f", self.latency) + let requestDuration = String(format: "%.3f", self.requestDuration) + let serializationDuration = String(format: "%.3f", self.serializationDuration) + let totalDuration = String(format: "%.3f", self.totalDuration) + + // NOTE: Had to move to string concatenation due to memory leak filed as rdar://26761490. Once memory leak is + // fixed, we should move back to string interpolation by reverting commit 7d4a43b1. + let timings = [ + "\"Latency\": " + latency + " secs", + "\"Request Duration\": " + requestDuration + " secs", + "\"Serialization Duration\": " + serializationDuration + " secs", + "\"Total Duration\": " + totalDuration + " secs" + ] + + return "Timeline: { " + timings.joined(separator: ", ") + " }" + } +} + +// MARK: - CustomDebugStringConvertible + +extension Timeline: CustomDebugStringConvertible { + /// The textual representation used when written to an output stream, which includes the request start time, the + /// initial response time, the request completed time, the serialization completed time, the latency, the request + /// duration and the total duration. + public var debugDescription: String { + let requestStartTime = String(format: "%.3f", self.requestStartTime) + let initialResponseTime = String(format: "%.3f", self.initialResponseTime) + let requestCompletedTime = String(format: "%.3f", self.requestCompletedTime) + let serializationCompletedTime = String(format: "%.3f", self.serializationCompletedTime) + let latency = String(format: "%.3f", self.latency) + let requestDuration = String(format: "%.3f", self.requestDuration) + let serializationDuration = String(format: "%.3f", self.serializationDuration) + let totalDuration = String(format: "%.3f", self.totalDuration) + + // NOTE: Had to move to string concatenation due to memory leak filed as rdar://26761490. Once memory leak is + // fixed, we should move back to string interpolation by reverting commit 7d4a43b1. + let timings = [ + "\"Request Start Time\": " + requestStartTime, + "\"Initial Response Time\": " + initialResponseTime, + "\"Request Completed Time\": " + requestCompletedTime, + "\"Serialization Completed Time\": " + serializationCompletedTime, + "\"Latency\": " + latency + " secs", + "\"Request Duration\": " + requestDuration + " secs", + "\"Serialization Duration\": " + serializationDuration + " secs", + "\"Total Duration\": " + totalDuration + " secs" + ] + + return "Timeline: { " + timings.joined(separator: ", ") + " }" + } +} diff --git a/Pods/Alamofire/Source/Validation.swift b/Pods/Alamofire/Source/Validation.swift new file mode 100644 index 0000000..c405d02 --- /dev/null +++ b/Pods/Alamofire/Source/Validation.swift @@ -0,0 +1,309 @@ +// +// Validation.swift +// +// Copyright (c) 2014-2016 Alamofire Software Foundation (http://alamofire.org/) +// +// Permission is hereby granted, free of charge, to any person obtaining a copy +// of this software and associated documentation files (the "Software"), to deal +// in the Software without restriction, including without limitation the rights +// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +// copies of the Software, and to permit persons to whom the Software is +// furnished to do so, subject to the following conditions: +// +// The above copyright notice and this permission notice shall be included in +// all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN +// THE SOFTWARE. +// + +import Foundation + +extension Request { + + // MARK: Helper Types + + fileprivate typealias ErrorReason = AFError.ResponseValidationFailureReason + + /// Used to represent whether validation was successful or encountered an error resulting in a failure. + /// + /// - success: The validation was successful. + /// - failure: The validation failed encountering the provided error. + public enum ValidationResult { + case success + case failure(Error) + } + + fileprivate struct MIMEType { + let type: String + let subtype: String + + var isWildcard: Bool { return type == "*" && subtype == "*" } + + init?(_ string: String) { + let components: [String] = { + let stripped = string.trimmingCharacters(in: .whitespacesAndNewlines) + let split = stripped.substring(to: stripped.range(of: ";")?.lowerBound ?? stripped.endIndex) + return split.components(separatedBy: "/") + }() + + if let type = components.first, let subtype = components.last { + self.type = type + self.subtype = subtype + } else { + return nil + } + } + + func matches(_ mime: MIMEType) -> Bool { + switch (type, subtype) { + case (mime.type, mime.subtype), (mime.type, "*"), ("*", mime.subtype), ("*", "*"): + return true + default: + return false + } + } + } + + // MARK: Properties + + fileprivate var acceptableStatusCodes: [Int] { return Array(200..<300) } + + fileprivate var acceptableContentTypes: [String] { + if let accept = request?.value(forHTTPHeaderField: "Accept") { + return accept.components(separatedBy: ",") + } + + return ["*/*"] + } + + // MARK: Status Code + + fileprivate func validate( + statusCode acceptableStatusCodes: S, + response: HTTPURLResponse) + -> ValidationResult + where S.Iterator.Element == Int + { + if acceptableStatusCodes.contains(response.statusCode) { + return .success + } else { + let reason: ErrorReason = .unacceptableStatusCode(code: response.statusCode) + return .failure(AFError.responseValidationFailed(reason: reason)) + } + } + + // MARK: Content Type + + fileprivate func validate( + contentType acceptableContentTypes: S, + response: HTTPURLResponse, + data: Data?) + -> ValidationResult + where S.Iterator.Element == String + { + guard let data = data, data.count > 0 else { return .success } + + guard + let responseContentType = response.mimeType, + let responseMIMEType = MIMEType(responseContentType) + else { + for contentType in acceptableContentTypes { + if let mimeType = MIMEType(contentType), mimeType.isWildcard { + return .success + } + } + + let error: AFError = { + let reason: ErrorReason = .missingContentType(acceptableContentTypes: Array(acceptableContentTypes)) + return AFError.responseValidationFailed(reason: reason) + }() + + return .failure(error) + } + + for contentType in acceptableContentTypes { + if let acceptableMIMEType = MIMEType(contentType), acceptableMIMEType.matches(responseMIMEType) { + return .success + } + } + + let error: AFError = { + let reason: ErrorReason = .unacceptableContentType( + acceptableContentTypes: Array(acceptableContentTypes), + responseContentType: responseContentType + ) + + return AFError.responseValidationFailed(reason: reason) + }() + + return .failure(error) + } +} + +// MARK: - + +extension DataRequest { + /// A closure used to validate a request that takes a URL request, a URL response and data, and returns whether the + /// request was valid. + public typealias Validation = (URLRequest?, HTTPURLResponse, Data?) -> ValidationResult + + /// Validates the request, using the specified closure. + /// + /// If validation fails, subsequent calls to response handlers will have an associated error. + /// + /// - parameter validation: A closure to validate the request. + /// + /// - returns: The request. + @discardableResult + public func validate(_ validation: @escaping Validation) -> Self { + let validationExecution: () -> Void = { [unowned self] in + if + let response = self.response, + self.delegate.error == nil, + case let .failure(error) = validation(self.request, response, self.delegate.data) + { + self.delegate.error = error + } + } + + validations.append(validationExecution) + + return self + } + + /// Validates that the response has a status code in the specified sequence. + /// + /// If validation fails, subsequent calls to response handlers will have an associated error. + /// + /// - parameter range: The range of acceptable status codes. + /// + /// - returns: The request. + @discardableResult + public func validate(statusCode acceptableStatusCodes: S) -> Self where S.Iterator.Element == Int { + return validate { [unowned self] _, response, _ in + return self.validate(statusCode: acceptableStatusCodes, response: response) + } + } + + /// Validates that the response has a content type in the specified sequence. + /// + /// If validation fails, subsequent calls to response handlers will have an associated error. + /// + /// - parameter contentType: The acceptable content types, which may specify wildcard types and/or subtypes. + /// + /// - returns: The request. + @discardableResult + public func validate(contentType acceptableContentTypes: S) -> Self where S.Iterator.Element == String { + return validate { [unowned self] _, response, data in + return self.validate(contentType: acceptableContentTypes, response: response, data: data) + } + } + + /// Validates that the response has a status code in the default acceptable range of 200...299, and that the content + /// type matches any specified in the Accept HTTP header field. + /// + /// If validation fails, subsequent calls to response handlers will have an associated error. + /// + /// - returns: The request. + @discardableResult + public func validate() -> Self { + return validate(statusCode: self.acceptableStatusCodes).validate(contentType: self.acceptableContentTypes) + } +} + +// MARK: - + +extension DownloadRequest { + /// A closure used to validate a request that takes a URL request, a URL response, a temporary URL and a + /// destination URL, and returns whether the request was valid. + public typealias Validation = ( + _ request: URLRequest?, + _ response: HTTPURLResponse, + _ temporaryURL: URL?, + _ destinationURL: URL?) + -> ValidationResult + + /// Validates the request, using the specified closure. + /// + /// If validation fails, subsequent calls to response handlers will have an associated error. + /// + /// - parameter validation: A closure to validate the request. + /// + /// - returns: The request. + @discardableResult + public func validate(_ validation: @escaping Validation) -> Self { + let validationExecution: () -> Void = { [unowned self] in + let request = self.request + let temporaryURL = self.downloadDelegate.temporaryURL + let destinationURL = self.downloadDelegate.destinationURL + + if + let response = self.response, + self.delegate.error == nil, + case let .failure(error) = validation(request, response, temporaryURL, destinationURL) + { + self.delegate.error = error + } + } + + validations.append(validationExecution) + + return self + } + + /// Validates that the response has a status code in the specified sequence. + /// + /// If validation fails, subsequent calls to response handlers will have an associated error. + /// + /// - parameter range: The range of acceptable status codes. + /// + /// - returns: The request. + @discardableResult + public func validate(statusCode acceptableStatusCodes: S) -> Self where S.Iterator.Element == Int { + return validate { [unowned self] _, response, _, _ in + return self.validate(statusCode: acceptableStatusCodes, response: response) + } + } + + /// Validates that the response has a content type in the specified sequence. + /// + /// If validation fails, subsequent calls to response handlers will have an associated error. + /// + /// - parameter contentType: The acceptable content types, which may specify wildcard types and/or subtypes. + /// + /// - returns: The request. + @discardableResult + public func validate(contentType acceptableContentTypes: S) -> Self where S.Iterator.Element == String { + return validate { [unowned self] _, response, _, _ in + let fileURL = self.downloadDelegate.fileURL + + guard let validFileURL = fileURL else { + return .failure(AFError.responseValidationFailed(reason: .dataFileNil)) + } + + do { + let data = try Data(contentsOf: validFileURL) + return self.validate(contentType: acceptableContentTypes, response: response, data: data) + } catch { + return .failure(AFError.responseValidationFailed(reason: .dataFileReadFailed(at: validFileURL))) + } + } + } + + /// Validates that the response has a status code in the default acceptable range of 200...299, and that the content + /// type matches any specified in the Accept HTTP header field. + /// + /// If validation fails, subsequent calls to response handlers will have an associated error. + /// + /// - returns: The request. + @discardableResult + public func validate() -> Self { + return validate(statusCode: self.acceptableStatusCodes).validate(contentType: self.acceptableContentTypes) + } +} diff --git a/Pods/Manifest.lock b/Pods/Manifest.lock new file mode 100644 index 0000000..a2c0289 --- /dev/null +++ b/Pods/Manifest.lock @@ -0,0 +1,12 @@ +PODS: + - Alamofire (4.3.0) + +DEPENDENCIES: + - Alamofire + +SPEC CHECKSUMS: + Alamofire: 856a113053a7bc9cbe5d6367a555d773fc5cfef7 + +PODFILE CHECKSUM: dc296b3fd9b6b081ed51a782cf5b4fec2b21bb1c + +COCOAPODS: 1.2.0.beta.3 diff --git a/Pods/Pods.xcodeproj/project.pbxproj b/Pods/Pods.xcodeproj/project.pbxproj new file mode 100644 index 0000000..795802c --- /dev/null +++ b/Pods/Pods.xcodeproj/project.pbxproj @@ -0,0 +1,598 @@ +// !$*UTF8*$! +{ + archiveVersion = 1; + classes = { + }; + objectVersion = 46; + objects = { + +/* Begin PBXBuildFile section */ + 10EB23E9ECC4B33E16933BB1EA560B6A /* Timeline.swift in Sources */ = {isa = PBXBuildFile; fileRef = 87882A1F5A92C8138D54545E51D51E6F /* Timeline.swift */; }; + 1B9EDEDC964E6B08F78920B4F4B9DB84 /* Alamofire-umbrella.h in Headers */ = {isa = PBXBuildFile; fileRef = B44A27EFBB0DA84D738057B77F3413B1 /* Alamofire-umbrella.h */; settings = {ATTRIBUTES = (Public, ); }; }; + 205A070A144A9AEA52CB2464FF09A43D /* Pods-App-umbrella.h in Headers */ = {isa = PBXBuildFile; fileRef = CFB9B6F0F36ECB44627648DFF07978C2 /* Pods-App-umbrella.h */; settings = {ATTRIBUTES = (Public, ); }; }; + 359F416009FE9E579563A828E03C870D /* Pods-App-dummy.m in Sources */ = {isa = PBXBuildFile; fileRef = 5C8144347BC58521E07DC398E6B01780 /* Pods-App-dummy.m */; }; + 3626B94094672CB1C9DEA32B9F9502E1 /* TaskDelegate.swift in Sources */ = {isa = PBXBuildFile; fileRef = A01C037B4034EDA3D7955BC5E4E9D9D6 /* TaskDelegate.swift */; }; + 5387216E723A3C68E851CA15573CDD71 /* Request.swift in Sources */ = {isa = PBXBuildFile; fileRef = 1E230A0448B394DE26E688DAC8E6201E /* Request.swift */; }; + 5F4F601C3A0E4FC53DE1884EA37D603D /* Foundation.framework in Frameworks */ = {isa = PBXBuildFile; fileRef = CBB3DE36805AF21409EC968A9691732F /* Foundation.framework */; }; + 61200D01A1855D7920CEF835C8BE00B0 /* DispatchQueue+Alamofire.swift in Sources */ = {isa = PBXBuildFile; fileRef = 0FCBF1EED873F61C6D46CE37FA5C39D3 /* DispatchQueue+Alamofire.swift */; }; + 62F65AD8DC4F0F9610F4B8B4738EC094 /* ServerTrustPolicy.swift in Sources */ = {isa = PBXBuildFile; fileRef = 32B030D27CAC730C5EB0F22390645310 /* ServerTrustPolicy.swift */; }; + 7B5FE28C7EA4122B0598738E54DBEBD8 /* SessionDelegate.swift in Sources */ = {isa = PBXBuildFile; fileRef = 195D73DD9EF275A3C56569E2B1CA8026 /* SessionDelegate.swift */; }; + 7D8CC01E8C9EFFF9F4D65406CDE0AB66 /* Result.swift in Sources */ = {isa = PBXBuildFile; fileRef = 3D60BC9955B4F7FFA62D7440CB385C11 /* Result.swift */; }; + 9ED2BB2981896E0A39EFA365503F58CE /* AFError.swift in Sources */ = {isa = PBXBuildFile; fileRef = 4AF006B0AD5765D1BFA8253C2DCBB126 /* AFError.swift */; }; + A04BFC558D69E7DBB68023C80A9CFE4E /* Foundation.framework in Frameworks */ = {isa = PBXBuildFile; fileRef = CBB3DE36805AF21409EC968A9691732F /* Foundation.framework */; }; + A2A6F71B727312BD45CC7A4AAD7B0AB7 /* NetworkReachabilityManager.swift in Sources */ = {isa = PBXBuildFile; fileRef = E5A8AA5F9EDED0A0BDDE7E830BF4AEE0 /* NetworkReachabilityManager.swift */; }; + A9EEEA7477981DEEBC72432DE9990A4B /* Alamofire-dummy.m in Sources */ = {isa = PBXBuildFile; fileRef = 22C1C119BCE81C53F76CAC2BE27C38E0 /* Alamofire-dummy.m */; }; + AE1EF48399533730D0066E04B22CA2D6 /* SessionManager.swift in Sources */ = {isa = PBXBuildFile; fileRef = 46CDAC6C1187C5467E576980E1062C8B /* SessionManager.swift */; }; + B65FCF589DA398C3EFE0128064E510EC /* MultipartFormData.swift in Sources */ = {isa = PBXBuildFile; fileRef = 155538D91ACEEEDF82069ACF6C1A02E7 /* MultipartFormData.swift */; }; + BBEFE2F9CEB73DC7BD97FFA66A0D9D4F /* Validation.swift in Sources */ = {isa = PBXBuildFile; fileRef = B029DBC43E49A740F12B5E4D2E6DD452 /* Validation.swift */; }; + BE5C67A07E289FE1F9BE27335B159997 /* ParameterEncoding.swift in Sources */ = {isa = PBXBuildFile; fileRef = 6639346628280A0D0FAD35196BF56108 /* ParameterEncoding.swift */; }; + CB6D60925223897FFA2662667DF83E8A /* Response.swift in Sources */ = {isa = PBXBuildFile; fileRef = 04F47F5C9CDB035C5AFADEBA5BF44F1C /* Response.swift */; }; + EFD264FC408EBF3BA2528E70B08DDD94 /* Notifications.swift in Sources */ = {isa = PBXBuildFile; fileRef = 66A46F517F0AF7E85A16D723F6406896 /* Notifications.swift */; }; + F6BECD98B97CBFEBE2C96F0E9E72A6C0 /* ResponseSerialization.swift in Sources */ = {isa = PBXBuildFile; fileRef = E2F9510473F6FFD7AA66524DB16C2263 /* ResponseSerialization.swift */; }; + F8B3D3092ED0417E8CDF32033F6122F5 /* Alamofire.swift in Sources */ = {isa = PBXBuildFile; fileRef = DFCB8C44DE758E906C0BCDA455937B85 /* Alamofire.swift */; }; +/* End PBXBuildFile section */ + +/* Begin PBXContainerItemProxy section */ + 4B642EB687A13D62DD767D17491FF6FB /* PBXContainerItemProxy */ = { + isa = PBXContainerItemProxy; + containerPortal = D41D8CD98F00B204E9800998ECF8427E /* Project object */; + proxyType = 1; + remoteGlobalIDString = 88E9EC28B8B46C3631E6B242B50F4442; + remoteInfo = Alamofire; + }; +/* End PBXContainerItemProxy section */ + +/* Begin PBXFileReference section */ + 04F47F5C9CDB035C5AFADEBA5BF44F1C /* Response.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = Response.swift; path = Source/Response.swift; sourceTree = ""; }; + 0FCBF1EED873F61C6D46CE37FA5C39D3 /* DispatchQueue+Alamofire.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = "DispatchQueue+Alamofire.swift"; path = "Source/DispatchQueue+Alamofire.swift"; sourceTree = ""; }; + 13A0A663B36A229C69D5274A83E93F88 /* Info.plist */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = text.plist.xml; path = Info.plist; sourceTree = ""; }; + 155538D91ACEEEDF82069ACF6C1A02E7 /* MultipartFormData.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = MultipartFormData.swift; path = Source/MultipartFormData.swift; sourceTree = ""; }; + 195D73DD9EF275A3C56569E2B1CA8026 /* SessionDelegate.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = SessionDelegate.swift; path = Source/SessionDelegate.swift; sourceTree = ""; }; + 1E230A0448B394DE26E688DAC8E6201E /* Request.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = Request.swift; path = Source/Request.swift; sourceTree = ""; }; + 22C1C119BCE81C53F76CAC2BE27C38E0 /* Alamofire-dummy.m */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.objc; path = "Alamofire-dummy.m"; sourceTree = ""; }; + 32B030D27CAC730C5EB0F22390645310 /* ServerTrustPolicy.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = ServerTrustPolicy.swift; path = Source/ServerTrustPolicy.swift; sourceTree = ""; }; + 337EAD924FD67F5B4E29E4188F340512 /* Pods-App-acknowledgements.markdown */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = text; path = "Pods-App-acknowledgements.markdown"; sourceTree = ""; }; + 3D0504B01F2638FBA19B4FC160EE5B1B /* Pods-App-acknowledgements.plist */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = text.plist.xml; path = "Pods-App-acknowledgements.plist"; sourceTree = ""; }; + 3D60BC9955B4F7FFA62D7440CB385C11 /* Result.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = Result.swift; path = Source/Result.swift; sourceTree = ""; }; + 46CDAC6C1187C5467E576980E1062C8B /* SessionManager.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = SessionManager.swift; path = Source/SessionManager.swift; sourceTree = ""; }; + 478D2A40B9F6CD2FA965CCD860EAFB49 /* Pods-App.debug.xcconfig */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = text.xcconfig; path = "Pods-App.debug.xcconfig"; sourceTree = ""; }; + 4AF006B0AD5765D1BFA8253C2DCBB126 /* AFError.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = AFError.swift; path = Source/AFError.swift; sourceTree = ""; }; + 4FAC16DF70DE22A85BBF55E089BB56E7 /* Pods-App.modulemap */ = {isa = PBXFileReference; includeInIndex = 1; path = "Pods-App.modulemap"; sourceTree = ""; }; + 576DB0340FCB12413536AA6784B1BF0F /* Alamofire.framework */ = {isa = PBXFileReference; explicitFileType = wrapper.framework; includeInIndex = 0; name = Alamofire.framework; path = Alamofire.framework; sourceTree = BUILT_PRODUCTS_DIR; }; + 5C8144347BC58521E07DC398E6B01780 /* Pods-App-dummy.m */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.objc; path = "Pods-App-dummy.m"; sourceTree = ""; }; + 6334E785167733FEBB6F54A43C3854EB /* Pods-App.release.xcconfig */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = text.xcconfig; path = "Pods-App.release.xcconfig"; sourceTree = ""; }; + 6639346628280A0D0FAD35196BF56108 /* ParameterEncoding.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = ParameterEncoding.swift; path = Source/ParameterEncoding.swift; sourceTree = ""; }; + 66A46F517F0AF7E85A16D723F6406896 /* Notifications.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = Notifications.swift; path = Source/Notifications.swift; sourceTree = ""; }; + 7CC7F8FC6ACA3D781B6D53BB904CC993 /* Pods_App.framework */ = {isa = PBXFileReference; explicitFileType = wrapper.framework; includeInIndex = 0; name = Pods_App.framework; path = "Pods-App.framework"; sourceTree = BUILT_PRODUCTS_DIR; }; + 7D141D1953E5C6E67E362CE73090E48A /* Alamofire.modulemap */ = {isa = PBXFileReference; includeInIndex = 1; path = Alamofire.modulemap; sourceTree = ""; }; + 87882A1F5A92C8138D54545E51D51E6F /* Timeline.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = Timeline.swift; path = Source/Timeline.swift; sourceTree = ""; }; + 93A4A3777CF96A4AAC1D13BA6DCCEA73 /* Podfile */ = {isa = PBXFileReference; explicitFileType = text.script.ruby; includeInIndex = 1; lastKnownFileType = text; name = Podfile; path = ../Podfile; sourceTree = SOURCE_ROOT; xcLanguageSpecificationIdentifier = xcode.lang.ruby; }; + 94038376D370146BBE1F9C238F6BAF36 /* Pods-App-resources.sh */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = text.script.sh; path = "Pods-App-resources.sh"; sourceTree = ""; }; + A01C037B4034EDA3D7955BC5E4E9D9D6 /* TaskDelegate.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = TaskDelegate.swift; path = Source/TaskDelegate.swift; sourceTree = ""; }; + B029DBC43E49A740F12B5E4D2E6DD452 /* Validation.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = Validation.swift; path = Source/Validation.swift; sourceTree = ""; }; + B44A27EFBB0DA84D738057B77F3413B1 /* Alamofire-umbrella.h */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.h; path = "Alamofire-umbrella.h"; sourceTree = ""; }; + BCCA9CA7D9C1A2047BB93336C5708DFD /* Alamofire-prefix.pch */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.h; path = "Alamofire-prefix.pch"; sourceTree = ""; }; + CBB3DE36805AF21409EC968A9691732F /* Foundation.framework */ = {isa = PBXFileReference; lastKnownFileType = wrapper.framework; name = Foundation.framework; path = Platforms/iPhoneOS.platform/Developer/SDKs/iPhoneOS10.0.sdk/System/Library/Frameworks/Foundation.framework; sourceTree = DEVELOPER_DIR; }; + CCD8EEF11AF208CB282FB69552083F94 /* Info.plist */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = text.plist.xml; path = Info.plist; sourceTree = ""; }; + CFB9B6F0F36ECB44627648DFF07978C2 /* Pods-App-umbrella.h */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.h; path = "Pods-App-umbrella.h"; sourceTree = ""; }; + DFCB8C44DE758E906C0BCDA455937B85 /* Alamofire.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = Alamofire.swift; path = Source/Alamofire.swift; sourceTree = ""; }; + E2F9510473F6FFD7AA66524DB16C2263 /* ResponseSerialization.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = ResponseSerialization.swift; path = Source/ResponseSerialization.swift; sourceTree = ""; }; + E5A8AA5F9EDED0A0BDDE7E830BF4AEE0 /* NetworkReachabilityManager.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = NetworkReachabilityManager.swift; path = Source/NetworkReachabilityManager.swift; sourceTree = ""; }; + E6F34CCF86067ED508C12C676E298C69 /* Alamofire.xcconfig */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = text.xcconfig; path = Alamofire.xcconfig; sourceTree = ""; }; + FD2760F65D8A4A2AC461779728F1B440 /* Pods-App-frameworks.sh */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = text.script.sh; path = "Pods-App-frameworks.sh"; sourceTree = ""; }; +/* End PBXFileReference section */ + +/* Begin PBXFrameworksBuildPhase section */ + 67F0928331F31A1FB11C99479609A274 /* Frameworks */ = { + isa = PBXFrameworksBuildPhase; + buildActionMask = 2147483647; + files = ( + 5F4F601C3A0E4FC53DE1884EA37D603D /* Foundation.framework in Frameworks */, + ); + runOnlyForDeploymentPostprocessing = 0; + }; + 99195E4207764744AEC07ECCBCD550EB /* Frameworks */ = { + isa = PBXFrameworksBuildPhase; + buildActionMask = 2147483647; + files = ( + A04BFC558D69E7DBB68023C80A9CFE4E /* Foundation.framework in Frameworks */, + ); + runOnlyForDeploymentPostprocessing = 0; + }; +/* End PBXFrameworksBuildPhase section */ + +/* Begin PBXGroup section */ + 18B9E30E40BDA81DE9B55B434D3E5418 /* Targets Support Files */ = { + isa = PBXGroup; + children = ( + CAACC5CC124A9CB4BCA9E985EE2865AC /* Pods-App */, + ); + name = "Targets Support Files"; + sourceTree = ""; + }; + 200D10EB20F0397D47F022B50CF0433F /* Alamofire */ = { + isa = PBXGroup; + children = ( + 4AF006B0AD5765D1BFA8253C2DCBB126 /* AFError.swift */, + DFCB8C44DE758E906C0BCDA455937B85 /* Alamofire.swift */, + 0FCBF1EED873F61C6D46CE37FA5C39D3 /* DispatchQueue+Alamofire.swift */, + 155538D91ACEEEDF82069ACF6C1A02E7 /* MultipartFormData.swift */, + E5A8AA5F9EDED0A0BDDE7E830BF4AEE0 /* NetworkReachabilityManager.swift */, + 66A46F517F0AF7E85A16D723F6406896 /* Notifications.swift */, + 6639346628280A0D0FAD35196BF56108 /* ParameterEncoding.swift */, + 1E230A0448B394DE26E688DAC8E6201E /* Request.swift */, + 04F47F5C9CDB035C5AFADEBA5BF44F1C /* Response.swift */, + E2F9510473F6FFD7AA66524DB16C2263 /* ResponseSerialization.swift */, + 3D60BC9955B4F7FFA62D7440CB385C11 /* Result.swift */, + 32B030D27CAC730C5EB0F22390645310 /* ServerTrustPolicy.swift */, + 195D73DD9EF275A3C56569E2B1CA8026 /* SessionDelegate.swift */, + 46CDAC6C1187C5467E576980E1062C8B /* SessionManager.swift */, + A01C037B4034EDA3D7955BC5E4E9D9D6 /* TaskDelegate.swift */, + 87882A1F5A92C8138D54545E51D51E6F /* Timeline.swift */, + B029DBC43E49A740F12B5E4D2E6DD452 /* Validation.swift */, + 55F14F994FE7AB51F028BFE66CEF3106 /* Support Files */, + ); + name = Alamofire; + path = Alamofire; + sourceTree = ""; + }; + 35F128EB69B6F7FB7DA93BBF6C130FAE /* Pods */ = { + isa = PBXGroup; + children = ( + 200D10EB20F0397D47F022B50CF0433F /* Alamofire */, + ); + name = Pods; + sourceTree = ""; + }; + 3C8C1E9A23930FB3FF737E74B7799330 /* Products */ = { + isa = PBXGroup; + children = ( + 576DB0340FCB12413536AA6784B1BF0F /* Alamofire.framework */, + 7CC7F8FC6ACA3D781B6D53BB904CC993 /* Pods_App.framework */, + ); + name = Products; + sourceTree = ""; + }; + 55F14F994FE7AB51F028BFE66CEF3106 /* Support Files */ = { + isa = PBXGroup; + children = ( + 7D141D1953E5C6E67E362CE73090E48A /* Alamofire.modulemap */, + E6F34CCF86067ED508C12C676E298C69 /* Alamofire.xcconfig */, + 22C1C119BCE81C53F76CAC2BE27C38E0 /* Alamofire-dummy.m */, + BCCA9CA7D9C1A2047BB93336C5708DFD /* Alamofire-prefix.pch */, + B44A27EFBB0DA84D738057B77F3413B1 /* Alamofire-umbrella.h */, + 13A0A663B36A229C69D5274A83E93F88 /* Info.plist */, + ); + name = "Support Files"; + path = "../Target Support Files/Alamofire"; + sourceTree = ""; + }; + 7531C8F8DE19F1AA3C8A7AC97A91DC29 /* iOS */ = { + isa = PBXGroup; + children = ( + CBB3DE36805AF21409EC968A9691732F /* Foundation.framework */, + ); + name = iOS; + sourceTree = ""; + }; + 7DB346D0F39D3F0E887471402A8071AB = { + isa = PBXGroup; + children = ( + 93A4A3777CF96A4AAC1D13BA6DCCEA73 /* Podfile */, + BC3CA7F9E30CC8F7E2DD044DD34432FC /* Frameworks */, + 35F128EB69B6F7FB7DA93BBF6C130FAE /* Pods */, + 3C8C1E9A23930FB3FF737E74B7799330 /* Products */, + 18B9E30E40BDA81DE9B55B434D3E5418 /* Targets Support Files */, + ); + sourceTree = ""; + }; + BC3CA7F9E30CC8F7E2DD044DD34432FC /* Frameworks */ = { + isa = PBXGroup; + children = ( + 7531C8F8DE19F1AA3C8A7AC97A91DC29 /* iOS */, + ); + name = Frameworks; + sourceTree = ""; + }; + CAACC5CC124A9CB4BCA9E985EE2865AC /* Pods-App */ = { + isa = PBXGroup; + children = ( + CCD8EEF11AF208CB282FB69552083F94 /* Info.plist */, + 4FAC16DF70DE22A85BBF55E089BB56E7 /* Pods-App.modulemap */, + 337EAD924FD67F5B4E29E4188F340512 /* Pods-App-acknowledgements.markdown */, + 3D0504B01F2638FBA19B4FC160EE5B1B /* Pods-App-acknowledgements.plist */, + 5C8144347BC58521E07DC398E6B01780 /* Pods-App-dummy.m */, + FD2760F65D8A4A2AC461779728F1B440 /* Pods-App-frameworks.sh */, + 94038376D370146BBE1F9C238F6BAF36 /* Pods-App-resources.sh */, + CFB9B6F0F36ECB44627648DFF07978C2 /* Pods-App-umbrella.h */, + 478D2A40B9F6CD2FA965CCD860EAFB49 /* Pods-App.debug.xcconfig */, + 6334E785167733FEBB6F54A43C3854EB /* Pods-App.release.xcconfig */, + ); + name = "Pods-App"; + path = "Target Support Files/Pods-App"; + sourceTree = ""; + }; +/* End PBXGroup section */ + +/* Begin PBXHeadersBuildPhase section */ + B4002B6E97835FDCCAA5963EFE09A3E0 /* Headers */ = { + isa = PBXHeadersBuildPhase; + buildActionMask = 2147483647; + files = ( + 1B9EDEDC964E6B08F78920B4F4B9DB84 /* Alamofire-umbrella.h in Headers */, + ); + runOnlyForDeploymentPostprocessing = 0; + }; + C554BF0E8804A6B7EEE5E4B81AED9823 /* Headers */ = { + isa = PBXHeadersBuildPhase; + buildActionMask = 2147483647; + files = ( + 205A070A144A9AEA52CB2464FF09A43D /* Pods-App-umbrella.h in Headers */, + ); + runOnlyForDeploymentPostprocessing = 0; + }; +/* End PBXHeadersBuildPhase section */ + +/* Begin PBXNativeTarget section */ + 88E9EC28B8B46C3631E6B242B50F4442 /* Alamofire */ = { + isa = PBXNativeTarget; + buildConfigurationList = 419E5D95491847CD79841B971A8A3277 /* Build configuration list for PBXNativeTarget "Alamofire" */; + buildPhases = ( + 32B9974868188C4803318E36329C87FE /* Sources */, + 99195E4207764744AEC07ECCBCD550EB /* Frameworks */, + B4002B6E97835FDCCAA5963EFE09A3E0 /* Headers */, + ); + buildRules = ( + ); + dependencies = ( + ); + name = Alamofire; + productName = Alamofire; + productReference = 576DB0340FCB12413536AA6784B1BF0F /* Alamofire.framework */; + productType = "com.apple.product-type.framework"; + }; + 8FD22D90E3A338BA74A6B068EC6421EF /* Pods-App */ = { + isa = PBXNativeTarget; + buildConfigurationList = 3CB0BD4419B174EBD3E2BDA54114BA81 /* Build configuration list for PBXNativeTarget "Pods-App" */; + buildPhases = ( + 807B5571D34CBB2EE4EF1D9C6AE6D51B /* Sources */, + 67F0928331F31A1FB11C99479609A274 /* Frameworks */, + C554BF0E8804A6B7EEE5E4B81AED9823 /* Headers */, + ); + buildRules = ( + ); + dependencies = ( + 053A052FE93E37BB5ACBA5F6243F713A /* PBXTargetDependency */, + ); + name = "Pods-App"; + productName = "Pods-App"; + productReference = 7CC7F8FC6ACA3D781B6D53BB904CC993 /* Pods_App.framework */; + productType = "com.apple.product-type.framework"; + }; +/* End PBXNativeTarget section */ + +/* Begin PBXProject section */ + D41D8CD98F00B204E9800998ECF8427E /* Project object */ = { + isa = PBXProject; + attributes = { + LastSwiftUpdateCheck = 0730; + LastUpgradeCheck = 0700; + }; + buildConfigurationList = 2D8E8EC45A3A1A1D94AE762CB5028504 /* Build configuration list for PBXProject "Pods" */; + compatibilityVersion = "Xcode 3.2"; + developmentRegion = English; + hasScannedForEncodings = 0; + knownRegions = ( + en, + ); + mainGroup = 7DB346D0F39D3F0E887471402A8071AB; + productRefGroup = 3C8C1E9A23930FB3FF737E74B7799330 /* Products */; + projectDirPath = ""; + projectRoot = ""; + targets = ( + 88E9EC28B8B46C3631E6B242B50F4442 /* Alamofire */, + 8FD22D90E3A338BA74A6B068EC6421EF /* Pods-App */, + ); + }; +/* End PBXProject section */ + +/* Begin PBXSourcesBuildPhase section */ + 32B9974868188C4803318E36329C87FE /* Sources */ = { + isa = PBXSourcesBuildPhase; + buildActionMask = 2147483647; + files = ( + 9ED2BB2981896E0A39EFA365503F58CE /* AFError.swift in Sources */, + A9EEEA7477981DEEBC72432DE9990A4B /* Alamofire-dummy.m in Sources */, + F8B3D3092ED0417E8CDF32033F6122F5 /* Alamofire.swift in Sources */, + 61200D01A1855D7920CEF835C8BE00B0 /* DispatchQueue+Alamofire.swift in Sources */, + B65FCF589DA398C3EFE0128064E510EC /* MultipartFormData.swift in Sources */, + A2A6F71B727312BD45CC7A4AAD7B0AB7 /* NetworkReachabilityManager.swift in Sources */, + EFD264FC408EBF3BA2528E70B08DDD94 /* Notifications.swift in Sources */, + BE5C67A07E289FE1F9BE27335B159997 /* ParameterEncoding.swift in Sources */, + 5387216E723A3C68E851CA15573CDD71 /* Request.swift in Sources */, + CB6D60925223897FFA2662667DF83E8A /* Response.swift in Sources */, + F6BECD98B97CBFEBE2C96F0E9E72A6C0 /* ResponseSerialization.swift in Sources */, + 7D8CC01E8C9EFFF9F4D65406CDE0AB66 /* Result.swift in Sources */, + 62F65AD8DC4F0F9610F4B8B4738EC094 /* ServerTrustPolicy.swift in Sources */, + 7B5FE28C7EA4122B0598738E54DBEBD8 /* SessionDelegate.swift in Sources */, + AE1EF48399533730D0066E04B22CA2D6 /* SessionManager.swift in Sources */, + 3626B94094672CB1C9DEA32B9F9502E1 /* TaskDelegate.swift in Sources */, + 10EB23E9ECC4B33E16933BB1EA560B6A /* Timeline.swift in Sources */, + BBEFE2F9CEB73DC7BD97FFA66A0D9D4F /* Validation.swift in Sources */, + ); + runOnlyForDeploymentPostprocessing = 0; + }; + 807B5571D34CBB2EE4EF1D9C6AE6D51B /* Sources */ = { + isa = PBXSourcesBuildPhase; + buildActionMask = 2147483647; + files = ( + 359F416009FE9E579563A828E03C870D /* Pods-App-dummy.m in Sources */, + ); + runOnlyForDeploymentPostprocessing = 0; + }; +/* End PBXSourcesBuildPhase section */ + +/* Begin PBXTargetDependency section */ + 053A052FE93E37BB5ACBA5F6243F713A /* PBXTargetDependency */ = { + isa = PBXTargetDependency; + name = Alamofire; + target = 88E9EC28B8B46C3631E6B242B50F4442 /* Alamofire */; + targetProxy = 4B642EB687A13D62DD767D17491FF6FB /* PBXContainerItemProxy */; + }; +/* End PBXTargetDependency section */ + +/* Begin XCBuildConfiguration section */ + 0A29B6F510198AF64EFD762EF6FA97A5 /* Release */ = { + isa = XCBuildConfiguration; + baseConfigurationReference = E6F34CCF86067ED508C12C676E298C69 /* Alamofire.xcconfig */; + buildSettings = { + "CODE_SIGN_IDENTITY[sdk=appletvos*]" = ""; + "CODE_SIGN_IDENTITY[sdk=iphoneos*]" = ""; + "CODE_SIGN_IDENTITY[sdk=watchos*]" = ""; + CURRENT_PROJECT_VERSION = 1; + DEBUG_INFORMATION_FORMAT = "dwarf-with-dsym"; + DEFINES_MODULE = YES; + DYLIB_COMPATIBILITY_VERSION = 1; + DYLIB_CURRENT_VERSION = 1; + DYLIB_INSTALL_NAME_BASE = "@rpath"; + ENABLE_STRICT_OBJC_MSGSEND = YES; + GCC_NO_COMMON_BLOCKS = YES; + GCC_PREFIX_HEADER = "Target Support Files/Alamofire/Alamofire-prefix.pch"; + INFOPLIST_FILE = "Target Support Files/Alamofire/Info.plist"; + INSTALL_PATH = "$(LOCAL_LIBRARY_DIR)/Frameworks"; + IPHONEOS_DEPLOYMENT_TARGET = 8.0; + LD_RUNPATH_SEARCH_PATHS = "$(inherited) @executable_path/Frameworks @loader_path/Frameworks"; + MODULEMAP_FILE = "Target Support Files/Alamofire/Alamofire.modulemap"; + MTL_ENABLE_DEBUG_INFO = NO; + PRODUCT_NAME = Alamofire; + SDKROOT = iphoneos; + SKIP_INSTALL = YES; + SWIFT_VERSION = 3.0; + TARGETED_DEVICE_FAMILY = "1,2"; + VERSIONING_SYSTEM = "apple-generic"; + VERSION_INFO_PREFIX = ""; + }; + name = Release; + }; + 59B042A655B7C20CBAB90E385BF4E4C7 /* Debug */ = { + isa = XCBuildConfiguration; + buildSettings = { + ALWAYS_SEARCH_USER_PATHS = NO; + CLANG_ANALYZER_NONNULL = YES; + CLANG_CXX_LANGUAGE_STANDARD = "gnu++0x"; + CLANG_CXX_LIBRARY = "libc++"; + CLANG_ENABLE_MODULES = YES; + CLANG_ENABLE_OBJC_ARC = YES; + CLANG_WARN_BOOL_CONVERSION = YES; + CLANG_WARN_CONSTANT_CONVERSION = YES; + CLANG_WARN_DIRECT_OBJC_ISA_USAGE = YES; + CLANG_WARN_EMPTY_BODY = YES; + CLANG_WARN_ENUM_CONVERSION = YES; + CLANG_WARN_INT_CONVERSION = YES; + CLANG_WARN_OBJC_ROOT_CLASS = YES; + CLANG_WARN_UNREACHABLE_CODE = YES; + CLANG_WARN__DUPLICATE_METHOD_MATCH = YES; + CODE_SIGNING_REQUIRED = NO; + COPY_PHASE_STRIP = NO; + ENABLE_TESTABILITY = YES; + GCC_C_LANGUAGE_STANDARD = gnu99; + GCC_DYNAMIC_NO_PIC = NO; + GCC_OPTIMIZATION_LEVEL = 0; + GCC_PREPROCESSOR_DEFINITIONS = ( + "POD_CONFIGURATION_DEBUG=1", + "DEBUG=1", + "$(inherited)", + ); + GCC_SYMBOLS_PRIVATE_EXTERN = NO; + GCC_WARN_64_TO_32_BIT_CONVERSION = YES; + GCC_WARN_ABOUT_RETURN_TYPE = YES; + GCC_WARN_UNDECLARED_SELECTOR = YES; + GCC_WARN_UNINITIALIZED_AUTOS = YES; + GCC_WARN_UNUSED_FUNCTION = YES; + GCC_WARN_UNUSED_VARIABLE = YES; + IPHONEOS_DEPLOYMENT_TARGET = 9.0; + ONLY_ACTIVE_ARCH = YES; + PROVISIONING_PROFILE_SPECIFIER = NO_SIGNING/; + STRIP_INSTALLED_PRODUCT = NO; + SYMROOT = "${SRCROOT}/../build"; + }; + name = Debug; + }; + B7324857C38B065FEB1EEE3105C2367A /* Release */ = { + isa = XCBuildConfiguration; + buildSettings = { + ALWAYS_SEARCH_USER_PATHS = NO; + CLANG_ANALYZER_NONNULL = YES; + CLANG_CXX_LANGUAGE_STANDARD = "gnu++0x"; + CLANG_CXX_LIBRARY = "libc++"; + CLANG_ENABLE_MODULES = YES; + CLANG_ENABLE_OBJC_ARC = YES; + CLANG_WARN_BOOL_CONVERSION = YES; + CLANG_WARN_CONSTANT_CONVERSION = YES; + CLANG_WARN_DIRECT_OBJC_ISA_USAGE = YES; + CLANG_WARN_EMPTY_BODY = YES; + CLANG_WARN_ENUM_CONVERSION = YES; + CLANG_WARN_INT_CONVERSION = YES; + CLANG_WARN_OBJC_ROOT_CLASS = YES; + CLANG_WARN_UNREACHABLE_CODE = YES; + CLANG_WARN__DUPLICATE_METHOD_MATCH = YES; + CODE_SIGNING_REQUIRED = NO; + COPY_PHASE_STRIP = YES; + ENABLE_NS_ASSERTIONS = NO; + GCC_C_LANGUAGE_STANDARD = gnu99; + GCC_PREPROCESSOR_DEFINITIONS = ( + "POD_CONFIGURATION_RELEASE=1", + "$(inherited)", + ); + GCC_WARN_64_TO_32_BIT_CONVERSION = YES; + GCC_WARN_ABOUT_RETURN_TYPE = YES; + GCC_WARN_UNDECLARED_SELECTOR = YES; + GCC_WARN_UNINITIALIZED_AUTOS = YES; + GCC_WARN_UNUSED_FUNCTION = YES; + GCC_WARN_UNUSED_VARIABLE = YES; + IPHONEOS_DEPLOYMENT_TARGET = 9.0; + PROVISIONING_PROFILE_SPECIFIER = NO_SIGNING/; + STRIP_INSTALLED_PRODUCT = NO; + SYMROOT = "${SRCROOT}/../build"; + VALIDATE_PRODUCT = YES; + }; + name = Release; + }; + CA0239AB9811E3B4160B0712683B0AA1 /* Release */ = { + isa = XCBuildConfiguration; + baseConfigurationReference = 6334E785167733FEBB6F54A43C3854EB /* Pods-App.release.xcconfig */; + buildSettings = { + "CODE_SIGN_IDENTITY[sdk=appletvos*]" = ""; + "CODE_SIGN_IDENTITY[sdk=iphoneos*]" = ""; + "CODE_SIGN_IDENTITY[sdk=watchos*]" = ""; + CURRENT_PROJECT_VERSION = 1; + DEBUG_INFORMATION_FORMAT = "dwarf-with-dsym"; + DEFINES_MODULE = YES; + DYLIB_COMPATIBILITY_VERSION = 1; + DYLIB_CURRENT_VERSION = 1; + DYLIB_INSTALL_NAME_BASE = "@rpath"; + ENABLE_STRICT_OBJC_MSGSEND = YES; + GCC_NO_COMMON_BLOCKS = YES; + INFOPLIST_FILE = "Target Support Files/Pods-App/Info.plist"; + INSTALL_PATH = "$(LOCAL_LIBRARY_DIR)/Frameworks"; + IPHONEOS_DEPLOYMENT_TARGET = 9.0; + LD_RUNPATH_SEARCH_PATHS = "$(inherited) @executable_path/Frameworks @loader_path/Frameworks"; + MACH_O_TYPE = staticlib; + MODULEMAP_FILE = "Target Support Files/Pods-App/Pods-App.modulemap"; + MTL_ENABLE_DEBUG_INFO = NO; + OTHER_LDFLAGS = ""; + OTHER_LIBTOOLFLAGS = ""; + PODS_ROOT = "$(SRCROOT)"; + PRODUCT_BUNDLE_IDENTIFIER = "org.cocoapods.${PRODUCT_NAME:rfc1034identifier}"; + PRODUCT_NAME = Pods_App; + SDKROOT = iphoneos; + SKIP_INSTALL = YES; + TARGETED_DEVICE_FAMILY = "1,2"; + VERSIONING_SYSTEM = "apple-generic"; + VERSION_INFO_PREFIX = ""; + }; + name = Release; + }; + F1DFAA816D2E18E80CFCC25A6E65D79F /* Debug */ = { + isa = XCBuildConfiguration; + baseConfigurationReference = 478D2A40B9F6CD2FA965CCD860EAFB49 /* Pods-App.debug.xcconfig */; + buildSettings = { + "CODE_SIGN_IDENTITY[sdk=appletvos*]" = ""; + "CODE_SIGN_IDENTITY[sdk=iphoneos*]" = ""; + "CODE_SIGN_IDENTITY[sdk=watchos*]" = ""; + CURRENT_PROJECT_VERSION = 1; + DEBUG_INFORMATION_FORMAT = dwarf; + DEFINES_MODULE = YES; + DYLIB_COMPATIBILITY_VERSION = 1; + DYLIB_CURRENT_VERSION = 1; + DYLIB_INSTALL_NAME_BASE = "@rpath"; + ENABLE_STRICT_OBJC_MSGSEND = YES; + GCC_NO_COMMON_BLOCKS = YES; + INFOPLIST_FILE = "Target Support Files/Pods-App/Info.plist"; + INSTALL_PATH = "$(LOCAL_LIBRARY_DIR)/Frameworks"; + IPHONEOS_DEPLOYMENT_TARGET = 9.0; + LD_RUNPATH_SEARCH_PATHS = "$(inherited) @executable_path/Frameworks @loader_path/Frameworks"; + MACH_O_TYPE = staticlib; + MODULEMAP_FILE = "Target Support Files/Pods-App/Pods-App.modulemap"; + MTL_ENABLE_DEBUG_INFO = YES; + OTHER_LDFLAGS = ""; + OTHER_LIBTOOLFLAGS = ""; + PODS_ROOT = "$(SRCROOT)"; + PRODUCT_BUNDLE_IDENTIFIER = "org.cocoapods.${PRODUCT_NAME:rfc1034identifier}"; + PRODUCT_NAME = Pods_App; + SDKROOT = iphoneos; + SKIP_INSTALL = YES; + SWIFT_OPTIMIZATION_LEVEL = "-Onone"; + TARGETED_DEVICE_FAMILY = "1,2"; + VERSIONING_SYSTEM = "apple-generic"; + VERSION_INFO_PREFIX = ""; + }; + name = Debug; + }; + F383079BFBF927813EA3613CFB679FDE /* Debug */ = { + isa = XCBuildConfiguration; + baseConfigurationReference = E6F34CCF86067ED508C12C676E298C69 /* Alamofire.xcconfig */; + buildSettings = { + "CODE_SIGN_IDENTITY[sdk=appletvos*]" = ""; + "CODE_SIGN_IDENTITY[sdk=iphoneos*]" = ""; + "CODE_SIGN_IDENTITY[sdk=watchos*]" = ""; + CURRENT_PROJECT_VERSION = 1; + DEBUG_INFORMATION_FORMAT = dwarf; + DEFINES_MODULE = YES; + DYLIB_COMPATIBILITY_VERSION = 1; + DYLIB_CURRENT_VERSION = 1; + DYLIB_INSTALL_NAME_BASE = "@rpath"; + ENABLE_STRICT_OBJC_MSGSEND = YES; + GCC_NO_COMMON_BLOCKS = YES; + GCC_PREFIX_HEADER = "Target Support Files/Alamofire/Alamofire-prefix.pch"; + INFOPLIST_FILE = "Target Support Files/Alamofire/Info.plist"; + INSTALL_PATH = "$(LOCAL_LIBRARY_DIR)/Frameworks"; + IPHONEOS_DEPLOYMENT_TARGET = 8.0; + LD_RUNPATH_SEARCH_PATHS = "$(inherited) @executable_path/Frameworks @loader_path/Frameworks"; + MODULEMAP_FILE = "Target Support Files/Alamofire/Alamofire.modulemap"; + MTL_ENABLE_DEBUG_INFO = YES; + PRODUCT_NAME = Alamofire; + SDKROOT = iphoneos; + SKIP_INSTALL = YES; + SWIFT_OPTIMIZATION_LEVEL = "-Onone"; + SWIFT_VERSION = 3.0; + TARGETED_DEVICE_FAMILY = "1,2"; + VERSIONING_SYSTEM = "apple-generic"; + VERSION_INFO_PREFIX = ""; + }; + name = Debug; + }; +/* End XCBuildConfiguration section */ + +/* Begin XCConfigurationList section */ + 2D8E8EC45A3A1A1D94AE762CB5028504 /* Build configuration list for PBXProject "Pods" */ = { + isa = XCConfigurationList; + buildConfigurations = ( + 59B042A655B7C20CBAB90E385BF4E4C7 /* Debug */, + B7324857C38B065FEB1EEE3105C2367A /* Release */, + ); + defaultConfigurationIsVisible = 0; + defaultConfigurationName = Release; + }; + 3CB0BD4419B174EBD3E2BDA54114BA81 /* Build configuration list for PBXNativeTarget "Pods-App" */ = { + isa = XCConfigurationList; + buildConfigurations = ( + F1DFAA816D2E18E80CFCC25A6E65D79F /* Debug */, + CA0239AB9811E3B4160B0712683B0AA1 /* Release */, + ); + defaultConfigurationIsVisible = 0; + defaultConfigurationName = Release; + }; + 419E5D95491847CD79841B971A8A3277 /* Build configuration list for PBXNativeTarget "Alamofire" */ = { + isa = XCConfigurationList; + buildConfigurations = ( + F383079BFBF927813EA3613CFB679FDE /* Debug */, + 0A29B6F510198AF64EFD762EF6FA97A5 /* Release */, + ); + defaultConfigurationIsVisible = 0; + defaultConfigurationName = Release; + }; +/* End XCConfigurationList section */ + }; + rootObject = D41D8CD98F00B204E9800998ECF8427E /* Project object */; +} diff --git a/Pods/Pods.xcodeproj/xcuserdata/ptran.xcuserdatad/xcschemes/Alamofire.xcscheme b/Pods/Pods.xcodeproj/xcuserdata/ptran.xcuserdatad/xcschemes/Alamofire.xcscheme new file mode 100644 index 0000000..44dc41e --- /dev/null +++ b/Pods/Pods.xcodeproj/xcuserdata/ptran.xcuserdatad/xcschemes/Alamofire.xcscheme @@ -0,0 +1,60 @@ + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/Pods/Pods.xcodeproj/xcuserdata/ptran.xcuserdatad/xcschemes/Pods-App.xcscheme b/Pods/Pods.xcodeproj/xcuserdata/ptran.xcuserdatad/xcschemes/Pods-App.xcscheme new file mode 100644 index 0000000..61975fa --- /dev/null +++ b/Pods/Pods.xcodeproj/xcuserdata/ptran.xcuserdatad/xcschemes/Pods-App.xcscheme @@ -0,0 +1,71 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/Pods/Pods.xcodeproj/xcuserdata/ptran.xcuserdatad/xcschemes/xcschememanagement.plist b/Pods/Pods.xcodeproj/xcuserdata/ptran.xcuserdatad/xcschemes/xcschememanagement.plist new file mode 100644 index 0000000..d821f28 --- /dev/null +++ b/Pods/Pods.xcodeproj/xcuserdata/ptran.xcuserdatad/xcschemes/xcschememanagement.plist @@ -0,0 +1,36 @@ + + + + + SchemeUserState + + Alamofire.xcscheme + + isShown + + orderHint + 2 + + Pods-App.xcscheme + + isShown + + orderHint + 3 + + + SuppressBuildableAutocreation + + 88E9EC28B8B46C3631E6B242B50F4442 + + primary + + + 8FD22D90E3A338BA74A6B068EC6421EF + + primary + + + + + diff --git a/Pods/Target Support Files/Alamofire/Alamofire-dummy.m b/Pods/Target Support Files/Alamofire/Alamofire-dummy.m new file mode 100644 index 0000000..a6c4594 --- /dev/null +++ b/Pods/Target Support Files/Alamofire/Alamofire-dummy.m @@ -0,0 +1,5 @@ +#import +@interface PodsDummy_Alamofire : NSObject +@end +@implementation PodsDummy_Alamofire +@end diff --git a/Pods/Target Support Files/Alamofire/Alamofire-prefix.pch b/Pods/Target Support Files/Alamofire/Alamofire-prefix.pch new file mode 100644 index 0000000..beb2a24 --- /dev/null +++ b/Pods/Target Support Files/Alamofire/Alamofire-prefix.pch @@ -0,0 +1,12 @@ +#ifdef __OBJC__ +#import +#else +#ifndef FOUNDATION_EXPORT +#if defined(__cplusplus) +#define FOUNDATION_EXPORT extern "C" +#else +#define FOUNDATION_EXPORT extern +#endif +#endif +#endif + diff --git a/Pods/Target Support Files/Alamofire/Alamofire-umbrella.h b/Pods/Target Support Files/Alamofire/Alamofire-umbrella.h new file mode 100644 index 0000000..00014e3 --- /dev/null +++ b/Pods/Target Support Files/Alamofire/Alamofire-umbrella.h @@ -0,0 +1,16 @@ +#ifdef __OBJC__ +#import +#else +#ifndef FOUNDATION_EXPORT +#if defined(__cplusplus) +#define FOUNDATION_EXPORT extern "C" +#else +#define FOUNDATION_EXPORT extern +#endif +#endif +#endif + + +FOUNDATION_EXPORT double AlamofireVersionNumber; +FOUNDATION_EXPORT const unsigned char AlamofireVersionString[]; + diff --git a/Pods/Target Support Files/Alamofire/Alamofire.modulemap b/Pods/Target Support Files/Alamofire/Alamofire.modulemap new file mode 100644 index 0000000..d1f125f --- /dev/null +++ b/Pods/Target Support Files/Alamofire/Alamofire.modulemap @@ -0,0 +1,6 @@ +framework module Alamofire { + umbrella header "Alamofire-umbrella.h" + + export * + module * { export * } +} diff --git a/Pods/Target Support Files/Alamofire/Alamofire.xcconfig b/Pods/Target Support Files/Alamofire/Alamofire.xcconfig new file mode 100644 index 0000000..619e5f4 --- /dev/null +++ b/Pods/Target Support Files/Alamofire/Alamofire.xcconfig @@ -0,0 +1,10 @@ +CONFIGURATION_BUILD_DIR = $PODS_CONFIGURATION_BUILD_DIR/Alamofire +GCC_PREPROCESSOR_DEFINITIONS = $(inherited) COCOAPODS=1 +HEADER_SEARCH_PATHS = "${PODS_ROOT}/Headers/Private" "${PODS_ROOT}/Headers/Public" +OTHER_SWIFT_FLAGS = $(inherited) "-D" "COCOAPODS" +PODS_BUILD_DIR = $BUILD_DIR +PODS_CONFIGURATION_BUILD_DIR = $PODS_BUILD_DIR/$(CONFIGURATION)$(EFFECTIVE_PLATFORM_NAME) +PODS_ROOT = ${SRCROOT} +PODS_TARGET_SRCROOT = ${PODS_ROOT}/Alamofire +PRODUCT_BUNDLE_IDENTIFIER = org.cocoapods.${PRODUCT_NAME:rfc1034identifier} +SKIP_INSTALL = YES diff --git a/Pods/Target Support Files/Alamofire/Info.plist b/Pods/Target Support Files/Alamofire/Info.plist new file mode 100644 index 0000000..a83149a --- /dev/null +++ b/Pods/Target Support Files/Alamofire/Info.plist @@ -0,0 +1,26 @@ + + + + + CFBundleDevelopmentRegion + en + CFBundleExecutable + ${EXECUTABLE_NAME} + CFBundleIdentifier + ${PRODUCT_BUNDLE_IDENTIFIER} + CFBundleInfoDictionaryVersion + 6.0 + CFBundleName + ${PRODUCT_NAME} + CFBundlePackageType + FMWK + CFBundleShortVersionString + 4.3.0 + CFBundleSignature + ???? + CFBundleVersion + ${CURRENT_PROJECT_VERSION} + NSPrincipalClass + + + diff --git a/Pods/Target Support Files/Pods-App/Info.plist b/Pods/Target Support Files/Pods-App/Info.plist new file mode 100644 index 0000000..2243fe6 --- /dev/null +++ b/Pods/Target Support Files/Pods-App/Info.plist @@ -0,0 +1,26 @@ + + + + + CFBundleDevelopmentRegion + en + CFBundleExecutable + ${EXECUTABLE_NAME} + CFBundleIdentifier + ${PRODUCT_BUNDLE_IDENTIFIER} + CFBundleInfoDictionaryVersion + 6.0 + CFBundleName + ${PRODUCT_NAME} + CFBundlePackageType + FMWK + CFBundleShortVersionString + 1.0.0 + CFBundleSignature + ???? + CFBundleVersion + ${CURRENT_PROJECT_VERSION} + NSPrincipalClass + + + diff --git a/Pods/Target Support Files/Pods-App/Pods-App-acknowledgements.markdown b/Pods/Target Support Files/Pods-App/Pods-App-acknowledgements.markdown new file mode 100644 index 0000000..e04b910 --- /dev/null +++ b/Pods/Target Support Files/Pods-App/Pods-App-acknowledgements.markdown @@ -0,0 +1,26 @@ +# Acknowledgements +This application makes use of the following third party libraries: + +## Alamofire + +Copyright (c) 2014-2016 Alamofire Software Foundation (http://alamofire.org/) + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in +all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN +THE SOFTWARE. + +Generated by CocoaPods - https://cocoapods.org diff --git a/Pods/Target Support Files/Pods-App/Pods-App-acknowledgements.plist b/Pods/Target Support Files/Pods-App/Pods-App-acknowledgements.plist new file mode 100644 index 0000000..9317477 --- /dev/null +++ b/Pods/Target Support Files/Pods-App/Pods-App-acknowledgements.plist @@ -0,0 +1,58 @@ + + + + + PreferenceSpecifiers + + + FooterText + This application makes use of the following third party libraries: + Title + Acknowledgements + Type + PSGroupSpecifier + + + FooterText + Copyright (c) 2014-2016 Alamofire Software Foundation (http://alamofire.org/) + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in +all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN +THE SOFTWARE. + + License + MIT + Title + Alamofire + Type + PSGroupSpecifier + + + FooterText + Generated by CocoaPods - https://cocoapods.org + Title + + Type + PSGroupSpecifier + + + StringsTable + Acknowledgements + Title + Acknowledgements + + diff --git a/Pods/Target Support Files/Pods-App/Pods-App-dummy.m b/Pods/Target Support Files/Pods-App/Pods-App-dummy.m new file mode 100644 index 0000000..ac0b6a1 --- /dev/null +++ b/Pods/Target Support Files/Pods-App/Pods-App-dummy.m @@ -0,0 +1,5 @@ +#import +@interface PodsDummy_Pods_App : NSObject +@end +@implementation PodsDummy_Pods_App +@end diff --git a/Pods/Target Support Files/Pods-App/Pods-App-frameworks.sh b/Pods/Target Support Files/Pods-App/Pods-App-frameworks.sh new file mode 100755 index 0000000..e2d5f6d --- /dev/null +++ b/Pods/Target Support Files/Pods-App/Pods-App-frameworks.sh @@ -0,0 +1,99 @@ +#!/bin/sh +set -e + +echo "mkdir -p ${CONFIGURATION_BUILD_DIR}/${FRAMEWORKS_FOLDER_PATH}" +mkdir -p "${CONFIGURATION_BUILD_DIR}/${FRAMEWORKS_FOLDER_PATH}" + +SWIFT_STDLIB_PATH="${DT_TOOLCHAIN_DIR}/usr/lib/swift/${PLATFORM_NAME}" + +install_framework() +{ + if [ -r "${BUILT_PRODUCTS_DIR}/$1" ]; then + local source="${BUILT_PRODUCTS_DIR}/$1" + elif [ -r "${BUILT_PRODUCTS_DIR}/$(basename "$1")" ]; then + local source="${BUILT_PRODUCTS_DIR}/$(basename "$1")" + elif [ -r "$1" ]; then + local source="$1" + fi + + local destination="${TARGET_BUILD_DIR}/${FRAMEWORKS_FOLDER_PATH}" + + if [ -L "${source}" ]; then + echo "Symlinked..." + source="$(readlink "${source}")" + fi + + # use filter instead of exclude so missing patterns dont' throw errors + echo "rsync -av --filter \"- CVS/\" --filter \"- .svn/\" --filter \"- .git/\" --filter \"- .hg/\" --filter \"- Headers\" --filter \"- PrivateHeaders\" --filter \"- Modules\" \"${source}\" \"${destination}\"" + rsync -av --filter "- CVS/" --filter "- .svn/" --filter "- .git/" --filter "- .hg/" --filter "- Headers" --filter "- PrivateHeaders" --filter "- Modules" "${source}" "${destination}" + + local basename + basename="$(basename -s .framework "$1")" + binary="${destination}/${basename}.framework/${basename}" + if ! [ -r "$binary" ]; then + binary="${destination}/${basename}" + fi + + # Strip invalid architectures so "fat" simulator / device frameworks work on device + if [[ "$(file "$binary")" == *"dynamically linked shared library"* ]]; then + strip_invalid_archs "$binary" + fi + + # Resign the code if required by the build settings to avoid unstable apps + code_sign_if_enabled "${destination}/$(basename "$1")" + + # Embed linked Swift runtime libraries. No longer necessary as of Xcode 7. + if [ "${XCODE_VERSION_MAJOR}" -lt 7 ]; then + local swift_runtime_libs + swift_runtime_libs=$(xcrun otool -LX "$binary" | grep --color=never @rpath/libswift | sed -E s/@rpath\\/\(.+dylib\).*/\\1/g | uniq -u && exit ${PIPESTATUS[0]}) + for lib in $swift_runtime_libs; do + echo "rsync -auv \"${SWIFT_STDLIB_PATH}/${lib}\" \"${destination}\"" + rsync -auv "${SWIFT_STDLIB_PATH}/${lib}" "${destination}" + code_sign_if_enabled "${destination}/${lib}" + done + fi +} + +# Signs a framework with the provided identity +code_sign_if_enabled() { + if [ -n "${EXPANDED_CODE_SIGN_IDENTITY}" -a "${CODE_SIGNING_REQUIRED}" != "NO" -a "${CODE_SIGNING_ALLOWED}" != "NO" ]; then + # Use the current code_sign_identitiy + echo "Code Signing $1 with Identity ${EXPANDED_CODE_SIGN_IDENTITY_NAME}" + local code_sign_cmd="/usr/bin/codesign --force --sign ${EXPANDED_CODE_SIGN_IDENTITY} ${OTHER_CODE_SIGN_FLAGS} --preserve-metadata=identifier,entitlements '$1'" + + if [ "${COCOAPODS_PARALLEL_CODE_SIGN}" == "true" ]; then + code_sign_cmd="$code_sign_cmd &" + fi + echo "$code_sign_cmd" + eval "$code_sign_cmd" + fi +} + +# Strip invalid architectures +strip_invalid_archs() { + binary="$1" + # Get architectures for current file + archs="$(lipo -info "$binary" | rev | cut -d ':' -f1 | rev)" + stripped="" + for arch in $archs; do + if ! [[ "${VALID_ARCHS}" == *"$arch"* ]]; then + # Strip non-valid architectures in-place + lipo -remove "$arch" -output "$binary" "$binary" || exit 1 + stripped="$stripped $arch" + fi + done + if [[ "$stripped" ]]; then + echo "Stripped $binary of architectures:$stripped" + fi +} + + +if [[ "$CONFIGURATION" == "Debug" ]]; then + install_framework "$BUILT_PRODUCTS_DIR/Alamofire/Alamofire.framework" +fi +if [[ "$CONFIGURATION" == "Release" ]]; then + install_framework "$BUILT_PRODUCTS_DIR/Alamofire/Alamofire.framework" +fi +if [ "${COCOAPODS_PARALLEL_CODE_SIGN}" == "true" ]; then + wait +fi diff --git a/Pods/Target Support Files/Pods-App/Pods-App-resources.sh b/Pods/Target Support Files/Pods-App/Pods-App-resources.sh new file mode 100755 index 0000000..4602c68 --- /dev/null +++ b/Pods/Target Support Files/Pods-App/Pods-App-resources.sh @@ -0,0 +1,99 @@ +#!/bin/sh +set -e + +mkdir -p "${TARGET_BUILD_DIR}/${UNLOCALIZED_RESOURCES_FOLDER_PATH}" + +RESOURCES_TO_COPY=${PODS_ROOT}/resources-to-copy-${TARGETNAME}.txt +> "$RESOURCES_TO_COPY" + +XCASSET_FILES=() + +case "${TARGETED_DEVICE_FAMILY}" in + 1,2) + TARGET_DEVICE_ARGS="--target-device ipad --target-device iphone" + ;; + 1) + TARGET_DEVICE_ARGS="--target-device iphone" + ;; + 2) + TARGET_DEVICE_ARGS="--target-device ipad" + ;; + 3) + TARGET_DEVICE_ARGS="--target-device tv" + ;; + *) + TARGET_DEVICE_ARGS="--target-device mac" + ;; +esac + +install_resource() +{ + if [[ "$1" = /* ]] ; then + RESOURCE_PATH="$1" + else + RESOURCE_PATH="${PODS_ROOT}/$1" + fi + if [[ ! -e "$RESOURCE_PATH" ]] ; then + cat << EOM +error: Resource "$RESOURCE_PATH" not found. Run 'pod install' to update the copy resources script. +EOM + exit 1 + fi + case $RESOURCE_PATH in + *.storyboard) + echo "ibtool --reference-external-strings-file --errors --warnings --notices --minimum-deployment-target ${!DEPLOYMENT_TARGET_SETTING_NAME} --output-format human-readable-text --compile ${TARGET_BUILD_DIR}/${UNLOCALIZED_RESOURCES_FOLDER_PATH}/`basename \"$RESOURCE_PATH\" .storyboard`.storyboardc $RESOURCE_PATH --sdk ${SDKROOT} ${TARGET_DEVICE_ARGS}" + ibtool --reference-external-strings-file --errors --warnings --notices --minimum-deployment-target ${!DEPLOYMENT_TARGET_SETTING_NAME} --output-format human-readable-text --compile "${TARGET_BUILD_DIR}/${UNLOCALIZED_RESOURCES_FOLDER_PATH}/`basename \"$RESOURCE_PATH\" .storyboard`.storyboardc" "$RESOURCE_PATH" --sdk "${SDKROOT}" ${TARGET_DEVICE_ARGS} + ;; + *.xib) + echo "ibtool --reference-external-strings-file --errors --warnings --notices --minimum-deployment-target ${!DEPLOYMENT_TARGET_SETTING_NAME} --output-format human-readable-text --compile ${TARGET_BUILD_DIR}/${UNLOCALIZED_RESOURCES_FOLDER_PATH}/`basename \"$RESOURCE_PATH\" .xib`.nib $RESOURCE_PATH --sdk ${SDKROOT} ${TARGET_DEVICE_ARGS}" + ibtool --reference-external-strings-file --errors --warnings --notices --minimum-deployment-target ${!DEPLOYMENT_TARGET_SETTING_NAME} --output-format human-readable-text --compile "${TARGET_BUILD_DIR}/${UNLOCALIZED_RESOURCES_FOLDER_PATH}/`basename \"$RESOURCE_PATH\" .xib`.nib" "$RESOURCE_PATH" --sdk "${SDKROOT}" ${TARGET_DEVICE_ARGS} + ;; + *.framework) + echo "mkdir -p ${TARGET_BUILD_DIR}/${FRAMEWORKS_FOLDER_PATH}" + mkdir -p "${TARGET_BUILD_DIR}/${FRAMEWORKS_FOLDER_PATH}" + echo "rsync -av $RESOURCE_PATH ${TARGET_BUILD_DIR}/${FRAMEWORKS_FOLDER_PATH}" + rsync -av "$RESOURCE_PATH" "${TARGET_BUILD_DIR}/${FRAMEWORKS_FOLDER_PATH}" + ;; + *.xcdatamodel) + echo "xcrun momc \"$RESOURCE_PATH\" \"${TARGET_BUILD_DIR}/${UNLOCALIZED_RESOURCES_FOLDER_PATH}/`basename "$RESOURCE_PATH"`.mom\"" + xcrun momc "$RESOURCE_PATH" "${TARGET_BUILD_DIR}/${UNLOCALIZED_RESOURCES_FOLDER_PATH}/`basename "$RESOURCE_PATH" .xcdatamodel`.mom" + ;; + *.xcdatamodeld) + echo "xcrun momc \"$RESOURCE_PATH\" \"${TARGET_BUILD_DIR}/${UNLOCALIZED_RESOURCES_FOLDER_PATH}/`basename "$RESOURCE_PATH" .xcdatamodeld`.momd\"" + xcrun momc "$RESOURCE_PATH" "${TARGET_BUILD_DIR}/${UNLOCALIZED_RESOURCES_FOLDER_PATH}/`basename "$RESOURCE_PATH" .xcdatamodeld`.momd" + ;; + *.xcmappingmodel) + echo "xcrun mapc \"$RESOURCE_PATH\" \"${TARGET_BUILD_DIR}/${UNLOCALIZED_RESOURCES_FOLDER_PATH}/`basename "$RESOURCE_PATH" .xcmappingmodel`.cdm\"" + xcrun mapc "$RESOURCE_PATH" "${TARGET_BUILD_DIR}/${UNLOCALIZED_RESOURCES_FOLDER_PATH}/`basename "$RESOURCE_PATH" .xcmappingmodel`.cdm" + ;; + *.xcassets) + ABSOLUTE_XCASSET_FILE="$RESOURCE_PATH" + XCASSET_FILES+=("$ABSOLUTE_XCASSET_FILE") + ;; + *) + echo "$RESOURCE_PATH" + echo "$RESOURCE_PATH" >> "$RESOURCES_TO_COPY" + ;; + esac +} + +mkdir -p "${TARGET_BUILD_DIR}/${UNLOCALIZED_RESOURCES_FOLDER_PATH}" +rsync -avr --copy-links --no-relative --exclude '*/.svn/*' --files-from="$RESOURCES_TO_COPY" / "${TARGET_BUILD_DIR}/${UNLOCALIZED_RESOURCES_FOLDER_PATH}" +if [[ "${ACTION}" == "install" ]] && [[ "${SKIP_INSTALL}" == "NO" ]]; then + mkdir -p "${INSTALL_DIR}/${UNLOCALIZED_RESOURCES_FOLDER_PATH}" + rsync -avr --copy-links --no-relative --exclude '*/.svn/*' --files-from="$RESOURCES_TO_COPY" / "${INSTALL_DIR}/${UNLOCALIZED_RESOURCES_FOLDER_PATH}" +fi +rm -f "$RESOURCES_TO_COPY" + +if [[ -n "${WRAPPER_EXTENSION}" ]] && [ "`xcrun --find actool`" ] && [ -n "$XCASSET_FILES" ] +then + # Find all other xcassets (this unfortunately includes those of path pods and other targets). + OTHER_XCASSETS=$(find "$PWD" -iname "*.xcassets" -type d) + while read line; do + if [[ $line != "${PODS_ROOT}*" ]]; then + XCASSET_FILES+=("$line") + fi + done <<<"$OTHER_XCASSETS" + + printf "%s\0" "${XCASSET_FILES[@]}" | xargs -0 xcrun actool --output-format human-readable-text --notices --warnings --platform "${PLATFORM_NAME}" --minimum-deployment-target "${!DEPLOYMENT_TARGET_SETTING_NAME}" ${TARGET_DEVICE_ARGS} --compress-pngs --compile "${BUILT_PRODUCTS_DIR}/${UNLOCALIZED_RESOURCES_FOLDER_PATH}" +fi diff --git a/Pods/Target Support Files/Pods-App/Pods-App-umbrella.h b/Pods/Target Support Files/Pods-App/Pods-App-umbrella.h new file mode 100644 index 0000000..e6a69e5 --- /dev/null +++ b/Pods/Target Support Files/Pods-App/Pods-App-umbrella.h @@ -0,0 +1,16 @@ +#ifdef __OBJC__ +#import +#else +#ifndef FOUNDATION_EXPORT +#if defined(__cplusplus) +#define FOUNDATION_EXPORT extern "C" +#else +#define FOUNDATION_EXPORT extern +#endif +#endif +#endif + + +FOUNDATION_EXPORT double Pods_AppVersionNumber; +FOUNDATION_EXPORT const unsigned char Pods_AppVersionString[]; + diff --git a/Pods/Target Support Files/Pods-App/Pods-App.debug.xcconfig b/Pods/Target Support Files/Pods-App/Pods-App.debug.xcconfig new file mode 100644 index 0000000..f45008c --- /dev/null +++ b/Pods/Target Support Files/Pods-App/Pods-App.debug.xcconfig @@ -0,0 +1,10 @@ +ALWAYS_EMBED_SWIFT_STANDARD_LIBRARIES = YES +FRAMEWORK_SEARCH_PATHS = $(inherited) "$PODS_CONFIGURATION_BUILD_DIR/Alamofire" +GCC_PREPROCESSOR_DEFINITIONS = $(inherited) COCOAPODS=1 +LD_RUNPATH_SEARCH_PATHS = $(inherited) '@executable_path/Frameworks' '@loader_path/Frameworks' +OTHER_CFLAGS = $(inherited) -iquote "$PODS_CONFIGURATION_BUILD_DIR/Alamofire/Alamofire.framework/Headers" +OTHER_LDFLAGS = $(inherited) -framework "Alamofire" +OTHER_SWIFT_FLAGS = $(inherited) "-D" "COCOAPODS" +PODS_BUILD_DIR = $BUILD_DIR +PODS_CONFIGURATION_BUILD_DIR = $PODS_BUILD_DIR/$(CONFIGURATION)$(EFFECTIVE_PLATFORM_NAME) +PODS_ROOT = ${SRCROOT}/Pods diff --git a/Pods/Target Support Files/Pods-App/Pods-App.modulemap b/Pods/Target Support Files/Pods-App/Pods-App.modulemap new file mode 100644 index 0000000..f4aba19 --- /dev/null +++ b/Pods/Target Support Files/Pods-App/Pods-App.modulemap @@ -0,0 +1,6 @@ +framework module Pods_App { + umbrella header "Pods-App-umbrella.h" + + export * + module * { export * } +} diff --git a/Pods/Target Support Files/Pods-App/Pods-App.release.xcconfig b/Pods/Target Support Files/Pods-App/Pods-App.release.xcconfig new file mode 100644 index 0000000..f45008c --- /dev/null +++ b/Pods/Target Support Files/Pods-App/Pods-App.release.xcconfig @@ -0,0 +1,10 @@ +ALWAYS_EMBED_SWIFT_STANDARD_LIBRARIES = YES +FRAMEWORK_SEARCH_PATHS = $(inherited) "$PODS_CONFIGURATION_BUILD_DIR/Alamofire" +GCC_PREPROCESSOR_DEFINITIONS = $(inherited) COCOAPODS=1 +LD_RUNPATH_SEARCH_PATHS = $(inherited) '@executable_path/Frameworks' '@loader_path/Frameworks' +OTHER_CFLAGS = $(inherited) -iquote "$PODS_CONFIGURATION_BUILD_DIR/Alamofire/Alamofire.framework/Headers" +OTHER_LDFLAGS = $(inherited) -framework "Alamofire" +OTHER_SWIFT_FLAGS = $(inherited) "-D" "COCOAPODS" +PODS_BUILD_DIR = $BUILD_DIR +PODS_CONFIGURATION_BUILD_DIR = $PODS_BUILD_DIR/$(CONFIGURATION)$(EFFECTIVE_PLATFORM_NAME) +PODS_ROOT = ${SRCROOT}/Pods -- 1.8.5.3