From 4edb2bc26f5722b960ee2301f9889002ece5e7ee Mon Sep 17 00:00:00 2001 From: Yurii Kolesnykov Date: Thu, 27 Sep 2018 19:13:29 +0300 Subject: [PATCH] init --- .gitignore | 104 ++ .ruby-version | 1 + .swift-version | 1 + .swiftlint.yml | 48 + .travis.yml | 10 + Gemfile | 9 + Gemfile.lock | 79 ++ GiphySearch.xcodeproj/project.pbxproj | 428 ++++++ .../contents.xcworkspacedata | 7 + .../xcshareddata/IDEWorkspaceChecks.plist | 8 + .../xcschemes/Giphy Search.xcscheme | 91 ++ .../contents.xcworkspacedata | 10 + .../xcshareddata/IDEWorkspaceChecks.plist | 8 + GiphySearch/AppDelegate.swift | 19 + .../AppIcon.appiconset/Contents.json | 98 ++ GiphySearch/Assets.xcassets/Contents.json | 6 + .../Base.lproj/LaunchScreen.storyboard | 25 + GiphySearch/Base.lproj/Main.storyboard | 24 + GiphySearch/Info.plist | 45 + GiphySearch/ViewController.swift | 18 + Podfile | 10 + Podfile.lock | 25 + Pods/Alamofire/LICENSE | 19 + Pods/Alamofire/README.md | 242 ++++ Pods/Alamofire/Source/AFError.swift | 460 +++++++ Pods/Alamofire/Source/Alamofire.swift | 465 +++++++ .../Source/DispatchQueue+Alamofire.swift | 37 + Pods/Alamofire/Source/MultipartFormData.swift | 580 ++++++++ .../Source/NetworkReachabilityManager.swift | 233 ++++ Pods/Alamofire/Source/Notifications.swift | 55 + Pods/Alamofire/Source/ParameterEncoding.swift | 483 +++++++ Pods/Alamofire/Source/Request.swift | 654 +++++++++ Pods/Alamofire/Source/Response.swift | 567 ++++++++ .../Source/ResponseSerialization.swift | 715 ++++++++++ Pods/Alamofire/Source/Result.swift | 300 ++++ Pods/Alamofire/Source/ServerTrustPolicy.swift | 307 +++++ Pods/Alamofire/Source/SessionDelegate.swift | 725 ++++++++++ Pods/Alamofire/Source/SessionManager.swift | 896 ++++++++++++ Pods/Alamofire/Source/TaskDelegate.swift | 466 +++++++ Pods/Alamofire/Source/Timeline.swift | 136 ++ Pods/Alamofire/Source/Validation.swift | 315 +++++ Pods/AlamofireImage/LICENSE | 19 + Pods/AlamofireImage/README.md | 590 ++++++++ Pods/AlamofireImage/Source/AFIError.swift | 63 + Pods/AlamofireImage/Source/Image.swift | 33 + Pods/AlamofireImage/Source/ImageCache.swift | 350 +++++ .../Source/ImageDownloader.swift | 559 ++++++++ Pods/AlamofireImage/Source/ImageFilter.swift | 423 ++++++ .../Source/Request+AlamofireImage.swift | 327 +++++ .../Source/UIButton+AlamofireImage.swift | 479 +++++++ .../Source/UIImage+AlamofireImage.swift | 322 +++++ .../Source/UIImageView+AlamofireImage.swift | 398 ++++++ Pods/GiphyCoreSDK/LICENSE | 373 +++++ Pods/GiphyCoreSDK/README.md | 356 +++++ .../Sources/GPHAbstractClient.swift | 166 +++ .../Sources/GPHAsyncOperation.swift | 111 ++ Pods/GiphyCoreSDK/Sources/GPHBottleData.swift | 114 ++ Pods/GiphyCoreSDK/Sources/GPHCategory.swift | 195 +++ Pods/GiphyCoreSDK/Sources/GPHChannel.swift | 191 +++ .../Sources/GPHChannelResponse.swift | 75 + Pods/GiphyCoreSDK/Sources/GPHChannelTag.swift | 106 ++ Pods/GiphyCoreSDK/Sources/GPHClient.swift | 518 +++++++ Pods/GiphyCoreSDK/Sources/GPHError.swift | 94 ++ Pods/GiphyCoreSDK/Sources/GPHFilterable.swift | 28 + Pods/GiphyCoreSDK/Sources/GPHImage.swift | 183 +++ Pods/GiphyCoreSDK/Sources/GPHImages.swift | 345 +++++ .../Sources/GPHListCategoryResponse.swift | 102 ++ .../Sources/GPHListChannelResponse.swift | 99 ++ .../Sources/GPHListMediaResponse.swift | 94 ++ .../GPHListTermSuggestionRespose.swift | 89 ++ Pods/GiphyCoreSDK/Sources/GPHMappable.swift | 108 ++ Pods/GiphyCoreSDK/Sources/GPHMedia.swift | 333 +++++ .../Sources/GPHMediaResponse.swift | 83 ++ Pods/GiphyCoreSDK/Sources/GPHMeta.swift | 93 ++ .../Sources/GPHNetworkReachability.swift | 66 + Pods/GiphyCoreSDK/Sources/GPHPagination.swift | 102 ++ Pods/GiphyCoreSDK/Sources/GPHRequest.swift | 352 +++++ .../Sources/GPHRequestConfig.swift | 27 + Pods/GiphyCoreSDK/Sources/GPHResponse.swift | 53 + .../Sources/GPHTermSuggestion.swift | 107 ++ Pods/GiphyCoreSDK/Sources/GPHTypes.swift | 523 +++++++ Pods/GiphyCoreSDK/Sources/GPHUser.swift | 241 ++++ Pods/GiphyCoreSDK/Sources/GiphyCore.swift | 32 + Pods/Manifest.lock | 25 + Pods/Pods.xcodeproj/project.pbxproj | 1209 +++++++++++++++++ .../Alamofire/Alamofire-dummy.m | 5 + .../Alamofire/Alamofire-prefix.pch | 12 + .../Alamofire/Alamofire-umbrella.h | 16 + .../Alamofire/Alamofire.modulemap | 6 + .../Alamofire/Alamofire.xcconfig | 9 + .../Target Support Files/Alamofire/Info.plist | 26 + .../AlamofireImage/AlamofireImage-dummy.m | 5 + .../AlamofireImage/AlamofireImage-prefix.pch | 12 + .../AlamofireImage/AlamofireImage-umbrella.h | 16 + .../AlamofireImage/AlamofireImage.modulemap | 6 + .../AlamofireImage/AlamofireImage.xcconfig | 10 + .../AlamofireImage/Info.plist | 26 + .../GiphyCoreSDK/GiphyCoreSDK-dummy.m | 5 + .../GiphyCoreSDK/GiphyCoreSDK-prefix.pch | 12 + .../GiphyCoreSDK/GiphyCoreSDK-umbrella.h | 16 + .../GiphyCoreSDK/GiphyCoreSDK.modulemap | 6 + .../GiphyCoreSDK/GiphyCoreSDK.xcconfig | 9 + .../GiphyCoreSDK/Info.plist | 26 + .../Pods-Giphy Search/Info.plist | 26 + ...ods-Giphy Search-acknowledgements.markdown | 426 ++++++ .../Pods-Giphy Search-acknowledgements.plist | 470 +++++++ .../Pods-Giphy Search-dummy.m | 5 + .../Pods-Giphy Search-frameworks.sh | 157 +++ .../Pods-Giphy Search-resources.sh | 118 ++ .../Pods-Giphy Search-umbrella.h | 16 + .../Pods-Giphy Search.debug.xcconfig | 11 + .../Pods-Giphy Search.modulemap | 6 + .../Pods-Giphy Search.release.xcconfig | 11 + README.md | 2 + 114 files changed, 20356 insertions(+) create mode 100644 .gitignore create mode 100644 .ruby-version create mode 100644 .swift-version create mode 100644 .swiftlint.yml create mode 100644 .travis.yml create mode 100644 Gemfile create mode 100644 Gemfile.lock create mode 100644 GiphySearch.xcodeproj/project.pbxproj create mode 100644 GiphySearch.xcodeproj/project.xcworkspace/contents.xcworkspacedata create mode 100644 GiphySearch.xcodeproj/project.xcworkspace/xcshareddata/IDEWorkspaceChecks.plist create mode 100644 GiphySearch.xcodeproj/xcshareddata/xcschemes/Giphy Search.xcscheme create mode 100644 GiphySearch.xcworkspace/contents.xcworkspacedata create mode 100644 GiphySearch.xcworkspace/xcshareddata/IDEWorkspaceChecks.plist create mode 100644 GiphySearch/AppDelegate.swift create mode 100644 GiphySearch/Assets.xcassets/AppIcon.appiconset/Contents.json create mode 100644 GiphySearch/Assets.xcassets/Contents.json create mode 100644 GiphySearch/Base.lproj/LaunchScreen.storyboard create mode 100644 GiphySearch/Base.lproj/Main.storyboard create mode 100644 GiphySearch/Info.plist create mode 100644 GiphySearch/ViewController.swift 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/AlamofireImage/LICENSE create mode 100644 Pods/AlamofireImage/README.md create mode 100644 Pods/AlamofireImage/Source/AFIError.swift create mode 100644 Pods/AlamofireImage/Source/Image.swift create mode 100644 Pods/AlamofireImage/Source/ImageCache.swift create mode 100644 Pods/AlamofireImage/Source/ImageDownloader.swift create mode 100644 Pods/AlamofireImage/Source/ImageFilter.swift create mode 100644 Pods/AlamofireImage/Source/Request+AlamofireImage.swift create mode 100644 Pods/AlamofireImage/Source/UIButton+AlamofireImage.swift create mode 100644 Pods/AlamofireImage/Source/UIImage+AlamofireImage.swift create mode 100644 Pods/AlamofireImage/Source/UIImageView+AlamofireImage.swift create mode 100644 Pods/GiphyCoreSDK/LICENSE create mode 100644 Pods/GiphyCoreSDK/README.md create mode 100644 Pods/GiphyCoreSDK/Sources/GPHAbstractClient.swift create mode 100644 Pods/GiphyCoreSDK/Sources/GPHAsyncOperation.swift create mode 100644 Pods/GiphyCoreSDK/Sources/GPHBottleData.swift create mode 100644 Pods/GiphyCoreSDK/Sources/GPHCategory.swift create mode 100644 Pods/GiphyCoreSDK/Sources/GPHChannel.swift create mode 100644 Pods/GiphyCoreSDK/Sources/GPHChannelResponse.swift create mode 100644 Pods/GiphyCoreSDK/Sources/GPHChannelTag.swift create mode 100644 Pods/GiphyCoreSDK/Sources/GPHClient.swift create mode 100644 Pods/GiphyCoreSDK/Sources/GPHError.swift create mode 100644 Pods/GiphyCoreSDK/Sources/GPHFilterable.swift create mode 100644 Pods/GiphyCoreSDK/Sources/GPHImage.swift create mode 100644 Pods/GiphyCoreSDK/Sources/GPHImages.swift create mode 100644 Pods/GiphyCoreSDK/Sources/GPHListCategoryResponse.swift create mode 100644 Pods/GiphyCoreSDK/Sources/GPHListChannelResponse.swift create mode 100644 Pods/GiphyCoreSDK/Sources/GPHListMediaResponse.swift create mode 100644 Pods/GiphyCoreSDK/Sources/GPHListTermSuggestionRespose.swift create mode 100644 Pods/GiphyCoreSDK/Sources/GPHMappable.swift create mode 100644 Pods/GiphyCoreSDK/Sources/GPHMedia.swift create mode 100644 Pods/GiphyCoreSDK/Sources/GPHMediaResponse.swift create mode 100644 Pods/GiphyCoreSDK/Sources/GPHMeta.swift create mode 100644 Pods/GiphyCoreSDK/Sources/GPHNetworkReachability.swift create mode 100644 Pods/GiphyCoreSDK/Sources/GPHPagination.swift create mode 100644 Pods/GiphyCoreSDK/Sources/GPHRequest.swift create mode 100644 Pods/GiphyCoreSDK/Sources/GPHRequestConfig.swift create mode 100644 Pods/GiphyCoreSDK/Sources/GPHResponse.swift create mode 100644 Pods/GiphyCoreSDK/Sources/GPHTermSuggestion.swift create mode 100644 Pods/GiphyCoreSDK/Sources/GPHTypes.swift create mode 100644 Pods/GiphyCoreSDK/Sources/GPHUser.swift create mode 100644 Pods/GiphyCoreSDK/Sources/GiphyCore.swift create mode 100644 Pods/Manifest.lock create mode 100644 Pods/Pods.xcodeproj/project.pbxproj 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/AlamofireImage/AlamofireImage-dummy.m create mode 100644 Pods/Target Support Files/AlamofireImage/AlamofireImage-prefix.pch create mode 100644 Pods/Target Support Files/AlamofireImage/AlamofireImage-umbrella.h create mode 100644 Pods/Target Support Files/AlamofireImage/AlamofireImage.modulemap create mode 100644 Pods/Target Support Files/AlamofireImage/AlamofireImage.xcconfig create mode 100644 Pods/Target Support Files/AlamofireImage/Info.plist create mode 100644 Pods/Target Support Files/GiphyCoreSDK/GiphyCoreSDK-dummy.m create mode 100644 Pods/Target Support Files/GiphyCoreSDK/GiphyCoreSDK-prefix.pch create mode 100644 Pods/Target Support Files/GiphyCoreSDK/GiphyCoreSDK-umbrella.h create mode 100644 Pods/Target Support Files/GiphyCoreSDK/GiphyCoreSDK.modulemap create mode 100644 Pods/Target Support Files/GiphyCoreSDK/GiphyCoreSDK.xcconfig create mode 100644 Pods/Target Support Files/GiphyCoreSDK/Info.plist create mode 100644 Pods/Target Support Files/Pods-Giphy Search/Info.plist create mode 100644 Pods/Target Support Files/Pods-Giphy Search/Pods-Giphy Search-acknowledgements.markdown create mode 100644 Pods/Target Support Files/Pods-Giphy Search/Pods-Giphy Search-acknowledgements.plist create mode 100644 Pods/Target Support Files/Pods-Giphy Search/Pods-Giphy Search-dummy.m create mode 100755 Pods/Target Support Files/Pods-Giphy Search/Pods-Giphy Search-frameworks.sh create mode 100755 Pods/Target Support Files/Pods-Giphy Search/Pods-Giphy Search-resources.sh create mode 100644 Pods/Target Support Files/Pods-Giphy Search/Pods-Giphy Search-umbrella.h create mode 100644 Pods/Target Support Files/Pods-Giphy Search/Pods-Giphy Search.debug.xcconfig create mode 100644 Pods/Target Support Files/Pods-Giphy Search/Pods-Giphy Search.modulemap create mode 100644 Pods/Target Support Files/Pods-Giphy Search/Pods-Giphy Search.release.xcconfig create mode 100644 README.md diff --git a/.gitignore b/.gitignore new file mode 100644 index 0000000..423278e --- /dev/null +++ b/.gitignore @@ -0,0 +1,104 @@ +# General +.DS_Store +.AppleDouble +.LSOverride + +# Icon must end with two \r +Icon + +# Thumbnails +._* + +# Files that might appear in the root of a volume +.DocumentRevisions-V100 +.fseventsd +.Spotlight-V100 +.TemporaryItems +.Trashes +.VolumeIcon.icns +.com.apple.timemachine.donotpresent + +# Directories potentially created on remote AFP share +.AppleDB +.AppleDesktop +Network Trash Folder +Temporary Items +.apdisk +# Xcode +# +# gitignore contributors: remember to update Global/Xcode.gitignore, Objective-C.gitignore & Swift.gitignore + +## Build generated +build/ +DerivedData/ + +## Various settings +*.pbxuser +!default.pbxuser +*.mode1v3 +!default.mode1v3 +*.mode2v3 +!default.mode2v3 +*.perspectivev3 +!default.perspectivev3 +xcuserdata/ + +## Other +*.moved-aside +*.xccheckout +*.xcscmblueprint + +## Obj-C/Swift specific +*.hmap +*.ipa +*.dSYM.zip +*.dSYM + +## Playgrounds +timeline.xctimeline +playground.xcworkspace + +# Swift Package Manager +# +# Add this line if you want to avoid checking in source code from Swift Package Manager dependencies. +# Packages/ +# Package.pins +# Package.resolved +.build/ + +# CocoaPods +# +# We recommend against adding the Pods directory to your .gitignore. However +# you should judge for yourself, the pros and cons are mentioned at: +# https://guides.cocoapods.org/using/using-cocoapods.html#should-i-check-the-pods-directory-into-source-control +# +# Pods/ +# +# Add this line if you want to avoid checking in source code from the Xcode workspace +# *.xcworkspace + +# Carthage +# +# Add this line if you want to avoid checking in source code from Carthage dependencies. +# Carthage/Checkouts + +Carthage/Build + +# fastlane +# +# It is recommended to not store the screenshots in the git repo. Instead, use fastlane to re-generate the +# screenshots whenever they are needed. +# For more information about the recommended setup visit: +# https://docs.fastlane.tools/best-practices/source-control/#source-control + +fastlane/report.xml +fastlane/Preview.html +fastlane/screenshots/**/*.png +fastlane/test_output + +# Code Injection +# +# After new code Injection tools there's a generated folder /iOSInjectionProject +# https://github.com/johnno1962/injectionforxcode + +iOSInjectionProject/ diff --git a/.ruby-version b/.ruby-version new file mode 100644 index 0000000..73462a5 --- /dev/null +++ b/.ruby-version @@ -0,0 +1 @@ +2.5.1 diff --git a/.swift-version b/.swift-version new file mode 100644 index 0000000..bf77d54 --- /dev/null +++ b/.swift-version @@ -0,0 +1 @@ +4.2 diff --git a/.swiftlint.yml b/.swiftlint.yml new file mode 100644 index 0000000..8a20a33 --- /dev/null +++ b/.swiftlint.yml @@ -0,0 +1,48 @@ +disabled_rules: # rule identifiers to exclude from running + - colon + - comma + - control_statement +opt_in_rules: # some rules are only opt-in + - empty_count + # Find all the available rules by running: + # swiftlint rules +included: # paths to include during linting. `--path` is ignored if present. + - GiphySearch +excluded: # paths to ignore during linting. Takes precedence over `included`. + - Carthage + - Pods +analyzer_rules: # Rules run by `swiftlint analyze` (experimental) + - explicit_self + +# configurable rules can be customized from this configuration file +# binary rules can set their severity level +force_cast: warning # implicitly +force_try: + severity: warning # explicitly +# rules that have both warning and error levels, can set just the warning level +# implicitly +line_length: 110 +# they can set both implicitly with an array +type_body_length: + - 300 # warning + - 400 # error +# or they can set both explicitly +file_length: + warning: 500 + error: 1200 +# naming rules can set warnings/errors for min_length and max_length +# additionally they can set excluded names +type_name: + min_length: 4 # only warning + max_length: # warning and error + warning: 40 + error: 50 + excluded: iPhone # excluded via string +identifier_name: + min_length: # only min_length + error: 4 # only error + excluded: # excluded via string array + - id + - URL + - GlobalAPIKey +reporter: "xcode" # reporter type (xcode, json, csv, checkstyle, junit, html, emoji, sonarqube) \ No newline at end of file diff --git a/.travis.yml b/.travis.yml new file mode 100644 index 0000000..d7814d3 --- /dev/null +++ b/.travis.yml @@ -0,0 +1,10 @@ +---- + +os: osx +osx_image: xcode10 +language: swift +script: + - set -o pipefail + - xcodebuild clean build test -project GiphySearch.xcodeproj\ + -scheme "Giphy Search" CODE_SIGN_IDENTITY="" CODE_SIGNING_REQUIRED=NO\ + -sdk iphonesimulator -destination "OS=12.0,name=iPhone XR" diff --git a/Gemfile b/Gemfile new file mode 100644 index 0000000..befc103 --- /dev/null +++ b/Gemfile @@ -0,0 +1,9 @@ +ruby "2.5.1" + +# frozen_string_literal: true + +source "https://rubygems.org" + +git_source(:github) {|repo_name| "https://github.com/#{repo_name}" } + +gem "cocoapods" diff --git a/Gemfile.lock b/Gemfile.lock new file mode 100644 index 0000000..964e8a8 --- /dev/null +++ b/Gemfile.lock @@ -0,0 +1,79 @@ +GEM + remote: https://rubygems.org/ + specs: + CFPropertyList (3.0.0) + activesupport (4.2.10) + i18n (~> 0.7) + minitest (~> 5.1) + thread_safe (~> 0.3, >= 0.3.4) + tzinfo (~> 1.1) + atomos (0.1.3) + claide (1.0.2) + cocoapods (1.5.3) + activesupport (>= 4.0.2, < 5) + claide (>= 1.0.2, < 2.0) + cocoapods-core (= 1.5.3) + cocoapods-deintegrate (>= 1.0.2, < 2.0) + cocoapods-downloader (>= 1.2.0, < 2.0) + cocoapods-plugins (>= 1.0.0, < 2.0) + cocoapods-search (>= 1.0.0, < 2.0) + cocoapods-stats (>= 1.0.0, < 2.0) + cocoapods-trunk (>= 1.3.0, < 2.0) + cocoapods-try (>= 1.1.0, < 2.0) + colored2 (~> 3.1) + escape (~> 0.0.4) + fourflusher (~> 2.0.1) + gh_inspector (~> 1.0) + molinillo (~> 0.6.5) + nap (~> 1.0) + ruby-macho (~> 1.1) + xcodeproj (>= 1.5.7, < 2.0) + cocoapods-core (1.5.3) + activesupport (>= 4.0.2, < 6) + fuzzy_match (~> 2.0.4) + nap (~> 1.0) + cocoapods-deintegrate (1.0.2) + cocoapods-downloader (1.2.1) + cocoapods-plugins (1.0.0) + nap + cocoapods-search (1.0.0) + cocoapods-stats (1.0.0) + cocoapods-trunk (1.3.1) + nap (>= 0.8, < 2.0) + netrc (~> 0.11) + cocoapods-try (1.1.0) + colored2 (3.1.2) + concurrent-ruby (1.0.5) + escape (0.0.4) + fourflusher (2.0.1) + fuzzy_match (2.0.4) + gh_inspector (1.1.3) + i18n (0.9.5) + concurrent-ruby (~> 1.0) + minitest (5.11.3) + molinillo (0.6.6) + nanaimo (0.2.6) + nap (1.1.0) + netrc (0.11.0) + ruby-macho (1.2.0) + thread_safe (0.3.6) + tzinfo (1.2.5) + thread_safe (~> 0.1) + xcodeproj (1.6.0) + CFPropertyList (>= 2.3.3, < 4.0) + atomos (~> 0.1.3) + claide (>= 1.0.2, < 2.0) + colored2 (~> 3.1) + nanaimo (~> 0.2.6) + +PLATFORMS + ruby + +DEPENDENCIES + cocoapods + +RUBY VERSION + ruby 2.5.1p57 + +BUNDLED WITH + 1.16.1 diff --git a/GiphySearch.xcodeproj/project.pbxproj b/GiphySearch.xcodeproj/project.pbxproj new file mode 100644 index 0000000..2823a21 --- /dev/null +++ b/GiphySearch.xcodeproj/project.pbxproj @@ -0,0 +1,428 @@ +// !$*UTF8*$! +{ + archiveVersion = 1; + classes = { + }; + objectVersion = 50; + objects = { + +/* Begin PBXBuildFile section */ + 48A839EFFA224998E09C4246 /* Pods_GiphySearch.framework in Frameworks */ = {isa = PBXBuildFile; fileRef = 8C867B2F7F4FB39C63747342 /* Pods_GiphySearch.framework */; }; + 8E5441B980EEBFE4BB9482F5 /* Pods_Giphy_Search.framework in Frameworks */ = {isa = PBXBuildFile; fileRef = A65653AFE74452A6667F9AA6 /* Pods_Giphy_Search.framework */; }; + 964050A8215D2BAD00AF47B0 /* AppDelegate.swift in Sources */ = {isa = PBXBuildFile; fileRef = 964050A7215D2BAD00AF47B0 /* AppDelegate.swift */; }; + 964050AA215D2BAD00AF47B0 /* ViewController.swift in Sources */ = {isa = PBXBuildFile; fileRef = 964050A9215D2BAD00AF47B0 /* ViewController.swift */; }; + 964050AD215D2BAD00AF47B0 /* Main.storyboard in Resources */ = {isa = PBXBuildFile; fileRef = 964050AB215D2BAD00AF47B0 /* Main.storyboard */; }; + 964050AF215D2BAE00AF47B0 /* Assets.xcassets in Resources */ = {isa = PBXBuildFile; fileRef = 964050AE215D2BAE00AF47B0 /* Assets.xcassets */; }; + 964050B2215D2BAE00AF47B0 /* LaunchScreen.storyboard in Resources */ = {isa = PBXBuildFile; fileRef = 964050B0215D2BAE00AF47B0 /* LaunchScreen.storyboard */; }; +/* End PBXBuildFile section */ + +/* Begin PBXFileReference section */ + 3634E82DA0239BE12D914F0B /* Pods-Giphy Search.release.xcconfig */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = text.xcconfig; name = "Pods-Giphy Search.release.xcconfig"; path = "Pods/Target Support Files/Pods-Giphy Search/Pods-Giphy Search.release.xcconfig"; sourceTree = ""; }; + 8C867B2F7F4FB39C63747342 /* Pods_GiphySearch.framework */ = {isa = PBXFileReference; explicitFileType = wrapper.framework; includeInIndex = 0; path = Pods_GiphySearch.framework; sourceTree = BUILT_PRODUCTS_DIR; }; + 964050A4215D2BAD00AF47B0 /* Giphy Search.app */ = {isa = PBXFileReference; explicitFileType = wrapper.application; includeInIndex = 0; path = "Giphy Search.app"; sourceTree = BUILT_PRODUCTS_DIR; }; + 964050A7215D2BAD00AF47B0 /* AppDelegate.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = AppDelegate.swift; sourceTree = ""; }; + 964050A9215D2BAD00AF47B0 /* ViewController.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = ViewController.swift; sourceTree = ""; }; + 964050AC215D2BAD00AF47B0 /* Base */ = {isa = PBXFileReference; lastKnownFileType = file.storyboard; name = Base; path = Base.lproj/Main.storyboard; sourceTree = ""; }; + 964050AE215D2BAE00AF47B0 /* Assets.xcassets */ = {isa = PBXFileReference; lastKnownFileType = folder.assetcatalog; path = Assets.xcassets; sourceTree = ""; }; + 964050B1215D2BAE00AF47B0 /* Base */ = {isa = PBXFileReference; lastKnownFileType = file.storyboard; name = Base; path = Base.lproj/LaunchScreen.storyboard; sourceTree = ""; }; + 964050B3215D2BAE00AF47B0 /* Info.plist */ = {isa = PBXFileReference; lastKnownFileType = text.plist.xml; path = Info.plist; sourceTree = ""; }; + A65653AFE74452A6667F9AA6 /* Pods_Giphy_Search.framework */ = {isa = PBXFileReference; explicitFileType = wrapper.framework; includeInIndex = 0; path = Pods_Giphy_Search.framework; sourceTree = BUILT_PRODUCTS_DIR; }; + B55654F7C3CEB29C1893A3D5 /* Pods-GiphySearch.release.xcconfig */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = text.xcconfig; name = "Pods-GiphySearch.release.xcconfig"; path = "Pods/Target Support Files/Pods-GiphySearch/Pods-GiphySearch.release.xcconfig"; sourceTree = ""; }; + B8CC3DB9773B29F207841D4F /* Pods-GiphySearch.debug.xcconfig */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = text.xcconfig; name = "Pods-GiphySearch.debug.xcconfig"; path = "Pods/Target Support Files/Pods-GiphySearch/Pods-GiphySearch.debug.xcconfig"; sourceTree = ""; }; + BE312496A4447CF8A0C3FE99 /* Pods-Giphy Search.debug.xcconfig */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = text.xcconfig; name = "Pods-Giphy Search.debug.xcconfig"; path = "Pods/Target Support Files/Pods-Giphy Search/Pods-Giphy Search.debug.xcconfig"; sourceTree = ""; }; +/* End PBXFileReference section */ + +/* Begin PBXFrameworksBuildPhase section */ + 964050A1215D2BAD00AF47B0 /* Frameworks */ = { + isa = PBXFrameworksBuildPhase; + buildActionMask = 2147483647; + files = ( + 48A839EFFA224998E09C4246 /* Pods_GiphySearch.framework in Frameworks */, + 8E5441B980EEBFE4BB9482F5 /* Pods_Giphy_Search.framework in Frameworks */, + ); + runOnlyForDeploymentPostprocessing = 0; + }; +/* End PBXFrameworksBuildPhase section */ + +/* Begin PBXGroup section */ + 316034ACAC5053BA35F48662 /* Frameworks */ = { + isa = PBXGroup; + children = ( + 8C867B2F7F4FB39C63747342 /* Pods_GiphySearch.framework */, + A65653AFE74452A6667F9AA6 /* Pods_Giphy_Search.framework */, + ); + name = Frameworks; + sourceTree = ""; + }; + 8D1D30EC3078FA125BB5F058 /* Pods */ = { + isa = PBXGroup; + children = ( + B8CC3DB9773B29F207841D4F /* Pods-GiphySearch.debug.xcconfig */, + B55654F7C3CEB29C1893A3D5 /* Pods-GiphySearch.release.xcconfig */, + BE312496A4447CF8A0C3FE99 /* Pods-Giphy Search.debug.xcconfig */, + 3634E82DA0239BE12D914F0B /* Pods-Giphy Search.release.xcconfig */, + ); + name = Pods; + sourceTree = ""; + }; + 9640509B215D2BAD00AF47B0 = { + isa = PBXGroup; + children = ( + 964050A6215D2BAD00AF47B0 /* GiphySearch */, + 964050A5215D2BAD00AF47B0 /* Products */, + 8D1D30EC3078FA125BB5F058 /* Pods */, + 316034ACAC5053BA35F48662 /* Frameworks */, + ); + sourceTree = ""; + }; + 964050A5215D2BAD00AF47B0 /* Products */ = { + isa = PBXGroup; + children = ( + 964050A4215D2BAD00AF47B0 /* Giphy Search.app */, + ); + name = Products; + sourceTree = ""; + }; + 964050A6215D2BAD00AF47B0 /* GiphySearch */ = { + isa = PBXGroup; + children = ( + 964050A7215D2BAD00AF47B0 /* AppDelegate.swift */, + 964050A9215D2BAD00AF47B0 /* ViewController.swift */, + 964050AB215D2BAD00AF47B0 /* Main.storyboard */, + 964050AE215D2BAE00AF47B0 /* Assets.xcassets */, + 964050B0215D2BAE00AF47B0 /* LaunchScreen.storyboard */, + 964050B3215D2BAE00AF47B0 /* Info.plist */, + ); + path = GiphySearch; + sourceTree = ""; + }; +/* End PBXGroup section */ + +/* Begin PBXNativeTarget section */ + 964050A3215D2BAD00AF47B0 /* Giphy Search */ = { + isa = PBXNativeTarget; + buildConfigurationList = 964050B6215D2BAE00AF47B0 /* Build configuration list for PBXNativeTarget "Giphy Search" */; + buildPhases = ( + C826924F8AB52A7863847636 /* [CP] Check Pods Manifest.lock */, + 964050A0215D2BAD00AF47B0 /* Sources */, + 964050A1215D2BAD00AF47B0 /* Frameworks */, + 964050A2215D2BAD00AF47B0 /* Resources */, + 47E873276B8075ED666D7882 /* [CP] Embed Pods Frameworks */, + ); + buildRules = ( + ); + dependencies = ( + ); + name = "Giphy Search"; + productName = GiphySearch; + productReference = 964050A4215D2BAD00AF47B0 /* Giphy Search.app */; + productType = "com.apple.product-type.application"; + }; +/* End PBXNativeTarget section */ + +/* Begin PBXProject section */ + 9640509C215D2BAD00AF47B0 /* Project object */ = { + isa = PBXProject; + attributes = { + LastSwiftUpdateCheck = 1000; + LastUpgradeCheck = 1000; + ORGANIZATIONNAME = yurikoles; + TargetAttributes = { + 964050A3215D2BAD00AF47B0 = { + CreatedOnToolsVersion = 10.0; + }; + }; + }; + buildConfigurationList = 9640509F215D2BAD00AF47B0 /* Build configuration list for PBXProject "GiphySearch" */; + compatibilityVersion = "Xcode 9.3"; + developmentRegion = en; + hasScannedForEncodings = 0; + knownRegions = ( + en, + Base, + ); + mainGroup = 9640509B215D2BAD00AF47B0; + productRefGroup = 964050A5215D2BAD00AF47B0 /* Products */; + projectDirPath = ""; + projectRoot = ""; + targets = ( + 964050A3215D2BAD00AF47B0 /* Giphy Search */, + ); + }; +/* End PBXProject section */ + +/* Begin PBXResourcesBuildPhase section */ + 964050A2215D2BAD00AF47B0 /* Resources */ = { + isa = PBXResourcesBuildPhase; + buildActionMask = 2147483647; + files = ( + 964050B2215D2BAE00AF47B0 /* LaunchScreen.storyboard in Resources */, + 964050AF215D2BAE00AF47B0 /* Assets.xcassets in Resources */, + 964050AD215D2BAD00AF47B0 /* Main.storyboard in Resources */, + ); + runOnlyForDeploymentPostprocessing = 0; + }; +/* End PBXResourcesBuildPhase section */ + +/* Begin PBXShellScriptBuildPhase section */ + 47E873276B8075ED666D7882 /* [CP] Embed Pods Frameworks */ = { + isa = PBXShellScriptBuildPhase; + buildActionMask = 2147483647; + files = ( + ); + inputFileListPaths = ( + ); + inputPaths = ( + "${SRCROOT}/Pods/Target Support Files/Pods-Giphy Search/Pods-Giphy Search-frameworks.sh", + "${BUILT_PRODUCTS_DIR}/Alamofire/Alamofire.framework", + "${BUILT_PRODUCTS_DIR}/AlamofireImage/AlamofireImage.framework", + "${BUILT_PRODUCTS_DIR}/GiphyCoreSDK/GiphyCoreSDK.framework", + ); + name = "[CP] Embed Pods Frameworks"; + outputFileListPaths = ( + ); + outputPaths = ( + "${TARGET_BUILD_DIR}/${FRAMEWORKS_FOLDER_PATH}/Alamofire.framework", + "${TARGET_BUILD_DIR}/${FRAMEWORKS_FOLDER_PATH}/AlamofireImage.framework", + "${TARGET_BUILD_DIR}/${FRAMEWORKS_FOLDER_PATH}/GiphyCoreSDK.framework", + ); + runOnlyForDeploymentPostprocessing = 0; + shellPath = /bin/sh; + shellScript = "\"${SRCROOT}/Pods/Target Support Files/Pods-Giphy Search/Pods-Giphy Search-frameworks.sh\"\n"; + showEnvVarsInLog = 0; + }; + C826924F8AB52A7863847636 /* [CP] Check Pods Manifest.lock */ = { + isa = PBXShellScriptBuildPhase; + buildActionMask = 2147483647; + files = ( + ); + inputFileListPaths = ( + ); + inputPaths = ( + "${PODS_PODFILE_DIR_PATH}/Podfile.lock", + "${PODS_ROOT}/Manifest.lock", + ); + name = "[CP] Check Pods Manifest.lock"; + outputFileListPaths = ( + ); + outputPaths = ( + "$(DERIVED_FILE_DIR)/Pods-Giphy Search-checkManifestLockResult.txt", + ); + runOnlyForDeploymentPostprocessing = 0; + shellPath = /bin/sh; + shellScript = "diff \"${PODS_PODFILE_DIR_PATH}/Podfile.lock\" \"${PODS_ROOT}/Manifest.lock\" > /dev/null\nif [ $? != 0 ] ; then\n # print error to STDERR\n echo \"error: The sandbox is not in sync with the Podfile.lock. Run 'pod install' or update your CocoaPods installation.\" >&2\n exit 1\nfi\n# This output is used by Xcode 'outputs' to avoid re-running this script phase.\necho \"SUCCESS\" > \"${SCRIPT_OUTPUT_FILE_0}\"\n"; + showEnvVarsInLog = 0; + }; +/* End PBXShellScriptBuildPhase section */ + +/* Begin PBXSourcesBuildPhase section */ + 964050A0215D2BAD00AF47B0 /* Sources */ = { + isa = PBXSourcesBuildPhase; + buildActionMask = 2147483647; + files = ( + 964050AA215D2BAD00AF47B0 /* ViewController.swift in Sources */, + 964050A8215D2BAD00AF47B0 /* AppDelegate.swift in Sources */, + ); + runOnlyForDeploymentPostprocessing = 0; + }; +/* End PBXSourcesBuildPhase section */ + +/* Begin PBXVariantGroup section */ + 964050AB215D2BAD00AF47B0 /* Main.storyboard */ = { + isa = PBXVariantGroup; + children = ( + 964050AC215D2BAD00AF47B0 /* Base */, + ); + name = Main.storyboard; + sourceTree = ""; + }; + 964050B0215D2BAE00AF47B0 /* LaunchScreen.storyboard */ = { + isa = PBXVariantGroup; + children = ( + 964050B1215D2BAE00AF47B0 /* Base */, + ); + name = LaunchScreen.storyboard; + sourceTree = ""; + }; +/* End PBXVariantGroup section */ + +/* Begin XCBuildConfiguration section */ + 964050B4215D2BAE00AF47B0 /* Debug */ = { + isa = XCBuildConfiguration; + buildSettings = { + ALWAYS_SEARCH_USER_PATHS = NO; + CLANG_ANALYZER_NONNULL = YES; + CLANG_ANALYZER_NUMBER_OBJECT_CONVERSION = YES_AGGRESSIVE; + CLANG_CXX_LANGUAGE_STANDARD = "gnu++14"; + CLANG_CXX_LIBRARY = "libc++"; + CLANG_ENABLE_MODULES = YES; + CLANG_ENABLE_OBJC_ARC = YES; + CLANG_ENABLE_OBJC_WEAK = YES; + CLANG_WARN_BLOCK_CAPTURE_AUTORELEASING = YES; + CLANG_WARN_BOOL_CONVERSION = YES; + CLANG_WARN_COMMA = YES; + CLANG_WARN_CONSTANT_CONVERSION = YES; + CLANG_WARN_DEPRECATED_OBJC_IMPLEMENTATIONS = YES; + CLANG_WARN_DIRECT_OBJC_ISA_USAGE = YES_ERROR; + CLANG_WARN_DOCUMENTATION_COMMENTS = YES; + CLANG_WARN_EMPTY_BODY = YES; + CLANG_WARN_ENUM_CONVERSION = YES; + CLANG_WARN_INFINITE_RECURSION = YES; + CLANG_WARN_INT_CONVERSION = YES; + CLANG_WARN_NON_LITERAL_NULL_CONVERSION = YES; + CLANG_WARN_OBJC_IMPLICIT_RETAIN_SELF = YES; + CLANG_WARN_OBJC_LITERAL_CONVERSION = YES; + CLANG_WARN_OBJC_ROOT_CLASS = YES_ERROR; + CLANG_WARN_RANGE_LOOP_ANALYSIS = YES; + CLANG_WARN_STRICT_PROTOTYPES = YES; + CLANG_WARN_SUSPICIOUS_MOVE = YES; + CLANG_WARN_UNGUARDED_AVAILABILITY = YES_AGGRESSIVE; + CLANG_WARN_UNREACHABLE_CODE = YES; + CLANG_WARN__DUPLICATE_METHOD_MATCH = YES; + CODE_SIGN_IDENTITY = "iPhone Developer"; + COPY_PHASE_STRIP = NO; + DEBUG_INFORMATION_FORMAT = dwarf; + ENABLE_STRICT_OBJC_MSGSEND = YES; + ENABLE_TESTABILITY = YES; + GCC_C_LANGUAGE_STANDARD = gnu11; + GCC_DYNAMIC_NO_PIC = NO; + GCC_NO_COMMON_BLOCKS = YES; + GCC_OPTIMIZATION_LEVEL = 0; + GCC_PREPROCESSOR_DEFINITIONS = ( + "DEBUG=1", + "$(inherited)", + ); + GCC_WARN_64_TO_32_BIT_CONVERSION = YES; + GCC_WARN_ABOUT_RETURN_TYPE = YES_ERROR; + GCC_WARN_UNDECLARED_SELECTOR = YES; + GCC_WARN_UNINITIALIZED_AUTOS = YES_AGGRESSIVE; + GCC_WARN_UNUSED_FUNCTION = YES; + GCC_WARN_UNUSED_VARIABLE = YES; + IPHONEOS_DEPLOYMENT_TARGET = 12.0; + MTL_ENABLE_DEBUG_INFO = INCLUDE_SOURCE; + MTL_FAST_MATH = YES; + ONLY_ACTIVE_ARCH = YES; + SDKROOT = iphoneos; + SWIFT_ACTIVE_COMPILATION_CONDITIONS = DEBUG; + SWIFT_OPTIMIZATION_LEVEL = "-Onone"; + }; + name = Debug; + }; + 964050B5215D2BAE00AF47B0 /* Release */ = { + isa = XCBuildConfiguration; + buildSettings = { + ALWAYS_SEARCH_USER_PATHS = NO; + CLANG_ANALYZER_NONNULL = YES; + CLANG_ANALYZER_NUMBER_OBJECT_CONVERSION = YES_AGGRESSIVE; + CLANG_CXX_LANGUAGE_STANDARD = "gnu++14"; + CLANG_CXX_LIBRARY = "libc++"; + CLANG_ENABLE_MODULES = YES; + CLANG_ENABLE_OBJC_ARC = YES; + CLANG_ENABLE_OBJC_WEAK = YES; + CLANG_WARN_BLOCK_CAPTURE_AUTORELEASING = YES; + CLANG_WARN_BOOL_CONVERSION = YES; + CLANG_WARN_COMMA = YES; + CLANG_WARN_CONSTANT_CONVERSION = YES; + CLANG_WARN_DEPRECATED_OBJC_IMPLEMENTATIONS = YES; + CLANG_WARN_DIRECT_OBJC_ISA_USAGE = YES_ERROR; + CLANG_WARN_DOCUMENTATION_COMMENTS = YES; + CLANG_WARN_EMPTY_BODY = YES; + CLANG_WARN_ENUM_CONVERSION = YES; + CLANG_WARN_INFINITE_RECURSION = YES; + CLANG_WARN_INT_CONVERSION = YES; + CLANG_WARN_NON_LITERAL_NULL_CONVERSION = YES; + CLANG_WARN_OBJC_IMPLICIT_RETAIN_SELF = YES; + CLANG_WARN_OBJC_LITERAL_CONVERSION = YES; + CLANG_WARN_OBJC_ROOT_CLASS = YES_ERROR; + CLANG_WARN_RANGE_LOOP_ANALYSIS = YES; + CLANG_WARN_STRICT_PROTOTYPES = YES; + CLANG_WARN_SUSPICIOUS_MOVE = YES; + CLANG_WARN_UNGUARDED_AVAILABILITY = YES_AGGRESSIVE; + CLANG_WARN_UNREACHABLE_CODE = YES; + CLANG_WARN__DUPLICATE_METHOD_MATCH = YES; + CODE_SIGN_IDENTITY = "iPhone Developer"; + COPY_PHASE_STRIP = NO; + DEBUG_INFORMATION_FORMAT = "dwarf-with-dsym"; + ENABLE_NS_ASSERTIONS = NO; + ENABLE_STRICT_OBJC_MSGSEND = YES; + GCC_C_LANGUAGE_STANDARD = gnu11; + GCC_NO_COMMON_BLOCKS = YES; + GCC_WARN_64_TO_32_BIT_CONVERSION = YES; + GCC_WARN_ABOUT_RETURN_TYPE = YES_ERROR; + GCC_WARN_UNDECLARED_SELECTOR = YES; + GCC_WARN_UNINITIALIZED_AUTOS = YES_AGGRESSIVE; + GCC_WARN_UNUSED_FUNCTION = YES; + GCC_WARN_UNUSED_VARIABLE = YES; + IPHONEOS_DEPLOYMENT_TARGET = 12.0; + MTL_ENABLE_DEBUG_INFO = NO; + MTL_FAST_MATH = YES; + SDKROOT = iphoneos; + SWIFT_COMPILATION_MODE = wholemodule; + SWIFT_OPTIMIZATION_LEVEL = "-O"; + VALIDATE_PRODUCT = YES; + }; + name = Release; + }; + 964050B7215D2BAE00AF47B0 /* Debug */ = { + isa = XCBuildConfiguration; + baseConfigurationReference = BE312496A4447CF8A0C3FE99 /* Pods-Giphy Search.debug.xcconfig */; + buildSettings = { + ASSETCATALOG_COMPILER_APPICON_NAME = AppIcon; + CODE_SIGN_STYLE = Automatic; + DEVELOPMENT_TEAM = 3YQZ33LKM8; + INFOPLIST_FILE = GiphySearch/Info.plist; + LD_RUNPATH_SEARCH_PATHS = ( + "$(inherited)", + "@executable_path/Frameworks", + ); + PRODUCT_BUNDLE_IDENTIFIER = com.yurikoles.GiphySearch; + PRODUCT_NAME = "$(TARGET_NAME)"; + SWIFT_VERSION = 4.2; + TARGETED_DEVICE_FAMILY = "1,2"; + }; + name = Debug; + }; + 964050B8215D2BAE00AF47B0 /* Release */ = { + isa = XCBuildConfiguration; + baseConfigurationReference = 3634E82DA0239BE12D914F0B /* Pods-Giphy Search.release.xcconfig */; + buildSettings = { + ASSETCATALOG_COMPILER_APPICON_NAME = AppIcon; + CODE_SIGN_STYLE = Automatic; + DEVELOPMENT_TEAM = 3YQZ33LKM8; + INFOPLIST_FILE = GiphySearch/Info.plist; + LD_RUNPATH_SEARCH_PATHS = ( + "$(inherited)", + "@executable_path/Frameworks", + ); + PRODUCT_BUNDLE_IDENTIFIER = com.yurikoles.GiphySearch; + PRODUCT_NAME = "$(TARGET_NAME)"; + SWIFT_VERSION = 4.2; + TARGETED_DEVICE_FAMILY = "1,2"; + }; + name = Release; + }; +/* End XCBuildConfiguration section */ + +/* Begin XCConfigurationList section */ + 9640509F215D2BAD00AF47B0 /* Build configuration list for PBXProject "GiphySearch" */ = { + isa = XCConfigurationList; + buildConfigurations = ( + 964050B4215D2BAE00AF47B0 /* Debug */, + 964050B5215D2BAE00AF47B0 /* Release */, + ); + defaultConfigurationIsVisible = 0; + defaultConfigurationName = Release; + }; + 964050B6215D2BAE00AF47B0 /* Build configuration list for PBXNativeTarget "Giphy Search" */ = { + isa = XCConfigurationList; + buildConfigurations = ( + 964050B7215D2BAE00AF47B0 /* Debug */, + 964050B8215D2BAE00AF47B0 /* Release */, + ); + defaultConfigurationIsVisible = 0; + defaultConfigurationName = Release; + }; +/* End XCConfigurationList section */ + }; + rootObject = 9640509C215D2BAD00AF47B0 /* Project object */; +} diff --git a/GiphySearch.xcodeproj/project.xcworkspace/contents.xcworkspacedata b/GiphySearch.xcodeproj/project.xcworkspace/contents.xcworkspacedata new file mode 100644 index 0000000..b2cece9 --- /dev/null +++ b/GiphySearch.xcodeproj/project.xcworkspace/contents.xcworkspacedata @@ -0,0 +1,7 @@ + + + + + diff --git a/GiphySearch.xcodeproj/project.xcworkspace/xcshareddata/IDEWorkspaceChecks.plist b/GiphySearch.xcodeproj/project.xcworkspace/xcshareddata/IDEWorkspaceChecks.plist new file mode 100644 index 0000000..18d9810 --- /dev/null +++ b/GiphySearch.xcodeproj/project.xcworkspace/xcshareddata/IDEWorkspaceChecks.plist @@ -0,0 +1,8 @@ + + + + + IDEDidComputeMac32BitWarning + + + diff --git a/GiphySearch.xcodeproj/xcshareddata/xcschemes/Giphy Search.xcscheme b/GiphySearch.xcodeproj/xcshareddata/xcschemes/Giphy Search.xcscheme new file mode 100644 index 0000000..91eeae9 --- /dev/null +++ b/GiphySearch.xcodeproj/xcshareddata/xcschemes/Giphy Search.xcscheme @@ -0,0 +1,91 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/GiphySearch.xcworkspace/contents.xcworkspacedata b/GiphySearch.xcworkspace/contents.xcworkspacedata new file mode 100644 index 0000000..58385e2 --- /dev/null +++ b/GiphySearch.xcworkspace/contents.xcworkspacedata @@ -0,0 +1,10 @@ + + + + + + + diff --git a/GiphySearch.xcworkspace/xcshareddata/IDEWorkspaceChecks.plist b/GiphySearch.xcworkspace/xcshareddata/IDEWorkspaceChecks.plist new file mode 100644 index 0000000..18d9810 --- /dev/null +++ b/GiphySearch.xcworkspace/xcshareddata/IDEWorkspaceChecks.plist @@ -0,0 +1,8 @@ + + + + + IDEDidComputeMac32BitWarning + + + diff --git a/GiphySearch/AppDelegate.swift b/GiphySearch/AppDelegate.swift new file mode 100644 index 0000000..a0fa5d7 --- /dev/null +++ b/GiphySearch/AppDelegate.swift @@ -0,0 +1,19 @@ +// +// AppDelegate.swift +// GiphySearch +// +// Created by Yurii Kolesnykov on 2018-09-27. +// Copyright © 2018 yurikoles. All rights reserved. +// + +import UIKit + +@UIApplicationMain +class AppDelegate: UIResponder, UIApplicationDelegate { + + var window: UIWindow? + + func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?) -> Bool { + return true + } +} diff --git a/GiphySearch/Assets.xcassets/AppIcon.appiconset/Contents.json b/GiphySearch/Assets.xcassets/AppIcon.appiconset/Contents.json new file mode 100644 index 0000000..d8db8d6 --- /dev/null +++ b/GiphySearch/Assets.xcassets/AppIcon.appiconset/Contents.json @@ -0,0 +1,98 @@ +{ + "images" : [ + { + "idiom" : "iphone", + "size" : "20x20", + "scale" : "2x" + }, + { + "idiom" : "iphone", + "size" : "20x20", + "scale" : "3x" + }, + { + "idiom" : "iphone", + "size" : "29x29", + "scale" : "2x" + }, + { + "idiom" : "iphone", + "size" : "29x29", + "scale" : "3x" + }, + { + "idiom" : "iphone", + "size" : "40x40", + "scale" : "2x" + }, + { + "idiom" : "iphone", + "size" : "40x40", + "scale" : "3x" + }, + { + "idiom" : "iphone", + "size" : "60x60", + "scale" : "2x" + }, + { + "idiom" : "iphone", + "size" : "60x60", + "scale" : "3x" + }, + { + "idiom" : "ipad", + "size" : "20x20", + "scale" : "1x" + }, + { + "idiom" : "ipad", + "size" : "20x20", + "scale" : "2x" + }, + { + "idiom" : "ipad", + "size" : "29x29", + "scale" : "1x" + }, + { + "idiom" : "ipad", + "size" : "29x29", + "scale" : "2x" + }, + { + "idiom" : "ipad", + "size" : "40x40", + "scale" : "1x" + }, + { + "idiom" : "ipad", + "size" : "40x40", + "scale" : "2x" + }, + { + "idiom" : "ipad", + "size" : "76x76", + "scale" : "1x" + }, + { + "idiom" : "ipad", + "size" : "76x76", + "scale" : "2x" + }, + { + "idiom" : "ipad", + "size" : "83.5x83.5", + "scale" : "2x" + }, + { + "idiom" : "ios-marketing", + "size" : "1024x1024", + "scale" : "1x" + } + ], + "info" : { + "version" : 1, + "author" : "xcode" + } +} \ No newline at end of file diff --git a/GiphySearch/Assets.xcassets/Contents.json b/GiphySearch/Assets.xcassets/Contents.json new file mode 100644 index 0000000..da4a164 --- /dev/null +++ b/GiphySearch/Assets.xcassets/Contents.json @@ -0,0 +1,6 @@ +{ + "info" : { + "version" : 1, + "author" : "xcode" + } +} \ No newline at end of file diff --git a/GiphySearch/Base.lproj/LaunchScreen.storyboard b/GiphySearch/Base.lproj/LaunchScreen.storyboard new file mode 100644 index 0000000..bfa3612 --- /dev/null +++ b/GiphySearch/Base.lproj/LaunchScreen.storyboard @@ -0,0 +1,25 @@ + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/GiphySearch/Base.lproj/Main.storyboard b/GiphySearch/Base.lproj/Main.storyboard new file mode 100644 index 0000000..f1bcf38 --- /dev/null +++ b/GiphySearch/Base.lproj/Main.storyboard @@ -0,0 +1,24 @@ + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/GiphySearch/Info.plist b/GiphySearch/Info.plist new file mode 100644 index 0000000..16be3b6 --- /dev/null +++ b/GiphySearch/Info.plist @@ -0,0 +1,45 @@ + + + + + CFBundleDevelopmentRegion + $(DEVELOPMENT_LANGUAGE) + CFBundleExecutable + $(EXECUTABLE_NAME) + CFBundleIdentifier + $(PRODUCT_BUNDLE_IDENTIFIER) + CFBundleInfoDictionaryVersion + 6.0 + CFBundleName + $(PRODUCT_NAME) + CFBundlePackageType + APPL + CFBundleShortVersionString + 1.0 + CFBundleVersion + 1 + LSRequiresIPhoneOS + + UILaunchStoryboardName + LaunchScreen + UIMainStoryboardFile + Main + UIRequiredDeviceCapabilities + + armv7 + + UISupportedInterfaceOrientations + + UIInterfaceOrientationPortrait + UIInterfaceOrientationLandscapeLeft + UIInterfaceOrientationLandscapeRight + + UISupportedInterfaceOrientations~ipad + + UIInterfaceOrientationPortrait + UIInterfaceOrientationPortraitUpsideDown + UIInterfaceOrientationLandscapeLeft + UIInterfaceOrientationLandscapeRight + + + diff --git a/GiphySearch/ViewController.swift b/GiphySearch/ViewController.swift new file mode 100644 index 0000000..8a7365f --- /dev/null +++ b/GiphySearch/ViewController.swift @@ -0,0 +1,18 @@ +// +// ViewController.swift +// GiphySearch +// +// Created by Yurii Kolesnykov on 2018-09-27. +// Copyright © 2018 yurikoles. All rights reserved. +// + +import UIKit + +class ViewController: UIViewController { + + override func viewDidLoad() { + super.viewDidLoad() + // Do any additional setup after loading the view, typically from a nib. + } + +} diff --git a/Podfile b/Podfile new file mode 100644 index 0000000..421564b --- /dev/null +++ b/Podfile @@ -0,0 +1,10 @@ +platform :ios, '11.0' +inhibit_all_warnings! + +target 'Giphy Search' do + use_frameworks! + + pod 'Alamofire' + pod 'AlamofireImage' + pod 'GiphyCoreSDK' +end diff --git a/Podfile.lock b/Podfile.lock new file mode 100644 index 0000000..f3d4d20 --- /dev/null +++ b/Podfile.lock @@ -0,0 +1,25 @@ +PODS: + - Alamofire (4.7.3) + - AlamofireImage (3.4.1): + - Alamofire (~> 4.7) + - GiphyCoreSDK (1.4.0) + +DEPENDENCIES: + - Alamofire + - AlamofireImage + - GiphyCoreSDK + +SPEC REPOS: + https://github.com/cocoapods/specs.git: + - Alamofire + - AlamofireImage + - GiphyCoreSDK + +SPEC CHECKSUMS: + Alamofire: c7287b6e5d7da964a70935e5db17046b7fde6568 + AlamofireImage: 78d67ccbb763d87ba44b21583d2153500a195630 + GiphyCoreSDK: 1fe401c5fc65f182e7aa8b7fb2c9005f2a523374 + +PODFILE CHECKSUM: de154add1f98ee8de3a656157ac9b567dfb60cea + +COCOAPODS: 1.5.3 diff --git a/Pods/Alamofire/LICENSE b/Pods/Alamofire/LICENSE new file mode 100644 index 0000000..2ec3cb1 --- /dev/null +++ b/Pods/Alamofire/LICENSE @@ -0,0 +1,19 @@ +Copyright (c) 2014-2018 Alamofire Software Foundation (http://alamofire.org/) + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in +all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN +THE SOFTWARE. diff --git a/Pods/Alamofire/README.md b/Pods/Alamofire/README.md new file mode 100644 index 0000000..0208252 --- /dev/null +++ b/Pods/Alamofire/README.md @@ -0,0 +1,242 @@ +![Alamofire: Elegant Networking in Swift](https://raw.githubusercontent.com/Alamofire/Alamofire/master/alamofire.png) + +[![Build Status](https://travis-ci.org/Alamofire/Alamofire.svg?branch=master)](https://travis-ci.org/Alamofire/Alamofire) +[![CocoaPods Compatible](https://img.shields.io/cocoapods/v/Alamofire.svg)](https://img.shields.io/cocoapods/v/Alamofire.svg) +[![Carthage Compatible](https://img.shields.io/badge/Carthage-compatible-4BC51D.svg?style=flat)](https://github.com/Carthage/Carthage) +[![Platform](https://img.shields.io/cocoapods/p/Alamofire.svg?style=flat)](https://alamofire.github.io/Alamofire) +[![Twitter](https://img.shields.io/badge/twitter-@AlamofireSF-blue.svg?style=flat)](https://twitter.com/AlamofireSF) +[![Gitter](https://badges.gitter.im/Alamofire/Alamofire.svg)](https://gitter.im/Alamofire/Alamofire?utm_source=badge&utm_medium=badge&utm_campaign=pr-badge) + +Alamofire is an HTTP networking library written in Swift. + +- [Features](#features) +- [Component Libraries](#component-libraries) +- [Requirements](#requirements) +- [Migration Guides](#migration-guides) +- [Communication](#communication) +- [Installation](#installation) +- [Usage](https://github.com/Alamofire/Alamofire/blob/master/Documentation/Usage.md) + - **Intro -** [Making a Request](https://github.com/Alamofire/Alamofire/blob/master/Documentation/Usage.md#making-a-request), [Response Handling](https://github.com/Alamofire/Alamofire/blob/master/Documentation/Usage.md#response-handling), [Response Validation](https://github.com/Alamofire/Alamofire/blob/master/Documentation/Usage.md#response-validation), [Response Caching](https://github.com/Alamofire/Alamofire/blob/master/Documentation/Usage.md#response-caching) + - **HTTP -** [HTTP Methods](https://github.com/Alamofire/Alamofire/blob/master/Documentation/Usage.md#http-methods), [Parameter Encoding](https://github.com/Alamofire/Alamofire/blob/master/Documentation/Usage.md#parameter-encoding), [HTTP Headers](https://github.com/Alamofire/Alamofire/blob/master/Documentation/Usage.md#http-headers), [Authentication](https://github.com/Alamofire/Alamofire/blob/master/Documentation/Usage.md#authentication) + - **Large Data -** [Downloading Data to a File](https://github.com/Alamofire/Alamofire/blob/master/Documentation/Usage.md#downloading-data-to-a-file), [Uploading Data to a Server](https://github.com/Alamofire/Alamofire/blob/master/Documentation/Usage.md#uploading-data-to-a-server) + - **Tools -** [Statistical Metrics](https://github.com/Alamofire/Alamofire/blob/master/Documentation/Usage.md#statistical-metrics), [cURL Command Output](https://github.com/Alamofire/Alamofire/blob/master/Documentation/Usage.md#curl-command-output) +- [Advanced Usage](https://github.com/Alamofire/Alamofire/blob/master/Documentation/AdvancedUsage.md) + - **URL Session -** [Session Manager](https://github.com/Alamofire/Alamofire/blob/master/Documentation/AdvancedUsage.md#session-manager), [Session Delegate](https://github.com/Alamofire/Alamofire/blob/master/Documentation/AdvancedUsage.md#session-delegate), [Request](https://github.com/Alamofire/Alamofire/blob/master/Documentation/AdvancedUsage.md#request) + - **Routing -** [Routing Requests](https://github.com/Alamofire/Alamofire/blob/master/Documentation/AdvancedUsage.md#routing-requests), [Adapting and Retrying Requests](https://github.com/Alamofire/Alamofire/blob/master/Documentation/AdvancedUsage.md#adapting-and-retrying-requests) + - **Model Objects -** [Custom Response Serialization](https://github.com/Alamofire/Alamofire/blob/master/Documentation/AdvancedUsage.md#custom-response-serialization) + - **Connection -** [Security](https://github.com/Alamofire/Alamofire/blob/master/Documentation/AdvancedUsage.md#security), [Network Reachability](https://github.com/Alamofire/Alamofire/blob/master/Documentation/AdvancedUsage.md#network-reachability) +- [Open Radars](#open-radars) +- [FAQ](#faq) +- [Credits](#credits) +- [Donations](#donations) +- [License](#license) + +## Features + +- [x] Chainable Request / Response Methods +- [x] URL / JSON / plist Parameter Encoding +- [x] Upload File / Data / Stream / MultipartFormData +- [x] Download File using Request or Resume Data +- [x] Authentication with URLCredential +- [x] HTTP Response Validation +- [x] Upload and Download Progress Closures with Progress +- [x] cURL Command Output +- [x] Dynamically Adapt and Retry Requests +- [x] TLS Certificate and Public Key Pinning +- [x] Network Reachability +- [x] Comprehensive Unit and Integration Test Coverage +- [x] [Complete Documentation](https://alamofire.github.io/Alamofire) + +## Component Libraries + +In order to keep Alamofire focused specifically on core networking implementations, additional component libraries have been created by the [Alamofire Software Foundation](https://github.com/Alamofire/Foundation) to bring additional functionality to the Alamofire ecosystem. + +- [AlamofireImage](https://github.com/Alamofire/AlamofireImage) - An image library including image response serializers, `UIImage` and `UIImageView` extensions, custom image filters, an auto-purging in-memory cache and a priority-based image downloading system. +- [AlamofireNetworkActivityIndicator](https://github.com/Alamofire/AlamofireNetworkActivityIndicator) - Controls the visibility of the network activity indicator on iOS using Alamofire. It contains configurable delay timers to help mitigate flicker and can support `URLSession` instances not managed by Alamofire. + +## Requirements + +- iOS 8.0+ / macOS 10.10+ / tvOS 9.0+ / watchOS 2.0+ +- Xcode 8.3+ +- Swift 3.1+ + +## Migration Guides + +- [Alamofire 4.0 Migration Guide](https://github.com/Alamofire/Alamofire/blob/master/Documentation/Alamofire%204.0%20Migration%20Guide.md) +- [Alamofire 3.0 Migration Guide](https://github.com/Alamofire/Alamofire/blob/master/Documentation/Alamofire%203.0%20Migration%20Guide.md) +- [Alamofire 2.0 Migration Guide](https://github.com/Alamofire/Alamofire/blob/master/Documentation/Alamofire%202.0%20Migration%20Guide.md) + +## Communication + +- If you **need help**, use [Stack Overflow](https://stackoverflow.com/questions/tagged/alamofire). (Tag 'alamofire') +- If you'd like to **ask a general question**, use [Stack Overflow](https://stackoverflow.com/questions/tagged/alamofire). +- If you **found a bug**, open an issue. +- If you **have a feature request**, open an issue. +- If you **want to contribute**, submit a pull request. + +## Installation + +### CocoaPods + +[CocoaPods](https://cocoapods.org) is a dependency manager for Cocoa projects. You can install it with the following command: + +```bash +$ gem install cocoapods +``` + +> CocoaPods 1.1+ is required to build Alamofire 4.0+. + +To integrate Alamofire into your Xcode project using CocoaPods, specify it in your `Podfile`: + +```ruby +source 'https://github.com/CocoaPods/Specs.git' +platform :ios, '10.0' +use_frameworks! + +target '' do + pod 'Alamofire', '~> 4.7' +end +``` + +Then, run the following command: + +```bash +$ pod install +``` + +### Carthage + +[Carthage](https://github.com/Carthage/Carthage) is a decentralized dependency manager that builds your dependencies and provides you with binary frameworks. + +You can install Carthage with [Homebrew](https://brew.sh/) using the following command: + +```bash +$ brew update +$ brew install carthage +``` + +To integrate Alamofire into your Xcode project using Carthage, specify it in your `Cartfile`: + +```ogdl +github "Alamofire/Alamofire" ~> 4.7 +``` + +Run `carthage update` to build the framework and drag the built `Alamofire.framework` into your Xcode project. + +### Swift Package Manager + +The [Swift Package Manager](https://swift.org/package-manager/) is a tool for automating the distribution of Swift code and is integrated into the `swift` compiler. It is in early development, but Alamofire does support its use on supported platforms. + +Once you have your Swift package set up, adding Alamofire as a dependency is as easy as adding it to the `dependencies` value of your `Package.swift`. + +#### Swift 3 + +```swift +dependencies: [ + .Package(url: "https://github.com/Alamofire/Alamofire.git", majorVersion: 4) +] +``` + +#### Swift 4 + +```swift +dependencies: [ + .package(url: "https://github.com/Alamofire/Alamofire.git", from: "4.0.0") +] +``` + +### Manually + +If you prefer not to use any of the aforementioned dependency managers, you can integrate Alamofire into your project manually. + +#### Embedded Framework + +- Open up Terminal, `cd` into your top-level project directory, and run the following command "if" your project is not initialized as a git repository: + + ```bash + $ git init + ``` + +- Add Alamofire as a git [submodule](https://git-scm.com/docs/git-submodule) by running the following command: + + ```bash + $ git submodule add https://github.com/Alamofire/Alamofire.git + ``` + +- Open the new `Alamofire` folder, and drag the `Alamofire.xcodeproj` into the Project Navigator of your application's Xcode project. + + > It should appear nested underneath your application's blue project icon. Whether it is above or below all the other Xcode groups does not matter. + +- Select the `Alamofire.xcodeproj` in the Project Navigator and verify the deployment target matches that of your application target. +- Next, select your application project in the Project Navigator (blue project icon) to navigate to the target configuration window and select the application target under the "Targets" heading in the sidebar. +- In the tab bar at the top of that window, open the "General" panel. +- Click on the `+` button under the "Embedded Binaries" section. +- You will see two different `Alamofire.xcodeproj` folders each with two different versions of the `Alamofire.framework` nested inside a `Products` folder. + + > It does not matter which `Products` folder you choose from, but it does matter whether you choose the top or bottom `Alamofire.framework`. + +- Select the top `Alamofire.framework` for iOS and the bottom one for OS X. + + > You can verify which one you selected by inspecting the build log for your project. The build target for `Alamofire` will be listed as either `Alamofire iOS`, `Alamofire macOS`, `Alamofire tvOS` or `Alamofire watchOS`. + +- And that's it! + + > The `Alamofire.framework` is automagically added as a target dependency, linked framework and embedded framework in a copy files build phase which is all you need to build on the simulator and a device. + +## Open Radars + +The following radars have some effect on the current implementation of Alamofire. + +- [`rdar://21349340`](http://www.openradar.me/radar?id=5517037090635776) - Compiler throwing warning due to toll-free bridging issue in test case +- `rdar://26870455` - Background URL Session Configurations do not work in the simulator +- `rdar://26849668` - Some URLProtocol APIs do not properly handle `URLRequest` +- [`rdar://36082113`](http://openradar.appspot.com/radar?id=4942308441063424) - `URLSessionTaskMetrics` failing to link on watchOS 3.0+ + +## Resolved Radars + +The following radars have been resolved over time after being filed against the Alamofire project. + +- [`rdar://26761490`](http://www.openradar.me/radar?id=5010235949318144) - Swift string interpolation causing memory leak with common usage (Resolved on 9/1/17 in Xcode 9 beta 6). + +## FAQ + +### What's the origin of the name Alamofire? + +Alamofire is named after the [Alamo Fire flower](https://aggie-horticulture.tamu.edu/wildseed/alamofire.html), a hybrid variant of the Bluebonnet, the official state flower of Texas. + +### What logic belongs in a Router vs. a Request Adapter? + +Simple, static data such as paths, parameters and common headers belong in the `Router`. Dynamic data such as an `Authorization` header whose value can changed based on an authentication system belongs in a `RequestAdapter`. + +The reason the dynamic data MUST be placed into the `RequestAdapter` is to support retry operations. When a `Request` is retried, the original request is not rebuilt meaning the `Router` will not be called again. The `RequestAdapter` is called again allowing the dynamic data to be updated on the original request before retrying the `Request`. + +## Credits + +Alamofire is owned and maintained by the [Alamofire Software Foundation](http://alamofire.org). You can follow them on Twitter at [@AlamofireSF](https://twitter.com/AlamofireSF) for project updates and releases. + +### Security Disclosure + +If you believe you have identified a security vulnerability with Alamofire, you should report it as soon as possible via email to security@alamofire.org. Please do not post it to a public issue tracker. + +## Donations + +The [ASF](https://github.com/Alamofire/Foundation#members) is looking to raise money to officially stay registered as a federal non-profit organization. +Registering will allow us members to gain some legal protections and also allow us to put donations to use, tax free. +Donating to the ASF will enable us to: + +- Pay our yearly legal fees to keep the non-profit in good status +- Pay for our mail servers to help us stay on top of all questions and security issues +- Potentially fund test servers to make it easier for us to test the edge cases +- Potentially fund developers to work on one of our projects full-time + +The community adoption of the ASF libraries has been amazing. +We are greatly humbled by your enthusiasm around the projects, and want to continue to do everything we can to move the needle forward. +With your continued support, the ASF will be able to improve its reach and also provide better legal safety for the core members. +If you use any of our libraries for work, see if your employers would be interested in donating. +Any amount you can donate today to help us reach our goal would be greatly appreciated. + +[![paypal](https://www.paypalobjects.com/en_US/i/btn/btn_donateCC_LG.gif)](https://www.paypal.com/cgi-bin/webscr?cmd=_s-xclick&hosted_button_id=W34WPEE74APJQ) + +## License + +Alamofire is released under the MIT license. [See LICENSE](https://github.com/Alamofire/Alamofire/blob/master/LICENSE) for details. diff --git a/Pods/Alamofire/Source/AFError.swift b/Pods/Alamofire/Source/AFError.swift new file mode 100644 index 0000000..8b90d84 --- /dev/null +++ b/Pods/Alamofire/Source/AFError.swift @@ -0,0 +1,460 @@ +// +// AFError.swift +// +// Copyright (c) 2014-2018 Alamofire Software Foundation (http://alamofire.org/) +// +// Permission is hereby granted, free of charge, to any person obtaining a copy +// of this software and associated documentation files (the "Software"), to deal +// in the Software without restriction, including without limitation the rights +// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +// copies of the Software, and to permit persons to whom the Software is +// furnished to do so, subject to the following conditions: +// +// The above copyright notice and this permission notice shall be included in +// all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN +// THE SOFTWARE. +// + +import Foundation + +/// `AFError` is the error type returned by Alamofire. It encompasses a few different types of errors, each with +/// their own associated reasons. +/// +/// - invalidURL: Returned when a `URLConvertible` type fails to create a valid `URL`. +/// - parameterEncodingFailed: Returned when a parameter encoding object throws an error during the encoding process. +/// - multipartEncodingFailed: Returned when some step in the multipart encoding process fails. +/// - responseValidationFailed: Returned when a `validate()` call fails. +/// - responseSerializationFailed: Returned when a response serializer encounters an error in the serialization process. +public enum AFError: Error { + /// The underlying reason the parameter encoding error occurred. + /// + /// - missingURL: The URL request did not have a URL to encode. + /// - jsonEncodingFailed: JSON serialization failed with an underlying system error during the + /// encoding process. + /// - propertyListEncodingFailed: Property list serialization failed with an underlying system error during + /// encoding process. + public enum ParameterEncodingFailureReason { + case missingURL + case jsonEncodingFailed(error: Error) + case propertyListEncodingFailed(error: Error) + } + + /// The underlying reason the multipart encoding error occurred. + /// + /// - bodyPartURLInvalid: The `fileURL` provided for reading an encodable body part isn't a + /// file URL. + /// - bodyPartFilenameInvalid: The filename of the `fileURL` provided has either an empty + /// `lastPathComponent` or `pathExtension. + /// - bodyPartFileNotReachable: The file at the `fileURL` provided was not reachable. + /// - bodyPartFileNotReachableWithError: Attempting to check the reachability of the `fileURL` provided threw + /// an error. + /// - bodyPartFileIsDirectory: The file at the `fileURL` provided is actually a directory. + /// - bodyPartFileSizeNotAvailable: The size of the file at the `fileURL` provided was not returned by + /// the system. + /// - bodyPartFileSizeQueryFailedWithError: The attempt to find the size of the file at the `fileURL` provided + /// threw an error. + /// - bodyPartInputStreamCreationFailed: An `InputStream` could not be created for the provided `fileURL`. + /// - outputStreamCreationFailed: An `OutputStream` could not be created when attempting to write the + /// encoded data to disk. + /// - outputStreamFileAlreadyExists: The encoded body data could not be writtent disk because a file + /// already exists at the provided `fileURL`. + /// - outputStreamURLInvalid: The `fileURL` provided for writing the encoded body data to disk is + /// not a file URL. + /// - outputStreamWriteFailed: The attempt to write the encoded body data to disk failed with an + /// underlying error. + /// - inputStreamReadFailed: The attempt to read an encoded body part `InputStream` failed with + /// underlying system error. + public enum MultipartEncodingFailureReason { + case bodyPartURLInvalid(url: URL) + case bodyPartFilenameInvalid(in: URL) + case bodyPartFileNotReachable(at: URL) + case bodyPartFileNotReachableWithError(atURL: URL, error: Error) + case bodyPartFileIsDirectory(at: URL) + case bodyPartFileSizeNotAvailable(at: URL) + case bodyPartFileSizeQueryFailedWithError(forURL: URL, error: Error) + case bodyPartInputStreamCreationFailed(for: URL) + + case outputStreamCreationFailed(for: URL) + case outputStreamFileAlreadyExists(at: URL) + case outputStreamURLInvalid(url: URL) + case outputStreamWriteFailed(error: Error) + + case inputStreamReadFailed(error: Error) + } + + /// The underlying reason the response validation error occurred. + /// + /// - dataFileNil: The data file containing the server response did not exist. + /// - dataFileReadFailed: The data file containing the server response could not be read. + /// - missingContentType: The response did not contain a `Content-Type` and the `acceptableContentTypes` + /// provided did not contain wildcard type. + /// - unacceptableContentType: The response `Content-Type` did not match any type in the provided + /// `acceptableContentTypes`. + /// - unacceptableStatusCode: The response status code was not acceptable. + public enum ResponseValidationFailureReason { + case dataFileNil + case dataFileReadFailed(at: URL) + case missingContentType(acceptableContentTypes: [String]) + case unacceptableContentType(acceptableContentTypes: [String], responseContentType: String) + case unacceptableStatusCode(code: Int) + } + + /// The underlying reason the response serialization error occurred. + /// + /// - inputDataNil: The server response contained no data. + /// - inputDataNilOrZeroLength: The server response contained no data or the data was zero length. + /// - inputFileNil: The file containing the server response did not exist. + /// - inputFileReadFailed: The file containing the server response could not be read. + /// - stringSerializationFailed: String serialization failed using the provided `String.Encoding`. + /// - jsonSerializationFailed: JSON serialization failed with an underlying system error. + /// - propertyListSerializationFailed: Property list serialization failed with an underlying system error. + public enum ResponseSerializationFailureReason { + case inputDataNil + case inputDataNilOrZeroLength + case inputFileNil + case inputFileReadFailed(at: URL) + case stringSerializationFailed(encoding: String.Encoding) + case jsonSerializationFailed(error: Error) + case propertyListSerializationFailed(error: Error) + } + + case invalidURL(url: URLConvertible) + case parameterEncodingFailed(reason: ParameterEncodingFailureReason) + case multipartEncodingFailed(reason: MultipartEncodingFailureReason) + case responseValidationFailed(reason: ResponseValidationFailureReason) + case responseSerializationFailed(reason: ResponseSerializationFailureReason) +} + +// MARK: - Adapt Error + +struct AdaptError: Error { + let error: Error +} + +extension Error { + var underlyingAdaptError: Error? { return (self as? AdaptError)?.error } +} + +// MARK: - Error Booleans + +extension AFError { + /// Returns whether the AFError is an invalid URL error. + public var isInvalidURLError: Bool { + if case .invalidURL = self { return true } + return false + } + + /// Returns whether the AFError is a parameter encoding error. When `true`, the `underlyingError` property will + /// contain the associated value. + public var isParameterEncodingError: Bool { + if case .parameterEncodingFailed = self { return true } + return false + } + + /// Returns whether the AFError is a multipart encoding error. When `true`, the `url` and `underlyingError` properties + /// will contain the associated values. + public var isMultipartEncodingError: Bool { + if case .multipartEncodingFailed = self { return true } + return false + } + + /// Returns whether the `AFError` is a response validation error. When `true`, the `acceptableContentTypes`, + /// `responseContentType`, and `responseCode` properties will contain the associated values. + public var isResponseValidationError: Bool { + if case .responseValidationFailed = self { return true } + return false + } + + /// Returns whether the `AFError` is a response serialization error. When `true`, the `failedStringEncoding` and + /// `underlyingError` properties will contain the associated values. + public var isResponseSerializationError: Bool { + if case .responseSerializationFailed = self { return true } + return false + } +} + +// MARK: - Convenience Properties + +extension AFError { + /// The `URLConvertible` associated with the error. + public var urlConvertible: URLConvertible? { + switch self { + case .invalidURL(let url): + return url + default: + return nil + } + } + + /// The `URL` associated with the error. + public var url: URL? { + switch self { + case .multipartEncodingFailed(let reason): + return reason.url + default: + return nil + } + } + + /// The `Error` returned by a system framework associated with a `.parameterEncodingFailed`, + /// `.multipartEncodingFailed` or `.responseSerializationFailed` error. + public var underlyingError: Error? { + switch self { + case .parameterEncodingFailed(let reason): + return reason.underlyingError + case .multipartEncodingFailed(let reason): + return reason.underlyingError + case .responseSerializationFailed(let reason): + return reason.underlyingError + default: + return nil + } + } + + /// The acceptable `Content-Type`s of a `.responseValidationFailed` error. + public var acceptableContentTypes: [String]? { + switch self { + case .responseValidationFailed(let reason): + return reason.acceptableContentTypes + default: + return nil + } + } + + /// The response `Content-Type` of a `.responseValidationFailed` error. + public var responseContentType: String? { + switch self { + case .responseValidationFailed(let reason): + return reason.responseContentType + default: + return nil + } + } + + /// The response code of a `.responseValidationFailed` error. + public var responseCode: Int? { + switch self { + case .responseValidationFailed(let reason): + return reason.responseCode + default: + return nil + } + } + + /// The `String.Encoding` associated with a failed `.stringResponse()` call. + public var failedStringEncoding: String.Encoding? { + switch self { + case .responseSerializationFailed(let reason): + return reason.failedStringEncoding + default: + return nil + } + } +} + +extension AFError.ParameterEncodingFailureReason { + var underlyingError: Error? { + switch self { + case .jsonEncodingFailed(let error), .propertyListEncodingFailed(let error): + return error + default: + return nil + } + } +} + +extension AFError.MultipartEncodingFailureReason { + var url: URL? { + switch self { + case .bodyPartURLInvalid(let url), .bodyPartFilenameInvalid(let url), .bodyPartFileNotReachable(let url), + .bodyPartFileIsDirectory(let url), .bodyPartFileSizeNotAvailable(let url), + .bodyPartInputStreamCreationFailed(let url), .outputStreamCreationFailed(let url), + .outputStreamFileAlreadyExists(let url), .outputStreamURLInvalid(let url), + .bodyPartFileNotReachableWithError(let url, _), .bodyPartFileSizeQueryFailedWithError(let url, _): + return url + default: + return nil + } + } + + var underlyingError: Error? { + switch self { + case .bodyPartFileNotReachableWithError(_, let error), .bodyPartFileSizeQueryFailedWithError(_, let error), + .outputStreamWriteFailed(let error), .inputStreamReadFailed(let error): + return error + default: + return nil + } + } +} + +extension AFError.ResponseValidationFailureReason { + var acceptableContentTypes: [String]? { + switch self { + case .missingContentType(let types), .unacceptableContentType(let types, _): + return types + default: + return nil + } + } + + var responseContentType: String? { + switch self { + case .unacceptableContentType(_, let responseType): + return responseType + default: + return nil + } + } + + var responseCode: Int? { + switch self { + case .unacceptableStatusCode(let code): + return code + default: + return nil + } + } +} + +extension AFError.ResponseSerializationFailureReason { + var failedStringEncoding: String.Encoding? { + switch self { + case .stringSerializationFailed(let encoding): + return encoding + default: + return nil + } + } + + var underlyingError: Error? { + switch self { + case .jsonSerializationFailed(let error), .propertyListSerializationFailed(let error): + return error + default: + return nil + } + } +} + +// MARK: - Error Descriptions + +extension AFError: LocalizedError { + public var errorDescription: String? { + switch self { + case .invalidURL(let url): + return "URL is not valid: \(url)" + case .parameterEncodingFailed(let reason): + return reason.localizedDescription + case .multipartEncodingFailed(let reason): + return reason.localizedDescription + case .responseValidationFailed(let reason): + return reason.localizedDescription + case .responseSerializationFailed(let reason): + return reason.localizedDescription + } + } +} + +extension AFError.ParameterEncodingFailureReason { + var localizedDescription: String { + switch self { + case .missingURL: + return "URL request to encode was missing a URL" + case .jsonEncodingFailed(let error): + return "JSON could not be encoded because of error:\n\(error.localizedDescription)" + case .propertyListEncodingFailed(let error): + return "PropertyList could not be encoded because of error:\n\(error.localizedDescription)" + } + } +} + +extension AFError.MultipartEncodingFailureReason { + var localizedDescription: String { + switch self { + case .bodyPartURLInvalid(let url): + return "The URL provided is not a file URL: \(url)" + case .bodyPartFilenameInvalid(let url): + return "The URL provided does not have a valid filename: \(url)" + case .bodyPartFileNotReachable(let url): + return "The URL provided is not reachable: \(url)" + case .bodyPartFileNotReachableWithError(let url, let error): + return ( + "The system returned an error while checking the provided URL for " + + "reachability.\nURL: \(url)\nError: \(error)" + ) + case .bodyPartFileIsDirectory(let url): + return "The URL provided is a directory: \(url)" + case .bodyPartFileSizeNotAvailable(let url): + return "Could not fetch the file size from the provided URL: \(url)" + case .bodyPartFileSizeQueryFailedWithError(let url, let error): + return ( + "The system returned an error while attempting to fetch the file size from the " + + "provided URL.\nURL: \(url)\nError: \(error)" + ) + case .bodyPartInputStreamCreationFailed(let url): + return "Failed to create an InputStream for the provided URL: \(url)" + case .outputStreamCreationFailed(let url): + return "Failed to create an OutputStream for URL: \(url)" + case .outputStreamFileAlreadyExists(let url): + return "A file already exists at the provided URL: \(url)" + case .outputStreamURLInvalid(let url): + return "The provided OutputStream URL is invalid: \(url)" + case .outputStreamWriteFailed(let error): + return "OutputStream write failed with error: \(error)" + case .inputStreamReadFailed(let error): + return "InputStream read failed with error: \(error)" + } + } +} + +extension AFError.ResponseSerializationFailureReason { + var localizedDescription: String { + switch self { + case .inputDataNil: + return "Response could not be serialized, input data was nil." + case .inputDataNilOrZeroLength: + return "Response could not be serialized, input data was nil or zero length." + case .inputFileNil: + return "Response could not be serialized, input file was nil." + case .inputFileReadFailed(let url): + return "Response could not be serialized, input file could not be read: \(url)." + case .stringSerializationFailed(let encoding): + return "String could not be serialized with encoding: \(encoding)." + case .jsonSerializationFailed(let error): + return "JSON could not be serialized because of error:\n\(error.localizedDescription)" + case .propertyListSerializationFailed(let error): + return "PropertyList could not be serialized because of error:\n\(error.localizedDescription)" + } + } +} + +extension AFError.ResponseValidationFailureReason { + var localizedDescription: String { + switch self { + case .dataFileNil: + return "Response could not be validated, data file was nil." + case .dataFileReadFailed(let url): + return "Response could not be validated, data file could not be read: \(url)." + case .missingContentType(let types): + return ( + "Response Content-Type was missing and acceptable content types " + + "(\(types.joined(separator: ","))) do not match \"*/*\"." + ) + case .unacceptableContentType(let acceptableTypes, let responseType): + return ( + "Response Content-Type \"\(responseType)\" does not match any acceptable types: " + + "\(acceptableTypes.joined(separator: ","))." + ) + case .unacceptableStatusCode(let code): + return "Response status code was unacceptable: \(code)." + } + } +} diff --git a/Pods/Alamofire/Source/Alamofire.swift b/Pods/Alamofire/Source/Alamofire.swift new file mode 100644 index 0000000..2fcc05c --- /dev/null +++ b/Pods/Alamofire/Source/Alamofire.swift @@ -0,0 +1,465 @@ +// +// Alamofire.swift +// +// Copyright (c) 2014-2018 Alamofire Software Foundation (http://alamofire.org/) +// +// Permission is hereby granted, free of charge, to any person obtaining a copy +// of this software and associated documentation files (the "Software"), to deal +// in the Software without restriction, including without limitation the rights +// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +// copies of the Software, and to permit persons to whom the Software is +// furnished to do so, subject to the following conditions: +// +// The above copyright notice and this permission notice shall be included in +// all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN +// THE SOFTWARE. +// + +import Foundation + +/// Types adopting the `URLConvertible` protocol can be used to construct URLs, which are then used to construct +/// URL requests. +public protocol URLConvertible { + /// Returns a URL that conforms to RFC 2396 or throws an `Error`. + /// + /// - throws: An `Error` if the type cannot be converted to a `URL`. + /// + /// - returns: A URL or throws an `Error`. + func asURL() throws -> URL +} + +extension String: URLConvertible { + /// Returns a URL if `self` represents a valid URL string that conforms to RFC 2396 or throws an `AFError`. + /// + /// - throws: An `AFError.invalidURL` if `self` is not a valid URL string. + /// + /// - returns: A URL or throws an `AFError`. + public func asURL() throws -> URL { + guard let url = URL(string: self) else { throw AFError.invalidURL(url: self) } + return url + } +} + +extension URL: URLConvertible { + /// Returns self. + public func asURL() throws -> URL { return self } +} + +extension URLComponents: URLConvertible { + /// Returns a URL if `url` is not nil, otherwise throws an `Error`. + /// + /// - throws: An `AFError.invalidURL` if `url` is `nil`. + /// + /// - returns: A URL or throws an `AFError`. + public func asURL() throws -> URL { + guard let url = url else { throw AFError.invalidURL(url: self) } + return url + } +} + +// MARK: - + +/// Types adopting the `URLRequestConvertible` protocol can be used to construct URL requests. +public protocol URLRequestConvertible { + /// Returns a URL request or throws if an `Error` was encountered. + /// + /// - throws: An `Error` if the underlying `URLRequest` is `nil`. + /// + /// - returns: A URL request. + func asURLRequest() throws -> URLRequest +} + +extension URLRequestConvertible { + /// The URL request. + public var urlRequest: URLRequest? { return try? asURLRequest() } +} + +extension URLRequest: URLRequestConvertible { + /// Returns a URL request or throws if an `Error` was encountered. + public func asURLRequest() throws -> URLRequest { return self } +} + +// MARK: - + +extension URLRequest { + /// Creates an instance with the specified `method`, `urlString` and `headers`. + /// + /// - parameter url: The URL. + /// - parameter method: The HTTP method. + /// - parameter headers: The HTTP headers. `nil` by default. + /// + /// - returns: The new `URLRequest` instance. + public init(url: URLConvertible, method: HTTPMethod, headers: HTTPHeaders? = nil) throws { + let url = try url.asURL() + + self.init(url: url) + + httpMethod = method.rawValue + + if let headers = headers { + for (headerField, headerValue) in headers { + setValue(headerValue, forHTTPHeaderField: headerField) + } + } + } + + func adapt(using adapter: RequestAdapter?) throws -> URLRequest { + guard let adapter = adapter else { return self } + return try adapter.adapt(self) + } +} + +// MARK: - Data Request + +/// Creates a `DataRequest` using the default `SessionManager` to retrieve the contents of the specified `url`, +/// `method`, `parameters`, `encoding` and `headers`. +/// +/// - parameter url: The URL. +/// - parameter method: The HTTP method. `.get` by default. +/// - parameter parameters: The parameters. `nil` by default. +/// - parameter encoding: The parameter encoding. `URLEncoding.default` by default. +/// - parameter headers: The HTTP headers. `nil` by default. +/// +/// - returns: The created `DataRequest`. +@discardableResult +public func request( + _ url: URLConvertible, + method: HTTPMethod = .get, + parameters: Parameters? = nil, + encoding: ParameterEncoding = URLEncoding.default, + headers: HTTPHeaders? = nil) + -> DataRequest +{ + return SessionManager.default.request( + url, + method: method, + parameters: parameters, + encoding: encoding, + headers: headers + ) +} + +/// Creates a `DataRequest` using the default `SessionManager` to retrieve the contents of a URL based on the +/// specified `urlRequest`. +/// +/// - parameter urlRequest: The URL request +/// +/// - returns: The created `DataRequest`. +@discardableResult +public func request(_ urlRequest: URLRequestConvertible) -> DataRequest { + return SessionManager.default.request(urlRequest) +} + +// MARK: - Download Request + +// MARK: URL Request + +/// Creates a `DownloadRequest` using the default `SessionManager` to retrieve the contents of the specified `url`, +/// `method`, `parameters`, `encoding`, `headers` and save them to the `destination`. +/// +/// If `destination` is not specified, the contents will remain in the temporary location determined by the +/// underlying URL session. +/// +/// - parameter url: The URL. +/// - parameter method: The HTTP method. `.get` by default. +/// - parameter parameters: The parameters. `nil` by default. +/// - parameter encoding: The parameter encoding. `URLEncoding.default` by default. +/// - parameter headers: The HTTP headers. `nil` by default. +/// - parameter destination: The closure used to determine the destination of the downloaded file. `nil` by default. +/// +/// - returns: The created `DownloadRequest`. +@discardableResult +public func download( + _ url: URLConvertible, + method: HTTPMethod = .get, + parameters: Parameters? = nil, + encoding: ParameterEncoding = URLEncoding.default, + headers: HTTPHeaders? = nil, + to destination: DownloadRequest.DownloadFileDestination? = nil) + -> DownloadRequest +{ + return SessionManager.default.download( + url, + method: method, + parameters: parameters, + encoding: encoding, + headers: headers, + to: destination + ) +} + +/// Creates a `DownloadRequest` using the default `SessionManager` to retrieve the contents of a URL based on the +/// specified `urlRequest` and save them to the `destination`. +/// +/// If `destination` is not specified, the contents will remain in the temporary location determined by the +/// underlying URL session. +/// +/// - parameter urlRequest: The URL request. +/// - parameter destination: The closure used to determine the destination of the downloaded file. `nil` by default. +/// +/// - returns: The created `DownloadRequest`. +@discardableResult +public func download( + _ urlRequest: URLRequestConvertible, + to destination: DownloadRequest.DownloadFileDestination? = nil) + -> DownloadRequest +{ + return SessionManager.default.download(urlRequest, to: destination) +} + +// MARK: Resume Data + +/// Creates a `DownloadRequest` using the default `SessionManager` from the `resumeData` produced from a +/// previous request cancellation to retrieve the contents of the original request and save them to the `destination`. +/// +/// If `destination` is not specified, the contents will remain in the temporary location determined by the +/// underlying URL session. +/// +/// On the latest release of all the Apple platforms (iOS 10, macOS 10.12, tvOS 10, watchOS 3), `resumeData` is broken +/// on background URL session configurations. There's an underlying bug in the `resumeData` generation logic where the +/// data is written incorrectly and will always fail to resume the download. For more information about the bug and +/// possible workarounds, please refer to the following Stack Overflow post: +/// +/// - http://stackoverflow.com/a/39347461/1342462 +/// +/// - parameter resumeData: The resume data. This is an opaque data blob produced by `URLSessionDownloadTask` +/// when a task is cancelled. See `URLSession -downloadTask(withResumeData:)` for additional +/// information. +/// - parameter destination: The closure used to determine the destination of the downloaded file. `nil` by default. +/// +/// - returns: The created `DownloadRequest`. +@discardableResult +public func download( + resumingWith resumeData: Data, + to destination: DownloadRequest.DownloadFileDestination? = nil) + -> DownloadRequest +{ + return SessionManager.default.download(resumingWith: resumeData, to: destination) +} + +// MARK: - Upload Request + +// MARK: File + +/// Creates an `UploadRequest` using the default `SessionManager` from the specified `url`, `method` and `headers` +/// for uploading the `file`. +/// +/// - parameter file: The file to upload. +/// - parameter url: The URL. +/// - parameter method: The HTTP method. `.post` by default. +/// - parameter headers: The HTTP headers. `nil` by default. +/// +/// - returns: The created `UploadRequest`. +@discardableResult +public func upload( + _ fileURL: URL, + to url: URLConvertible, + method: HTTPMethod = .post, + headers: HTTPHeaders? = nil) + -> UploadRequest +{ + return SessionManager.default.upload(fileURL, to: url, method: method, headers: headers) +} + +/// Creates a `UploadRequest` using the default `SessionManager` from the specified `urlRequest` for +/// uploading the `file`. +/// +/// - parameter file: The file to upload. +/// - parameter urlRequest: The URL request. +/// +/// - returns: The created `UploadRequest`. +@discardableResult +public func upload(_ fileURL: URL, with urlRequest: URLRequestConvertible) -> UploadRequest { + return SessionManager.default.upload(fileURL, with: urlRequest) +} + +// MARK: Data + +/// Creates an `UploadRequest` using the default `SessionManager` from the specified `url`, `method` and `headers` +/// for uploading the `data`. +/// +/// - parameter data: The data to upload. +/// - parameter url: The URL. +/// - parameter method: The HTTP method. `.post` by default. +/// - parameter headers: The HTTP headers. `nil` by default. +/// +/// - returns: The created `UploadRequest`. +@discardableResult +public func upload( + _ data: Data, + to url: URLConvertible, + method: HTTPMethod = .post, + headers: HTTPHeaders? = nil) + -> UploadRequest +{ + return SessionManager.default.upload(data, to: url, method: method, headers: headers) +} + +/// Creates an `UploadRequest` using the default `SessionManager` from the specified `urlRequest` for +/// uploading the `data`. +/// +/// - parameter data: The data to upload. +/// - parameter urlRequest: The URL request. +/// +/// - returns: The created `UploadRequest`. +@discardableResult +public func upload(_ data: Data, with urlRequest: URLRequestConvertible) -> UploadRequest { + return SessionManager.default.upload(data, with: urlRequest) +} + +// MARK: InputStream + +/// Creates an `UploadRequest` using the default `SessionManager` from the specified `url`, `method` and `headers` +/// for uploading the `stream`. +/// +/// - parameter stream: The stream to upload. +/// - parameter url: The URL. +/// - parameter method: The HTTP method. `.post` by default. +/// - parameter headers: The HTTP headers. `nil` by default. +/// +/// - returns: The created `UploadRequest`. +@discardableResult +public func upload( + _ stream: InputStream, + to url: URLConvertible, + method: HTTPMethod = .post, + headers: HTTPHeaders? = nil) + -> UploadRequest +{ + return SessionManager.default.upload(stream, to: url, method: method, headers: headers) +} + +/// Creates an `UploadRequest` using the default `SessionManager` from the specified `urlRequest` for +/// uploading the `stream`. +/// +/// - parameter urlRequest: The URL request. +/// - parameter stream: The stream to upload. +/// +/// - returns: The created `UploadRequest`. +@discardableResult +public func upload(_ stream: InputStream, with urlRequest: URLRequestConvertible) -> UploadRequest { + return SessionManager.default.upload(stream, with: urlRequest) +} + +// MARK: MultipartFormData + +/// Encodes `multipartFormData` using `encodingMemoryThreshold` with the default `SessionManager` and calls +/// `encodingCompletion` with new `UploadRequest` using the `url`, `method` and `headers`. +/// +/// It is important to understand the memory implications of uploading `MultipartFormData`. If the cummulative +/// payload is small, encoding the data in-memory and directly uploading to a server is the by far the most +/// efficient approach. However, if the payload is too large, encoding the data in-memory could cause your app to +/// be terminated. Larger payloads must first be written to disk using input and output streams to keep the memory +/// footprint low, then the data can be uploaded as a stream from the resulting file. Streaming from disk MUST be +/// used for larger payloads such as video content. +/// +/// The `encodingMemoryThreshold` parameter allows Alamofire to automatically determine whether to encode in-memory +/// or stream from disk. If the content length of the `MultipartFormData` is below the `encodingMemoryThreshold`, +/// encoding takes place in-memory. If the content length exceeds the threshold, the data is streamed to disk +/// during the encoding process. Then the result is uploaded as data or as a stream depending on which encoding +/// technique was used. +/// +/// - parameter multipartFormData: The closure used to append body parts to the `MultipartFormData`. +/// - parameter encodingMemoryThreshold: The encoding memory threshold in bytes. +/// `multipartFormDataEncodingMemoryThreshold` by default. +/// - parameter url: The URL. +/// - parameter method: The HTTP method. `.post` by default. +/// - parameter headers: The HTTP headers. `nil` by default. +/// - parameter encodingCompletion: The closure called when the `MultipartFormData` encoding is complete. +public func upload( + multipartFormData: @escaping (MultipartFormData) -> Void, + usingThreshold encodingMemoryThreshold: UInt64 = SessionManager.multipartFormDataEncodingMemoryThreshold, + to url: URLConvertible, + method: HTTPMethod = .post, + headers: HTTPHeaders? = nil, + encodingCompletion: ((SessionManager.MultipartFormDataEncodingResult) -> Void)?) +{ + return SessionManager.default.upload( + multipartFormData: multipartFormData, + usingThreshold: encodingMemoryThreshold, + to: url, + method: method, + headers: headers, + encodingCompletion: encodingCompletion + ) +} + +/// Encodes `multipartFormData` using `encodingMemoryThreshold` and the default `SessionManager` and +/// calls `encodingCompletion` with new `UploadRequest` using the `urlRequest`. +/// +/// It is important to understand the memory implications of uploading `MultipartFormData`. If the cummulative +/// payload is small, encoding the data in-memory and directly uploading to a server is the by far the most +/// efficient approach. However, if the payload is too large, encoding the data in-memory could cause your app to +/// be terminated. Larger payloads must first be written to disk using input and output streams to keep the memory +/// footprint low, then the data can be uploaded as a stream from the resulting file. Streaming from disk MUST be +/// used for larger payloads such as video content. +/// +/// The `encodingMemoryThreshold` parameter allows Alamofire to automatically determine whether to encode in-memory +/// or stream from disk. If the content length of the `MultipartFormData` is below the `encodingMemoryThreshold`, +/// encoding takes place in-memory. If the content length exceeds the threshold, the data is streamed to disk +/// during the encoding process. Then the result is uploaded as data or as a stream depending on which encoding +/// technique was used. +/// +/// - parameter multipartFormData: The closure used to append body parts to the `MultipartFormData`. +/// - parameter encodingMemoryThreshold: The encoding memory threshold in bytes. +/// `multipartFormDataEncodingMemoryThreshold` by default. +/// - parameter urlRequest: The URL request. +/// - parameter encodingCompletion: The closure called when the `MultipartFormData` encoding is complete. +public func upload( + multipartFormData: @escaping (MultipartFormData) -> Void, + usingThreshold encodingMemoryThreshold: UInt64 = SessionManager.multipartFormDataEncodingMemoryThreshold, + with urlRequest: URLRequestConvertible, + encodingCompletion: ((SessionManager.MultipartFormDataEncodingResult) -> Void)?) +{ + return SessionManager.default.upload( + multipartFormData: multipartFormData, + usingThreshold: encodingMemoryThreshold, + with: urlRequest, + encodingCompletion: encodingCompletion + ) +} + +#if !os(watchOS) + +// MARK: - Stream Request + +// MARK: Hostname and Port + +/// Creates a `StreamRequest` using the default `SessionManager` for bidirectional streaming with the `hostname` +/// and `port`. +/// +/// If `startRequestsImmediately` is `true`, the request will have `resume()` called before being returned. +/// +/// - parameter hostName: The hostname of the server to connect to. +/// - parameter port: The port of the server to connect to. +/// +/// - returns: The created `StreamRequest`. +@discardableResult +@available(iOS 9.0, macOS 10.11, tvOS 9.0, *) +public func stream(withHostName hostName: String, port: Int) -> StreamRequest { + return SessionManager.default.stream(withHostName: hostName, port: port) +} + +// MARK: NetService + +/// Creates a `StreamRequest` using the default `SessionManager` for bidirectional streaming with the `netService`. +/// +/// If `startRequestsImmediately` is `true`, the request will have `resume()` called before being returned. +/// +/// - parameter netService: The net service used to identify the endpoint. +/// +/// - returns: The created `StreamRequest`. +@discardableResult +@available(iOS 9.0, macOS 10.11, tvOS 9.0, *) +public func stream(with netService: NetService) -> StreamRequest { + return SessionManager.default.stream(with: netService) +} + +#endif diff --git a/Pods/Alamofire/Source/DispatchQueue+Alamofire.swift b/Pods/Alamofire/Source/DispatchQueue+Alamofire.swift new file mode 100644 index 0000000..dea3ebc --- /dev/null +++ b/Pods/Alamofire/Source/DispatchQueue+Alamofire.swift @@ -0,0 +1,37 @@ +// +// DispatchQueue+Alamofire.swift +// +// Copyright (c) 2014-2018 Alamofire Software Foundation (http://alamofire.org/) +// +// Permission is hereby granted, free of charge, to any person obtaining a copy +// of this software and associated documentation files (the "Software"), to deal +// in the Software without restriction, including without limitation the rights +// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +// copies of the Software, and to permit persons to whom the Software is +// furnished to do so, subject to the following conditions: +// +// The above copyright notice and this permission notice shall be included in +// all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN +// THE SOFTWARE. +// + +import Dispatch +import Foundation + +extension DispatchQueue { + static var userInteractive: DispatchQueue { return DispatchQueue.global(qos: .userInteractive) } + static var userInitiated: DispatchQueue { return DispatchQueue.global(qos: .userInitiated) } + static var utility: DispatchQueue { return DispatchQueue.global(qos: .utility) } + static var background: DispatchQueue { return DispatchQueue.global(qos: .background) } + + func after(_ delay: TimeInterval, execute closure: @escaping () -> Void) { + asyncAfter(deadline: .now() + delay, execute: closure) + } +} diff --git a/Pods/Alamofire/Source/MultipartFormData.swift b/Pods/Alamofire/Source/MultipartFormData.swift new file mode 100644 index 0000000..057e68b --- /dev/null +++ b/Pods/Alamofire/Source/MultipartFormData.swift @@ -0,0 +1,580 @@ +// +// MultipartFormData.swift +// +// Copyright (c) 2014-2018 Alamofire Software Foundation (http://alamofire.org/) +// +// Permission is hereby granted, free of charge, to any person obtaining a copy +// of this software and associated documentation files (the "Software"), to deal +// in the Software without restriction, including without limitation the rights +// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +// copies of the Software, and to permit persons to whom the Software is +// furnished to do so, subject to the following conditions: +// +// The above copyright notice and this permission notice shall be included in +// all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN +// THE SOFTWARE. +// + +import Foundation + +#if os(iOS) || os(watchOS) || os(tvOS) +import MobileCoreServices +#elseif os(macOS) +import CoreServices +#endif + +/// Constructs `multipart/form-data` for uploads within an HTTP or HTTPS body. There are currently two ways to encode +/// multipart form data. The first way is to encode the data directly in memory. This is very efficient, but can lead +/// to memory issues if the dataset is too large. The second way is designed for larger datasets and will write all the +/// data to a single file on disk with all the proper boundary segmentation. The second approach MUST be used for +/// larger datasets such as video content, otherwise your app may run out of memory when trying to encode the dataset. +/// +/// For more information on `multipart/form-data` in general, please refer to the RFC-2388 and RFC-2045 specs as well +/// and the w3 form documentation. +/// +/// - https://www.ietf.org/rfc/rfc2388.txt +/// - https://www.ietf.org/rfc/rfc2045.txt +/// - https://www.w3.org/TR/html401/interact/forms.html#h-17.13 +open class MultipartFormData { + + // MARK: - Helper Types + + struct EncodingCharacters { + static let crlf = "\r\n" + } + + struct BoundaryGenerator { + enum BoundaryType { + case initial, encapsulated, final + } + + static func randomBoundary() -> String { + return String(format: "alamofire.boundary.%08x%08x", arc4random(), arc4random()) + } + + static func boundaryData(forBoundaryType boundaryType: BoundaryType, boundary: String) -> Data { + let boundaryText: String + + switch boundaryType { + case .initial: + boundaryText = "--\(boundary)\(EncodingCharacters.crlf)" + case .encapsulated: + boundaryText = "\(EncodingCharacters.crlf)--\(boundary)\(EncodingCharacters.crlf)" + case .final: + boundaryText = "\(EncodingCharacters.crlf)--\(boundary)--\(EncodingCharacters.crlf)" + } + + return boundaryText.data(using: String.Encoding.utf8, allowLossyConversion: false)! + } + } + + class BodyPart { + let headers: HTTPHeaders + let bodyStream: InputStream + let bodyContentLength: UInt64 + var hasInitialBoundary = false + var hasFinalBoundary = false + + init(headers: HTTPHeaders, bodyStream: InputStream, bodyContentLength: UInt64) { + self.headers = headers + self.bodyStream = bodyStream + self.bodyContentLength = bodyContentLength + } + } + + // MARK: - Properties + + /// The `Content-Type` header value containing the boundary used to generate the `multipart/form-data`. + open lazy var contentType: String = "multipart/form-data; boundary=\(self.boundary)" + + /// The content length of all body parts used to generate the `multipart/form-data` not including the boundaries. + public var contentLength: UInt64 { return bodyParts.reduce(0) { $0 + $1.bodyContentLength } } + + /// The boundary used to separate the body parts in the encoded form data. + public let boundary: String + + private var bodyParts: [BodyPart] + private var bodyPartError: AFError? + private let streamBufferSize: Int + + // MARK: - Lifecycle + + /// Creates a multipart form data object. + /// + /// - returns: The multipart form data object. + public init() { + self.boundary = BoundaryGenerator.randomBoundary() + self.bodyParts = [] + + /// + /// The optimal read/write buffer size in bytes for input and output streams is 1024 (1KB). For more + /// information, please refer to the following article: + /// - https://developer.apple.com/library/mac/documentation/Cocoa/Conceptual/Streams/Articles/ReadingInputStreams.html + /// + + self.streamBufferSize = 1024 + } + + // MARK: - Body Parts + + /// Creates a body part from the data and appends it to the multipart form data object. + /// + /// The body part data will be encoded using the following format: + /// + /// - `Content-Disposition: form-data; name=#{name}` (HTTP Header) + /// - Encoded data + /// - Multipart form boundary + /// + /// - parameter data: The data to encode into the multipart form data. + /// - parameter name: The name to associate with the data in the `Content-Disposition` HTTP header. + public func append(_ data: Data, withName name: String) { + let headers = contentHeaders(withName: name) + let stream = InputStream(data: data) + let length = UInt64(data.count) + + append(stream, withLength: length, headers: headers) + } + + /// Creates a body part from the data and appends it to the multipart form data object. + /// + /// The body part data will be encoded using the following format: + /// + /// - `Content-Disposition: form-data; name=#{name}` (HTTP Header) + /// - `Content-Type: #{generated mimeType}` (HTTP Header) + /// - Encoded data + /// - Multipart form boundary + /// + /// - parameter data: The data to encode into the multipart form data. + /// - parameter name: The name to associate with the data in the `Content-Disposition` HTTP header. + /// - parameter mimeType: The MIME type to associate with the data content type in the `Content-Type` HTTP header. + public func append(_ data: Data, withName name: String, mimeType: String) { + let headers = contentHeaders(withName: name, mimeType: mimeType) + let stream = InputStream(data: data) + let length = UInt64(data.count) + + append(stream, withLength: length, headers: headers) + } + + /// Creates a body part from the data and appends it to the multipart form data object. + /// + /// The body part data will be encoded using the following format: + /// + /// - `Content-Disposition: form-data; name=#{name}; filename=#{filename}` (HTTP Header) + /// - `Content-Type: #{mimeType}` (HTTP Header) + /// - Encoded file data + /// - Multipart form boundary + /// + /// - parameter data: The data to encode into the multipart form data. + /// - parameter name: The name to associate with the data in the `Content-Disposition` HTTP header. + /// - parameter fileName: The filename to associate with the data in the `Content-Disposition` HTTP header. + /// - parameter mimeType: The MIME type to associate with the data in the `Content-Type` HTTP header. + public func append(_ data: Data, withName name: String, fileName: String, mimeType: String) { + let headers = contentHeaders(withName: name, fileName: fileName, mimeType: mimeType) + let stream = InputStream(data: data) + let length = UInt64(data.count) + + append(stream, withLength: length, headers: headers) + } + + /// Creates a body part from the file and appends it to the multipart form data object. + /// + /// The body part data will be encoded using the following format: + /// + /// - `Content-Disposition: form-data; name=#{name}; filename=#{generated filename}` (HTTP Header) + /// - `Content-Type: #{generated mimeType}` (HTTP Header) + /// - Encoded file data + /// - Multipart form boundary + /// + /// The filename in the `Content-Disposition` HTTP header is generated from the last path component of the + /// `fileURL`. The `Content-Type` HTTP header MIME type is generated by mapping the `fileURL` extension to the + /// system associated MIME type. + /// + /// - parameter fileURL: The URL of the file whose content will be encoded into the multipart form data. + /// - parameter name: The name to associate with the file content in the `Content-Disposition` HTTP header. + public func append(_ fileURL: URL, withName name: String) { + let fileName = fileURL.lastPathComponent + let pathExtension = fileURL.pathExtension + + if !fileName.isEmpty && !pathExtension.isEmpty { + let mime = mimeType(forPathExtension: pathExtension) + append(fileURL, withName: name, fileName: fileName, mimeType: mime) + } else { + setBodyPartError(withReason: .bodyPartFilenameInvalid(in: fileURL)) + } + } + + /// Creates a body part from the file and appends it to the multipart form data object. + /// + /// The body part data will be encoded using the following format: + /// + /// - Content-Disposition: form-data; name=#{name}; filename=#{filename} (HTTP Header) + /// - Content-Type: #{mimeType} (HTTP Header) + /// - Encoded file data + /// - Multipart form boundary + /// + /// - parameter fileURL: The URL of the file whose content will be encoded into the multipart form data. + /// - parameter name: The name to associate with the file content in the `Content-Disposition` HTTP header. + /// - parameter fileName: The filename to associate with the file content in the `Content-Disposition` HTTP header. + /// - parameter mimeType: The MIME type to associate with the file content in the `Content-Type` HTTP header. + public func append(_ fileURL: URL, withName name: String, fileName: String, mimeType: String) { + let headers = contentHeaders(withName: name, fileName: fileName, mimeType: mimeType) + + //============================================================ + // Check 1 - is file URL? + //============================================================ + + guard fileURL.isFileURL else { + setBodyPartError(withReason: .bodyPartURLInvalid(url: fileURL)) + return + } + + //============================================================ + // Check 2 - is file URL reachable? + //============================================================ + + do { + let isReachable = try fileURL.checkPromisedItemIsReachable() + guard isReachable else { + setBodyPartError(withReason: .bodyPartFileNotReachable(at: fileURL)) + return + } + } catch { + setBodyPartError(withReason: .bodyPartFileNotReachableWithError(atURL: fileURL, error: error)) + return + } + + //============================================================ + // Check 3 - is file URL a directory? + //============================================================ + + var isDirectory: ObjCBool = false + let path = fileURL.path + + guard FileManager.default.fileExists(atPath: path, isDirectory: &isDirectory) && !isDirectory.boolValue else { + setBodyPartError(withReason: .bodyPartFileIsDirectory(at: fileURL)) + return + } + + //============================================================ + // Check 4 - can the file size be extracted? + //============================================================ + + let bodyContentLength: UInt64 + + do { + guard let fileSize = try FileManager.default.attributesOfItem(atPath: path)[.size] as? NSNumber else { + setBodyPartError(withReason: .bodyPartFileSizeNotAvailable(at: fileURL)) + return + } + + bodyContentLength = fileSize.uint64Value + } + catch { + setBodyPartError(withReason: .bodyPartFileSizeQueryFailedWithError(forURL: fileURL, error: error)) + return + } + + //============================================================ + // Check 5 - can a stream be created from file URL? + //============================================================ + + guard let stream = InputStream(url: fileURL) else { + setBodyPartError(withReason: .bodyPartInputStreamCreationFailed(for: fileURL)) + return + } + + append(stream, withLength: bodyContentLength, headers: headers) + } + + /// Creates a body part from the stream and appends it to the multipart form data object. + /// + /// The body part data will be encoded using the following format: + /// + /// - `Content-Disposition: form-data; name=#{name}; filename=#{filename}` (HTTP Header) + /// - `Content-Type: #{mimeType}` (HTTP Header) + /// - Encoded stream data + /// - Multipart form boundary + /// + /// - parameter stream: The input stream to encode in the multipart form data. + /// - parameter length: The content length of the stream. + /// - parameter name: The name to associate with the stream content in the `Content-Disposition` HTTP header. + /// - parameter fileName: The filename to associate with the stream content in the `Content-Disposition` HTTP header. + /// - parameter mimeType: The MIME type to associate with the stream content in the `Content-Type` HTTP header. + public func append( + _ stream: InputStream, + withLength length: UInt64, + name: String, + fileName: String, + mimeType: String) + { + let headers = contentHeaders(withName: name, fileName: fileName, mimeType: mimeType) + append(stream, withLength: length, headers: headers) + } + + /// Creates a body part with the headers, stream and length and appends it to the multipart form data object. + /// + /// The body part data will be encoded using the following format: + /// + /// - HTTP headers + /// - Encoded stream data + /// - Multipart form boundary + /// + /// - parameter stream: The input stream to encode in the multipart form data. + /// - parameter length: The content length of the stream. + /// - parameter headers: The HTTP headers for the body part. + public func append(_ stream: InputStream, withLength length: UInt64, headers: HTTPHeaders) { + let bodyPart = BodyPart(headers: headers, bodyStream: stream, bodyContentLength: length) + bodyParts.append(bodyPart) + } + + // MARK: - Data Encoding + + /// Encodes all the appended body parts into a single `Data` value. + /// + /// It is important to note that this method will load all the appended body parts into memory all at the same + /// time. This method should only be used when the encoded data will have a small memory footprint. For large data + /// cases, please use the `writeEncodedDataToDisk(fileURL:completionHandler:)` method. + /// + /// - throws: An `AFError` if encoding encounters an error. + /// + /// - returns: The encoded `Data` if encoding is successful. + public func encode() throws -> Data { + if let bodyPartError = bodyPartError { + throw bodyPartError + } + + var encoded = Data() + + bodyParts.first?.hasInitialBoundary = true + bodyParts.last?.hasFinalBoundary = true + + for bodyPart in bodyParts { + let encodedData = try encode(bodyPart) + encoded.append(encodedData) + } + + return encoded + } + + /// Writes the appended body parts into the given file URL. + /// + /// This process is facilitated by reading and writing with input and output streams, respectively. Thus, + /// this approach is very memory efficient and should be used for large body part data. + /// + /// - parameter fileURL: The file URL to write the multipart form data into. + /// + /// - throws: An `AFError` if encoding encounters an error. + public func writeEncodedData(to fileURL: URL) throws { + if let bodyPartError = bodyPartError { + throw bodyPartError + } + + if FileManager.default.fileExists(atPath: fileURL.path) { + throw AFError.multipartEncodingFailed(reason: .outputStreamFileAlreadyExists(at: fileURL)) + } else if !fileURL.isFileURL { + throw AFError.multipartEncodingFailed(reason: .outputStreamURLInvalid(url: fileURL)) + } + + guard let outputStream = OutputStream(url: fileURL, append: false) else { + throw AFError.multipartEncodingFailed(reason: .outputStreamCreationFailed(for: fileURL)) + } + + outputStream.open() + defer { outputStream.close() } + + self.bodyParts.first?.hasInitialBoundary = true + self.bodyParts.last?.hasFinalBoundary = true + + for bodyPart in self.bodyParts { + try write(bodyPart, to: outputStream) + } + } + + // MARK: - Private - Body Part Encoding + + private func encode(_ bodyPart: BodyPart) throws -> Data { + var encoded = Data() + + let initialData = bodyPart.hasInitialBoundary ? initialBoundaryData() : encapsulatedBoundaryData() + encoded.append(initialData) + + let headerData = encodeHeaders(for: bodyPart) + encoded.append(headerData) + + let bodyStreamData = try encodeBodyStream(for: bodyPart) + encoded.append(bodyStreamData) + + if bodyPart.hasFinalBoundary { + encoded.append(finalBoundaryData()) + } + + return encoded + } + + private func encodeHeaders(for bodyPart: BodyPart) -> Data { + var headerText = "" + + for (key, value) in bodyPart.headers { + headerText += "\(key): \(value)\(EncodingCharacters.crlf)" + } + headerText += EncodingCharacters.crlf + + return headerText.data(using: String.Encoding.utf8, allowLossyConversion: false)! + } + + private func encodeBodyStream(for bodyPart: BodyPart) throws -> Data { + let inputStream = bodyPart.bodyStream + inputStream.open() + defer { inputStream.close() } + + var encoded = Data() + + while inputStream.hasBytesAvailable { + var buffer = [UInt8](repeating: 0, count: streamBufferSize) + let bytesRead = inputStream.read(&buffer, maxLength: streamBufferSize) + + if let error = inputStream.streamError { + throw AFError.multipartEncodingFailed(reason: .inputStreamReadFailed(error: error)) + } + + if bytesRead > 0 { + encoded.append(buffer, count: bytesRead) + } else { + break + } + } + + return encoded + } + + // MARK: - Private - Writing Body Part to Output Stream + + private func write(_ bodyPart: BodyPart, to outputStream: OutputStream) throws { + try writeInitialBoundaryData(for: bodyPart, to: outputStream) + try writeHeaderData(for: bodyPart, to: outputStream) + try writeBodyStream(for: bodyPart, to: outputStream) + try writeFinalBoundaryData(for: bodyPart, to: outputStream) + } + + private func writeInitialBoundaryData(for bodyPart: BodyPart, to outputStream: OutputStream) throws { + let initialData = bodyPart.hasInitialBoundary ? initialBoundaryData() : encapsulatedBoundaryData() + return try write(initialData, to: outputStream) + } + + private func writeHeaderData(for bodyPart: BodyPart, to outputStream: OutputStream) throws { + let headerData = encodeHeaders(for: bodyPart) + return try write(headerData, to: outputStream) + } + + private func writeBodyStream(for bodyPart: BodyPart, to outputStream: OutputStream) throws { + let inputStream = bodyPart.bodyStream + + inputStream.open() + defer { inputStream.close() } + + while inputStream.hasBytesAvailable { + var buffer = [UInt8](repeating: 0, count: streamBufferSize) + let bytesRead = inputStream.read(&buffer, maxLength: streamBufferSize) + + if let streamError = inputStream.streamError { + throw AFError.multipartEncodingFailed(reason: .inputStreamReadFailed(error: streamError)) + } + + if bytesRead > 0 { + if buffer.count != bytesRead { + buffer = Array(buffer[0.. 0, outputStream.hasSpaceAvailable { + let bytesWritten = outputStream.write(buffer, maxLength: bytesToWrite) + + if let error = outputStream.streamError { + throw AFError.multipartEncodingFailed(reason: .outputStreamWriteFailed(error: error)) + } + + bytesToWrite -= bytesWritten + + if bytesToWrite > 0 { + buffer = Array(buffer[bytesWritten.. String { + if + let id = UTTypeCreatePreferredIdentifierForTag(kUTTagClassFilenameExtension, pathExtension as CFString, nil)?.takeRetainedValue(), + let contentType = UTTypeCopyPreferredTagWithClass(id, kUTTagClassMIMEType)?.takeRetainedValue() + { + return contentType as String + } + + return "application/octet-stream" + } + + // MARK: - Private - Content Headers + + private func contentHeaders(withName name: String, fileName: String? = nil, mimeType: String? = nil) -> [String: String] { + var disposition = "form-data; name=\"\(name)\"" + if let fileName = fileName { disposition += "; filename=\"\(fileName)\"" } + + var headers = ["Content-Disposition": disposition] + if let mimeType = mimeType { headers["Content-Type"] = mimeType } + + return headers + } + + // MARK: - Private - Boundary Encoding + + private func initialBoundaryData() -> Data { + return BoundaryGenerator.boundaryData(forBoundaryType: .initial, boundary: boundary) + } + + private func encapsulatedBoundaryData() -> Data { + return BoundaryGenerator.boundaryData(forBoundaryType: .encapsulated, boundary: boundary) + } + + private func finalBoundaryData() -> Data { + return BoundaryGenerator.boundaryData(forBoundaryType: .final, boundary: boundary) + } + + // MARK: - Private - Errors + + private func setBodyPartError(withReason reason: AFError.MultipartEncodingFailureReason) { + guard bodyPartError == nil else { return } + bodyPartError = AFError.multipartEncodingFailed(reason: reason) + } +} diff --git a/Pods/Alamofire/Source/NetworkReachabilityManager.swift b/Pods/Alamofire/Source/NetworkReachabilityManager.swift new file mode 100644 index 0000000..3ff2e7f --- /dev/null +++ b/Pods/Alamofire/Source/NetworkReachabilityManager.swift @@ -0,0 +1,233 @@ +// +// NetworkReachabilityManager.swift +// +// Copyright (c) 2014-2018 Alamofire Software Foundation (http://alamofire.org/) +// +// Permission is hereby granted, free of charge, to any person obtaining a copy +// of this software and associated documentation files (the "Software"), to deal +// in the Software without restriction, including without limitation the rights +// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +// copies of the Software, and to permit persons to whom the Software is +// furnished to do so, subject to the following conditions: +// +// The above copyright notice and this permission notice shall be included in +// all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN +// THE SOFTWARE. +// + +#if !os(watchOS) + +import Foundation +import SystemConfiguration + +/// The `NetworkReachabilityManager` class listens for reachability changes of hosts and addresses for both WWAN and +/// WiFi network interfaces. +/// +/// Reachability can be used to determine background information about why a network operation failed, or to retry +/// network requests when a connection is established. It should not be used to prevent a user from initiating a network +/// request, as it's possible that an initial request may be required to establish reachability. +open class NetworkReachabilityManager { + /// Defines the various states of network reachability. + /// + /// - unknown: It is unknown whether the network is reachable. + /// - notReachable: The network is not reachable. + /// - reachable: The network is reachable. + public enum NetworkReachabilityStatus { + case unknown + case notReachable + case reachable(ConnectionType) + } + + /// Defines the various connection types detected by reachability flags. + /// + /// - ethernetOrWiFi: The connection type is either over Ethernet or WiFi. + /// - wwan: The connection type is a WWAN connection. + public enum ConnectionType { + case ethernetOrWiFi + case wwan + } + + /// A closure executed when the network reachability status changes. The closure takes a single argument: the + /// network reachability status. + public typealias Listener = (NetworkReachabilityStatus) -> Void + + // MARK: - Properties + + /// Whether the network is currently reachable. + open var isReachable: Bool { return isReachableOnWWAN || isReachableOnEthernetOrWiFi } + + /// Whether the network is currently reachable over the WWAN interface. + open var isReachableOnWWAN: Bool { return networkReachabilityStatus == .reachable(.wwan) } + + /// Whether the network is currently reachable over Ethernet or WiFi interface. + open var isReachableOnEthernetOrWiFi: Bool { return networkReachabilityStatus == .reachable(.ethernetOrWiFi) } + + /// The current network reachability status. + open var networkReachabilityStatus: NetworkReachabilityStatus { + guard let flags = self.flags else { return .unknown } + return networkReachabilityStatusForFlags(flags) + } + + /// The dispatch queue to execute the `listener` closure on. + open var listenerQueue: DispatchQueue = DispatchQueue.main + + /// A closure executed when the network reachability status changes. + open var listener: Listener? + + open var flags: SCNetworkReachabilityFlags? { + var flags = SCNetworkReachabilityFlags() + + if SCNetworkReachabilityGetFlags(reachability, &flags) { + return flags + } + + return nil + } + + private let reachability: SCNetworkReachability + open var previousFlags: SCNetworkReachabilityFlags + + // MARK: - Initialization + + /// Creates a `NetworkReachabilityManager` instance with the specified host. + /// + /// - parameter host: The host used to evaluate network reachability. + /// + /// - returns: The new `NetworkReachabilityManager` instance. + public convenience init?(host: String) { + guard let reachability = SCNetworkReachabilityCreateWithName(nil, host) else { return nil } + self.init(reachability: reachability) + } + + /// Creates a `NetworkReachabilityManager` instance that monitors the address 0.0.0.0. + /// + /// Reachability treats the 0.0.0.0 address as a special token that causes it to monitor the general routing + /// status of the device, both IPv4 and IPv6. + /// + /// - returns: The new `NetworkReachabilityManager` instance. + public convenience init?() { + var address = sockaddr_in() + address.sin_len = UInt8(MemoryLayout.size) + address.sin_family = sa_family_t(AF_INET) + + guard let reachability = withUnsafePointer(to: &address, { pointer in + return pointer.withMemoryRebound(to: sockaddr.self, capacity: MemoryLayout.size) { + return SCNetworkReachabilityCreateWithAddress(nil, $0) + } + }) else { return nil } + + self.init(reachability: reachability) + } + + private init(reachability: SCNetworkReachability) { + self.reachability = reachability + self.previousFlags = SCNetworkReachabilityFlags() + } + + deinit { + stopListening() + } + + // MARK: - Listening + + /// Starts listening for changes in network reachability status. + /// + /// - returns: `true` if listening was started successfully, `false` otherwise. + @discardableResult + open func startListening() -> Bool { + var context = SCNetworkReachabilityContext(version: 0, info: nil, retain: nil, release: nil, copyDescription: nil) + context.info = Unmanaged.passUnretained(self).toOpaque() + + let callbackEnabled = SCNetworkReachabilitySetCallback( + reachability, + { (_, flags, info) in + let reachability = Unmanaged.fromOpaque(info!).takeUnretainedValue() + reachability.notifyListener(flags) + }, + &context + ) + + let queueEnabled = SCNetworkReachabilitySetDispatchQueue(reachability, listenerQueue) + + listenerQueue.async { + self.previousFlags = SCNetworkReachabilityFlags() + self.notifyListener(self.flags ?? SCNetworkReachabilityFlags()) + } + + return callbackEnabled && queueEnabled + } + + /// Stops listening for changes in network reachability status. + open func stopListening() { + SCNetworkReachabilitySetCallback(reachability, nil, nil) + SCNetworkReachabilitySetDispatchQueue(reachability, nil) + } + + // MARK: - Internal - Listener Notification + + func notifyListener(_ flags: SCNetworkReachabilityFlags) { + guard previousFlags != flags else { return } + previousFlags = flags + + listener?(networkReachabilityStatusForFlags(flags)) + } + + // MARK: - Internal - Network Reachability Status + + func networkReachabilityStatusForFlags(_ flags: SCNetworkReachabilityFlags) -> NetworkReachabilityStatus { + guard isNetworkReachable(with: flags) else { return .notReachable } + + var networkStatus: NetworkReachabilityStatus = .reachable(.ethernetOrWiFi) + + #if os(iOS) + if flags.contains(.isWWAN) { networkStatus = .reachable(.wwan) } + #endif + + return networkStatus + } + + func isNetworkReachable(with flags: SCNetworkReachabilityFlags) -> Bool { + let isReachable = flags.contains(.reachable) + let needsConnection = flags.contains(.connectionRequired) + let canConnectAutomatically = flags.contains(.connectionOnDemand) || flags.contains(.connectionOnTraffic) + let canConnectWithoutUserInteraction = canConnectAutomatically && !flags.contains(.interventionRequired) + + return isReachable && (!needsConnection || canConnectWithoutUserInteraction) + } +} + +// MARK: - + +extension NetworkReachabilityManager.NetworkReachabilityStatus: Equatable {} + +/// Returns whether the two network reachability status values are equal. +/// +/// - parameter lhs: The left-hand side value to compare. +/// - parameter rhs: The right-hand side value to compare. +/// +/// - returns: `true` if the two values are equal, `false` otherwise. +public func ==( + lhs: NetworkReachabilityManager.NetworkReachabilityStatus, + rhs: NetworkReachabilityManager.NetworkReachabilityStatus) + -> Bool +{ + switch (lhs, rhs) { + case (.unknown, .unknown): + return true + case (.notReachable, .notReachable): + return true + case let (.reachable(lhsConnectionType), .reachable(rhsConnectionType)): + return lhsConnectionType == rhsConnectionType + default: + return false + } +} + +#endif diff --git a/Pods/Alamofire/Source/Notifications.swift b/Pods/Alamofire/Source/Notifications.swift new file mode 100644 index 0000000..e1b6120 --- /dev/null +++ b/Pods/Alamofire/Source/Notifications.swift @@ -0,0 +1,55 @@ +// +// Notifications.swift +// +// Copyright (c) 2014-2018 Alamofire Software Foundation (http://alamofire.org/) +// +// Permission is hereby granted, free of charge, to any person obtaining a copy +// of this software and associated documentation files (the "Software"), to deal +// in the Software without restriction, including without limitation the rights +// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +// copies of the Software, and to permit persons to whom the Software is +// furnished to do so, subject to the following conditions: +// +// The above copyright notice and this permission notice shall be included in +// all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN +// THE SOFTWARE. +// + +import Foundation + +extension Notification.Name { + /// Used as a namespace for all `URLSessionTask` related notifications. + public struct Task { + /// Posted when a `URLSessionTask` is resumed. The notification `object` contains the resumed `URLSessionTask`. + public static let DidResume = Notification.Name(rawValue: "org.alamofire.notification.name.task.didResume") + + /// Posted when a `URLSessionTask` is suspended. The notification `object` contains the suspended `URLSessionTask`. + public static let DidSuspend = Notification.Name(rawValue: "org.alamofire.notification.name.task.didSuspend") + + /// Posted when a `URLSessionTask` is cancelled. The notification `object` contains the cancelled `URLSessionTask`. + public static let DidCancel = Notification.Name(rawValue: "org.alamofire.notification.name.task.didCancel") + + /// Posted when a `URLSessionTask` is completed. The notification `object` contains the completed `URLSessionTask`. + public static let DidComplete = Notification.Name(rawValue: "org.alamofire.notification.name.task.didComplete") + } +} + +// MARK: - + +extension Notification { + /// Used as a namespace for all `Notification` user info dictionary keys. + public struct Key { + /// User info dictionary key representing the `URLSessionTask` associated with the notification. + public static let Task = "org.alamofire.notification.key.task" + + /// User info dictionary key representing the responseData associated with the notification. + public static let ResponseData = "org.alamofire.notification.key.responseData" + } +} diff --git a/Pods/Alamofire/Source/ParameterEncoding.swift b/Pods/Alamofire/Source/ParameterEncoding.swift new file mode 100644 index 0000000..4a54f2d --- /dev/null +++ b/Pods/Alamofire/Source/ParameterEncoding.swift @@ -0,0 +1,483 @@ +// +// ParameterEncoding.swift +// +// Copyright (c) 2014-2018 Alamofire Software Foundation (http://alamofire.org/) +// +// Permission is hereby granted, free of charge, to any person obtaining a copy +// of this software and associated documentation files (the "Software"), to deal +// in the Software without restriction, including without limitation the rights +// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +// copies of the Software, and to permit persons to whom the Software is +// furnished to do so, subject to the following conditions: +// +// The above copyright notice and this permission notice shall be included in +// all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN +// THE SOFTWARE. +// + +import Foundation + +/// HTTP method definitions. +/// +/// See https://tools.ietf.org/html/rfc7231#section-4.3 +public enum HTTPMethod: String { + case options = "OPTIONS" + case get = "GET" + case head = "HEAD" + case post = "POST" + case put = "PUT" + case patch = "PATCH" + case delete = "DELETE" + case trace = "TRACE" + case connect = "CONNECT" +} + +// MARK: - + +/// A dictionary of parameters to apply to a `URLRequest`. +public typealias Parameters = [String: Any] + +/// A type used to define how a set of parameters are applied to a `URLRequest`. +public protocol ParameterEncoding { + /// Creates a URL request by encoding parameters and applying them onto an existing request. + /// + /// - parameter urlRequest: The request to have parameters applied. + /// - parameter parameters: The parameters to apply. + /// + /// - throws: An `AFError.parameterEncodingFailed` error if encoding fails. + /// + /// - returns: The encoded request. + func encode(_ urlRequest: URLRequestConvertible, with parameters: Parameters?) throws -> URLRequest +} + +// MARK: - + +/// Creates a url-encoded query string to be set as or appended to any existing URL query string or set as the HTTP +/// body of the URL request. Whether the query string is set or appended to any existing URL query string or set as +/// the HTTP body depends on the destination of the encoding. +/// +/// The `Content-Type` HTTP header field of an encoded request with HTTP body is set to +/// `application/x-www-form-urlencoded; charset=utf-8`. +/// +/// There is no published specification for how to encode collection types. By default the convention of appending +/// `[]` to the key for array values (`foo[]=1&foo[]=2`), and appending the key surrounded by square brackets for +/// nested dictionary values (`foo[bar]=baz`) is used. Optionally, `ArrayEncoding` can be used to omit the +/// square brackets appended to array keys. +/// +/// `BoolEncoding` can be used to configure how boolean values are encoded. The default behavior is to encode +/// `true` as 1 and `false` as 0. +public struct URLEncoding: ParameterEncoding { + + // MARK: Helper Types + + /// Defines whether the url-encoded query string is applied to the existing query string or HTTP body of the + /// resulting URL request. + /// + /// - methodDependent: Applies encoded query string result to existing query string for `GET`, `HEAD` and `DELETE` + /// requests and sets as the HTTP body for requests with any other HTTP method. + /// - queryString: Sets or appends encoded query string result to existing query string. + /// - httpBody: Sets encoded query string result as the HTTP body of the URL request. + public enum Destination { + case methodDependent, queryString, httpBody + } + + /// Configures how `Array` parameters are encoded. + /// + /// - brackets: An empty set of square brackets is appended to the key for every value. + /// This is the default behavior. + /// - noBrackets: No brackets are appended. The key is encoded as is. + public enum ArrayEncoding { + case brackets, noBrackets + + func encode(key: String) -> String { + switch self { + case .brackets: + return "\(key)[]" + case .noBrackets: + return key + } + } + } + + /// Configures how `Bool` parameters are encoded. + /// + /// - numeric: Encode `true` as `1` and `false` as `0`. This is the default behavior. + /// - literal: Encode `true` and `false` as string literals. + public enum BoolEncoding { + case numeric, literal + + func encode(value: Bool) -> String { + switch self { + case .numeric: + return value ? "1" : "0" + case .literal: + return value ? "true" : "false" + } + } + } + + // MARK: Properties + + /// Returns a default `URLEncoding` instance. + public static var `default`: URLEncoding { return URLEncoding() } + + /// Returns a `URLEncoding` instance with a `.methodDependent` destination. + public static var methodDependent: URLEncoding { return URLEncoding() } + + /// Returns a `URLEncoding` instance with a `.queryString` destination. + public static var queryString: URLEncoding { return URLEncoding(destination: .queryString) } + + /// Returns a `URLEncoding` instance with an `.httpBody` destination. + public static var httpBody: URLEncoding { return URLEncoding(destination: .httpBody) } + + /// The destination defining where the encoded query string is to be applied to the URL request. + public let destination: Destination + + /// The encoding to use for `Array` parameters. + public let arrayEncoding: ArrayEncoding + + /// The encoding to use for `Bool` parameters. + public let boolEncoding: BoolEncoding + + // MARK: Initialization + + /// Creates a `URLEncoding` instance using the specified destination. + /// + /// - parameter destination: The destination defining where the encoded query string is to be applied. + /// - parameter arrayEncoding: The encoding to use for `Array` parameters. + /// - parameter boolEncoding: The encoding to use for `Bool` parameters. + /// + /// - returns: The new `URLEncoding` instance. + public init(destination: Destination = .methodDependent, arrayEncoding: ArrayEncoding = .brackets, boolEncoding: BoolEncoding = .numeric) { + self.destination = destination + self.arrayEncoding = arrayEncoding + self.boolEncoding = boolEncoding + } + + // MARK: Encoding + + /// Creates a URL request by encoding parameters and applying them onto an existing request. + /// + /// - parameter urlRequest: The request to have parameters applied. + /// - parameter parameters: The parameters to apply. + /// + /// - throws: An `Error` if the encoding process encounters an error. + /// + /// - returns: The encoded request. + public func encode(_ urlRequest: URLRequestConvertible, with parameters: Parameters?) throws -> URLRequest { + var urlRequest = try urlRequest.asURLRequest() + + guard let parameters = parameters else { return urlRequest } + + if let method = HTTPMethod(rawValue: urlRequest.httpMethod ?? "GET"), encodesParametersInURL(with: method) { + guard let url = urlRequest.url else { + throw AFError.parameterEncodingFailed(reason: .missingURL) + } + + if var urlComponents = URLComponents(url: url, resolvingAgainstBaseURL: false), !parameters.isEmpty { + let percentEncodedQuery = (urlComponents.percentEncodedQuery.map { $0 + "&" } ?? "") + query(parameters) + urlComponents.percentEncodedQuery = percentEncodedQuery + urlRequest.url = urlComponents.url + } + } else { + if urlRequest.value(forHTTPHeaderField: "Content-Type") == nil { + urlRequest.setValue("application/x-www-form-urlencoded; charset=utf-8", forHTTPHeaderField: "Content-Type") + } + + urlRequest.httpBody = query(parameters).data(using: .utf8, allowLossyConversion: false) + } + + return urlRequest + } + + /// Creates percent-escaped, URL encoded query string components from the given key-value pair using recursion. + /// + /// - parameter key: The key of the query component. + /// - parameter value: The value of the query component. + /// + /// - returns: The percent-escaped, URL encoded query string components. + public func queryComponents(fromKey key: String, value: Any) -> [(String, String)] { + var components: [(String, String)] = [] + + if let dictionary = value as? [String: Any] { + for (nestedKey, value) in dictionary { + components += queryComponents(fromKey: "\(key)[\(nestedKey)]", value: value) + } + } else if let array = value as? [Any] { + for value in array { + components += queryComponents(fromKey: arrayEncoding.encode(key: key), value: value) + } + } else if let value = value as? NSNumber { + if value.isBool { + components.append((escape(key), escape(boolEncoding.encode(value: value.boolValue)))) + } else { + components.append((escape(key), escape("\(value)"))) + } + } else if let bool = value as? Bool { + components.append((escape(key), escape(boolEncoding.encode(value: bool)))) + } else { + components.append((escape(key), escape("\(value)"))) + } + + return components + } + + /// Returns a percent-escaped string following RFC 3986 for a query string key or value. + /// + /// RFC 3986 states that the following characters are "reserved" characters. + /// + /// - General Delimiters: ":", "#", "[", "]", "@", "?", "/" + /// - Sub-Delimiters: "!", "$", "&", "'", "(", ")", "*", "+", ",", ";", "=" + /// + /// In RFC 3986 - Section 3.4, it states that the "?" and "/" characters should not be escaped to allow + /// query strings to include a URL. Therefore, all "reserved" characters with the exception of "?" and "/" + /// should be percent-escaped in the query string. + /// + /// - parameter string: The string to be percent-escaped. + /// + /// - returns: The percent-escaped string. + public func escape(_ string: String) -> String { + let generalDelimitersToEncode = ":#[]@" // does not include "?" or "/" due to RFC 3986 - Section 3.4 + let subDelimitersToEncode = "!$&'()*+,;=" + + var allowedCharacterSet = CharacterSet.urlQueryAllowed + allowedCharacterSet.remove(charactersIn: "\(generalDelimitersToEncode)\(subDelimitersToEncode)") + + var escaped = "" + + //========================================================================================================== + // + // Batching is required for escaping due to an internal bug in iOS 8.1 and 8.2. Encoding more than a few + // hundred Chinese characters causes various malloc error crashes. To avoid this issue until iOS 8 is no + // longer supported, batching MUST be used for encoding. This introduces roughly a 20% overhead. For more + // info, please refer to: + // + // - https://github.com/Alamofire/Alamofire/issues/206 + // + //========================================================================================================== + + if #available(iOS 8.3, *) { + escaped = string.addingPercentEncoding(withAllowedCharacters: allowedCharacterSet) ?? string + } else { + let batchSize = 50 + var index = string.startIndex + + while index != string.endIndex { + let startIndex = index + let endIndex = string.index(index, offsetBy: batchSize, limitedBy: string.endIndex) ?? string.endIndex + let range = startIndex.. String { + var components: [(String, String)] = [] + + for key in parameters.keys.sorted(by: <) { + let value = parameters[key]! + components += queryComponents(fromKey: key, value: value) + } + return components.map { "\($0)=\($1)" }.joined(separator: "&") + } + + private func encodesParametersInURL(with method: HTTPMethod) -> Bool { + switch destination { + case .queryString: + return true + case .httpBody: + return false + default: + break + } + + switch method { + case .get, .head, .delete: + return true + default: + return false + } + } +} + +// MARK: - + +/// Uses `JSONSerialization` to create a JSON representation of the parameters object, which is set as the body of the +/// request. The `Content-Type` HTTP header field of an encoded request is set to `application/json`. +public struct JSONEncoding: ParameterEncoding { + + // MARK: Properties + + /// Returns a `JSONEncoding` instance with default writing options. + public static var `default`: JSONEncoding { return JSONEncoding() } + + /// Returns a `JSONEncoding` instance with `.prettyPrinted` writing options. + public static var prettyPrinted: JSONEncoding { return JSONEncoding(options: .prettyPrinted) } + + /// The options for writing the parameters as JSON data. + public let options: JSONSerialization.WritingOptions + + // MARK: Initialization + + /// Creates a `JSONEncoding` instance using the specified options. + /// + /// - parameter options: The options for writing the parameters as JSON data. + /// + /// - returns: The new `JSONEncoding` instance. + public init(options: JSONSerialization.WritingOptions = []) { + self.options = options + } + + // MARK: Encoding + + /// Creates a URL request by encoding parameters and applying them onto an existing request. + /// + /// - parameter urlRequest: The request to have parameters applied. + /// - parameter parameters: The parameters to apply. + /// + /// - throws: An `Error` if the encoding process encounters an error. + /// + /// - returns: The encoded request. + public func encode(_ urlRequest: URLRequestConvertible, with parameters: Parameters?) throws -> URLRequest { + var urlRequest = try urlRequest.asURLRequest() + + guard let parameters = parameters else { return urlRequest } + + do { + let data = try JSONSerialization.data(withJSONObject: parameters, options: options) + + if urlRequest.value(forHTTPHeaderField: "Content-Type") == nil { + urlRequest.setValue("application/json", forHTTPHeaderField: "Content-Type") + } + + urlRequest.httpBody = data + } catch { + throw AFError.parameterEncodingFailed(reason: .jsonEncodingFailed(error: error)) + } + + return urlRequest + } + + /// Creates a URL request by encoding the JSON object and setting the resulting data on the HTTP body. + /// + /// - parameter urlRequest: The request to apply the JSON object to. + /// - parameter jsonObject: The JSON object to apply to the request. + /// + /// - throws: An `Error` if the encoding process encounters an error. + /// + /// - returns: The encoded request. + public func encode(_ urlRequest: URLRequestConvertible, withJSONObject jsonObject: Any? = nil) throws -> URLRequest { + var urlRequest = try urlRequest.asURLRequest() + + guard let jsonObject = jsonObject else { return urlRequest } + + do { + let data = try JSONSerialization.data(withJSONObject: jsonObject, options: options) + + if urlRequest.value(forHTTPHeaderField: "Content-Type") == nil { + urlRequest.setValue("application/json", forHTTPHeaderField: "Content-Type") + } + + urlRequest.httpBody = data + } catch { + throw AFError.parameterEncodingFailed(reason: .jsonEncodingFailed(error: error)) + } + + return urlRequest + } +} + +// MARK: - + +/// Uses `PropertyListSerialization` to create a plist representation of the parameters object, according to the +/// associated format and write options values, which is set as the body of the request. The `Content-Type` HTTP header +/// field of an encoded request is set to `application/x-plist`. +public struct PropertyListEncoding: ParameterEncoding { + + // MARK: Properties + + /// Returns a default `PropertyListEncoding` instance. + public static var `default`: PropertyListEncoding { return PropertyListEncoding() } + + /// Returns a `PropertyListEncoding` instance with xml formatting and default writing options. + public static var xml: PropertyListEncoding { return PropertyListEncoding(format: .xml) } + + /// Returns a `PropertyListEncoding` instance with binary formatting and default writing options. + public static var binary: PropertyListEncoding { return PropertyListEncoding(format: .binary) } + + /// The property list serialization format. + public let format: PropertyListSerialization.PropertyListFormat + + /// The options for writing the parameters as plist data. + public let options: PropertyListSerialization.WriteOptions + + // MARK: Initialization + + /// Creates a `PropertyListEncoding` instance using the specified format and options. + /// + /// - parameter format: The property list serialization format. + /// - parameter options: The options for writing the parameters as plist data. + /// + /// - returns: The new `PropertyListEncoding` instance. + public init( + format: PropertyListSerialization.PropertyListFormat = .xml, + options: PropertyListSerialization.WriteOptions = 0) + { + self.format = format + self.options = options + } + + // MARK: Encoding + + /// Creates a URL request by encoding parameters and applying them onto an existing request. + /// + /// - parameter urlRequest: The request to have parameters applied. + /// - parameter parameters: The parameters to apply. + /// + /// - throws: An `Error` if the encoding process encounters an error. + /// + /// - returns: The encoded request. + public func encode(_ urlRequest: URLRequestConvertible, with parameters: Parameters?) throws -> URLRequest { + var urlRequest = try urlRequest.asURLRequest() + + guard let parameters = parameters else { return urlRequest } + + do { + let data = try PropertyListSerialization.data( + fromPropertyList: parameters, + format: format, + options: options + ) + + if urlRequest.value(forHTTPHeaderField: "Content-Type") == nil { + urlRequest.setValue("application/x-plist", forHTTPHeaderField: "Content-Type") + } + + urlRequest.httpBody = data + } catch { + throw AFError.parameterEncodingFailed(reason: .propertyListEncodingFailed(error: error)) + } + + return urlRequest + } +} + +// MARK: - + +extension NSNumber { + fileprivate var isBool: Bool { return CFBooleanGetTypeID() == CFGetTypeID(self) } +} diff --git a/Pods/Alamofire/Source/Request.swift b/Pods/Alamofire/Source/Request.swift new file mode 100644 index 0000000..ea43411 --- /dev/null +++ b/Pods/Alamofire/Source/Request.swift @@ -0,0 +1,654 @@ +// +// Request.swift +// +// Copyright (c) 2014-2018 Alamofire Software Foundation (http://alamofire.org/) +// +// Permission is hereby granted, free of charge, to any person obtaining a copy +// of this software and associated documentation files (the "Software"), to deal +// in the Software without restriction, including without limitation the rights +// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +// copies of the Software, and to permit persons to whom the Software is +// furnished to do so, subject to the following conditions: +// +// The above copyright notice and this permission notice shall be included in +// all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN +// THE SOFTWARE. +// + +import Foundation + +/// A type that can inspect and optionally adapt a `URLRequest` in some manner if necessary. +public protocol RequestAdapter { + /// Inspects and adapts the specified `URLRequest` in some manner if necessary and returns the result. + /// + /// - parameter urlRequest: The URL request to adapt. + /// + /// - throws: An `Error` if the adaptation encounters an error. + /// + /// - returns: The adapted `URLRequest`. + func adapt(_ urlRequest: URLRequest) throws -> URLRequest +} + +// MARK: - + +/// A closure executed when the `RequestRetrier` determines whether a `Request` should be retried or not. +public typealias RequestRetryCompletion = (_ shouldRetry: Bool, _ timeDelay: TimeInterval) -> Void + +/// A type that determines whether a request should be retried after being executed by the specified session manager +/// and encountering an error. +public protocol RequestRetrier { + /// Determines whether the `Request` should be retried by calling the `completion` closure. + /// + /// This operation is fully asynchronous. Any amount of time can be taken to determine whether the request needs + /// to be retried. The one requirement is that the completion closure is called to ensure the request is properly + /// cleaned up after. + /// + /// - parameter manager: The session manager the request was executed on. + /// - parameter request: The request that failed due to the encountered error. + /// - parameter error: The error encountered when executing the request. + /// - parameter completion: The completion closure to be executed when retry decision has been determined. + func should(_ manager: SessionManager, retry request: Request, with error: Error, completion: @escaping RequestRetryCompletion) +} + +// MARK: - + +protocol TaskConvertible { + func task(session: URLSession, adapter: RequestAdapter?, queue: DispatchQueue) throws -> URLSessionTask +} + +/// A dictionary of headers to apply to a `URLRequest`. +public typealias HTTPHeaders = [String: String] + +// MARK: - + +/// Responsible for sending a request and receiving the response and associated data from the server, as well as +/// managing its underlying `URLSessionTask`. +open class Request { + + // MARK: Helper Types + + /// A closure executed when monitoring upload or download progress of a request. + public typealias ProgressHandler = (Progress) -> Void + + enum RequestTask { + case data(TaskConvertible?, URLSessionTask?) + case download(TaskConvertible?, URLSessionTask?) + case upload(TaskConvertible?, URLSessionTask?) + case stream(TaskConvertible?, URLSessionTask?) + } + + // MARK: Properties + + /// The delegate for the underlying task. + open internal(set) var delegate: TaskDelegate { + get { + taskDelegateLock.lock() ; defer { taskDelegateLock.unlock() } + return taskDelegate + } + set { + taskDelegateLock.lock() ; defer { taskDelegateLock.unlock() } + taskDelegate = newValue + } + } + + /// The underlying task. + open var task: URLSessionTask? { return delegate.task } + + /// The session belonging to the underlying task. + public let session: URLSession + + /// The request sent or to be sent to the server. + open var request: URLRequest? { return task?.originalRequest } + + /// The response received from the server, if any. + open var response: HTTPURLResponse? { return task?.response as? HTTPURLResponse } + + /// The number of times the request has been retried. + open internal(set) var retryCount: UInt = 0 + + let originalTask: TaskConvertible? + + var startTime: CFAbsoluteTime? + var endTime: CFAbsoluteTime? + + var validations: [() -> Void] = [] + + private var taskDelegate: TaskDelegate + private var taskDelegateLock = NSLock() + + // MARK: Lifecycle + + init(session: URLSession, requestTask: RequestTask, error: Error? = nil) { + self.session = session + + switch requestTask { + case .data(let originalTask, let task): + taskDelegate = DataTaskDelegate(task: task) + self.originalTask = originalTask + case .download(let originalTask, let task): + taskDelegate = DownloadTaskDelegate(task: task) + self.originalTask = originalTask + case .upload(let originalTask, let task): + taskDelegate = UploadTaskDelegate(task: task) + self.originalTask = originalTask + case .stream(let originalTask, let task): + taskDelegate = TaskDelegate(task: task) + self.originalTask = originalTask + } + + delegate.error = error + delegate.queue.addOperation { self.endTime = CFAbsoluteTimeGetCurrent() } + } + + // MARK: Authentication + + /// Associates an HTTP Basic credential with the request. + /// + /// - parameter user: The user. + /// - parameter password: The password. + /// - parameter persistence: The URL credential persistence. `.ForSession` by default. + /// + /// - returns: The request. + @discardableResult + open func authenticate( + user: String, + password: String, + persistence: URLCredential.Persistence = .forSession) + -> Self + { + let credential = URLCredential(user: user, password: password, persistence: persistence) + return authenticate(usingCredential: credential) + } + + /// Associates a specified credential with the request. + /// + /// - parameter credential: The credential. + /// + /// - returns: The request. + @discardableResult + open func authenticate(usingCredential credential: URLCredential) -> Self { + delegate.credential = credential + return self + } + + /// Returns a base64 encoded basic authentication credential as an authorization header tuple. + /// + /// - parameter user: The user. + /// - parameter password: The password. + /// + /// - returns: A tuple with Authorization header and credential value if encoding succeeds, `nil` otherwise. + open class func authorizationHeader(user: String, password: String) -> (key: String, value: String)? { + guard let data = "\(user):\(password)".data(using: .utf8) else { return nil } + + let credential = data.base64EncodedString(options: []) + + return (key: "Authorization", value: "Basic \(credential)") + } + + // MARK: State + + /// Resumes the request. + open func resume() { + guard let task = task else { delegate.queue.isSuspended = false ; return } + + if startTime == nil { startTime = CFAbsoluteTimeGetCurrent() } + + task.resume() + + NotificationCenter.default.post( + name: Notification.Name.Task.DidResume, + object: self, + userInfo: [Notification.Key.Task: task] + ) + } + + /// Suspends the request. + open func suspend() { + guard let task = task else { return } + + task.suspend() + + NotificationCenter.default.post( + name: Notification.Name.Task.DidSuspend, + object: self, + userInfo: [Notification.Key.Task: task] + ) + } + + /// Cancels the request. + open func cancel() { + guard let task = task else { return } + + task.cancel() + + NotificationCenter.default.post( + name: Notification.Name.Task.DidCancel, + object: self, + userInfo: [Notification.Key.Task: task] + ) + } +} + +// MARK: - CustomStringConvertible + +extension Request: CustomStringConvertible { + /// The textual representation used when written to an output stream, which includes the HTTP method and URL, as + /// well as the response status code if a response has been received. + open var description: String { + var components: [String] = [] + + if let HTTPMethod = request?.httpMethod { + components.append(HTTPMethod) + } + + if let urlString = request?.url?.absoluteString { + components.append(urlString) + } + + if let response = response { + components.append("(\(response.statusCode))") + } + + return components.joined(separator: " ") + } +} + +// MARK: - CustomDebugStringConvertible + +extension Request: CustomDebugStringConvertible { + /// The textual representation used when written to an output stream, in the form of a cURL command. + open var debugDescription: String { + return cURLRepresentation() + } + + func cURLRepresentation() -> String { + var components = ["$ curl -v"] + + guard let request = self.request, + let url = request.url, + let host = url.host + else { + return "$ curl command could not be created" + } + + if let httpMethod = request.httpMethod, httpMethod != "GET" { + components.append("-X \(httpMethod)") + } + + if let credentialStorage = self.session.configuration.urlCredentialStorage { + let protectionSpace = URLProtectionSpace( + host: host, + port: url.port ?? 0, + protocol: url.scheme, + realm: host, + authenticationMethod: NSURLAuthenticationMethodHTTPBasic + ) + + if let credentials = credentialStorage.credentials(for: protectionSpace)?.values { + for credential in credentials { + guard let user = credential.user, let password = credential.password else { continue } + components.append("-u \(user):\(password)") + } + } else { + if let credential = delegate.credential, let user = credential.user, let password = credential.password { + components.append("-u \(user):\(password)") + } + } + } + + if session.configuration.httpShouldSetCookies { + if + let cookieStorage = session.configuration.httpCookieStorage, + let cookies = cookieStorage.cookies(for: url), !cookies.isEmpty + { + let string = cookies.reduce("") { $0 + "\($1.name)=\($1.value);" } + + #if swift(>=3.2) + components.append("-b \"\(string[.. URLSessionTask { + do { + let urlRequest = try self.urlRequest.adapt(using: adapter) + return queue.sync { session.dataTask(with: urlRequest) } + } catch { + throw AdaptError(error: error) + } + } + } + + // MARK: Properties + + /// The request sent or to be sent to the server. + open override var request: URLRequest? { + if let request = super.request { return request } + if let requestable = originalTask as? Requestable { return requestable.urlRequest } + + return nil + } + + /// The progress of fetching the response data from the server for the request. + open var progress: Progress { return dataDelegate.progress } + + var dataDelegate: DataTaskDelegate { return delegate as! DataTaskDelegate } + + // MARK: Stream + + /// Sets a closure to be called periodically during the lifecycle of the request as data is read from the server. + /// + /// This closure returns the bytes most recently received from the server, not including data from previous calls. + /// If this closure is set, data will only be available within this closure, and will not be saved elsewhere. It is + /// also important to note that the server data in any `Response` object will be `nil`. + /// + /// - parameter closure: The code to be executed periodically during the lifecycle of the request. + /// + /// - returns: The request. + @discardableResult + open func stream(closure: ((Data) -> Void)? = nil) -> Self { + dataDelegate.dataStream = closure + return self + } + + // MARK: Progress + + /// Sets a closure to be called periodically during the lifecycle of the `Request` as data is read from the server. + /// + /// - parameter queue: The dispatch queue to execute the closure on. + /// - parameter closure: The code to be executed periodically as data is read from the server. + /// + /// - returns: The request. + @discardableResult + open func downloadProgress(queue: DispatchQueue = DispatchQueue.main, closure: @escaping ProgressHandler) -> Self { + dataDelegate.progressHandler = (closure, queue) + return self + } +} + +// MARK: - + +/// Specific type of `Request` that manages an underlying `URLSessionDownloadTask`. +open class DownloadRequest: Request { + + // MARK: Helper Types + + /// A collection of options to be executed prior to moving a downloaded file from the temporary URL to the + /// destination URL. + public struct DownloadOptions: OptionSet { + /// Returns the raw bitmask value of the option and satisfies the `RawRepresentable` protocol. + public let rawValue: UInt + + /// A `DownloadOptions` flag that creates intermediate directories for the destination URL if specified. + public static let createIntermediateDirectories = DownloadOptions(rawValue: 1 << 0) + + /// A `DownloadOptions` flag that removes a previous file from the destination URL if specified. + public static let removePreviousFile = DownloadOptions(rawValue: 1 << 1) + + /// Creates a `DownloadFileDestinationOptions` instance with the specified raw value. + /// + /// - parameter rawValue: The raw bitmask value for the option. + /// + /// - returns: A new log level instance. + public init(rawValue: UInt) { + self.rawValue = rawValue + } + } + + /// A closure executed once a download request has successfully completed in order to determine where to move the + /// temporary file written to during the download process. The closure takes two arguments: the temporary file URL + /// and the URL response, and returns a two arguments: the file URL where the temporary file should be moved and + /// the options defining how the file should be moved. + public typealias DownloadFileDestination = ( + _ temporaryURL: URL, + _ response: HTTPURLResponse) + -> (destinationURL: URL, options: DownloadOptions) + + enum Downloadable: TaskConvertible { + case request(URLRequest) + case resumeData(Data) + + func task(session: URLSession, adapter: RequestAdapter?, queue: DispatchQueue) throws -> URLSessionTask { + do { + let task: URLSessionTask + + switch self { + case let .request(urlRequest): + let urlRequest = try urlRequest.adapt(using: adapter) + task = queue.sync { session.downloadTask(with: urlRequest) } + case let .resumeData(resumeData): + task = queue.sync { session.downloadTask(withResumeData: resumeData) } + } + + return task + } catch { + throw AdaptError(error: error) + } + } + } + + // MARK: Properties + + /// The request sent or to be sent to the server. + open override var request: URLRequest? { + if let request = super.request { return request } + + if let downloadable = originalTask as? Downloadable, case let .request(urlRequest) = downloadable { + return urlRequest + } + + return nil + } + + /// The resume data of the underlying download task if available after a failure. + open var resumeData: Data? { return downloadDelegate.resumeData } + + /// The progress of downloading the response data from the server for the request. + open var progress: Progress { return downloadDelegate.progress } + + var downloadDelegate: DownloadTaskDelegate { return delegate as! DownloadTaskDelegate } + + // MARK: State + + /// Cancels the request. + open override func cancel() { + downloadDelegate.downloadTask.cancel { self.downloadDelegate.resumeData = $0 } + + NotificationCenter.default.post( + name: Notification.Name.Task.DidCancel, + object: self, + userInfo: [Notification.Key.Task: task as Any] + ) + } + + // MARK: Progress + + /// Sets a closure to be called periodically during the lifecycle of the `Request` as data is read from the server. + /// + /// - parameter queue: The dispatch queue to execute the closure on. + /// - parameter closure: The code to be executed periodically as data is read from the server. + /// + /// - returns: The request. + @discardableResult + open func downloadProgress(queue: DispatchQueue = DispatchQueue.main, closure: @escaping ProgressHandler) -> Self { + downloadDelegate.progressHandler = (closure, queue) + return self + } + + // MARK: Destination + + /// Creates a download file destination closure which uses the default file manager to move the temporary file to a + /// file URL in the first available directory with the specified search path directory and search path domain mask. + /// + /// - parameter directory: The search path directory. `.DocumentDirectory` by default. + /// - parameter domain: The search path domain mask. `.UserDomainMask` by default. + /// + /// - returns: A download file destination closure. + open class func suggestedDownloadDestination( + for directory: FileManager.SearchPathDirectory = .documentDirectory, + in domain: FileManager.SearchPathDomainMask = .userDomainMask) + -> DownloadFileDestination + { + return { temporaryURL, response in + let directoryURLs = FileManager.default.urls(for: directory, in: domain) + + if !directoryURLs.isEmpty { + return (directoryURLs[0].appendingPathComponent(response.suggestedFilename!), []) + } + + return (temporaryURL, []) + } + } +} + +// MARK: - + +/// Specific type of `Request` that manages an underlying `URLSessionUploadTask`. +open class UploadRequest: DataRequest { + + // MARK: Helper Types + + enum Uploadable: TaskConvertible { + case data(Data, URLRequest) + case file(URL, URLRequest) + case stream(InputStream, URLRequest) + + func task(session: URLSession, adapter: RequestAdapter?, queue: DispatchQueue) throws -> URLSessionTask { + do { + let task: URLSessionTask + + switch self { + case let .data(data, urlRequest): + let urlRequest = try urlRequest.adapt(using: adapter) + task = queue.sync { session.uploadTask(with: urlRequest, from: data) } + case let .file(url, urlRequest): + let urlRequest = try urlRequest.adapt(using: adapter) + task = queue.sync { session.uploadTask(with: urlRequest, fromFile: url) } + case let .stream(_, urlRequest): + let urlRequest = try urlRequest.adapt(using: adapter) + task = queue.sync { session.uploadTask(withStreamedRequest: urlRequest) } + } + + return task + } catch { + throw AdaptError(error: error) + } + } + } + + // MARK: Properties + + /// The request sent or to be sent to the server. + open override var request: URLRequest? { + if let request = super.request { return request } + + guard let uploadable = originalTask as? Uploadable else { return nil } + + switch uploadable { + case .data(_, let urlRequest), .file(_, let urlRequest), .stream(_, let urlRequest): + return urlRequest + } + } + + /// The progress of uploading the payload to the server for the upload request. + open var uploadProgress: Progress { return uploadDelegate.uploadProgress } + + var uploadDelegate: UploadTaskDelegate { return delegate as! UploadTaskDelegate } + + // MARK: Upload Progress + + /// Sets a closure to be called periodically during the lifecycle of the `UploadRequest` as data is sent to + /// the server. + /// + /// After the data is sent to the server, the `progress(queue:closure:)` APIs can be used to monitor the progress + /// of data being read from the server. + /// + /// - parameter queue: The dispatch queue to execute the closure on. + /// - parameter closure: The code to be executed periodically as data is sent to the server. + /// + /// - returns: The request. + @discardableResult + open func uploadProgress(queue: DispatchQueue = DispatchQueue.main, closure: @escaping ProgressHandler) -> Self { + uploadDelegate.uploadProgressHandler = (closure, queue) + return self + } +} + +// MARK: - + +#if !os(watchOS) + +/// Specific type of `Request` that manages an underlying `URLSessionStreamTask`. +@available(iOS 9.0, macOS 10.11, tvOS 9.0, *) +open class StreamRequest: Request { + enum Streamable: TaskConvertible { + case stream(hostName: String, port: Int) + case netService(NetService) + + func task(session: URLSession, adapter: RequestAdapter?, queue: DispatchQueue) throws -> URLSessionTask { + let task: URLSessionTask + + switch self { + case let .stream(hostName, port): + task = queue.sync { session.streamTask(withHostName: hostName, port: port) } + case let .netService(netService): + task = queue.sync { session.streamTask(with: netService) } + } + + return task + } + } +} + +#endif diff --git a/Pods/Alamofire/Source/Response.swift b/Pods/Alamofire/Source/Response.swift new file mode 100644 index 0000000..74b1ef5 --- /dev/null +++ b/Pods/Alamofire/Source/Response.swift @@ -0,0 +1,567 @@ +// +// Response.swift +// +// Copyright (c) 2014-2018 Alamofire Software Foundation (http://alamofire.org/) +// +// Permission is hereby granted, free of charge, to any person obtaining a copy +// of this software and associated documentation files (the "Software"), to deal +// in the Software without restriction, including without limitation the rights +// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +// copies of the Software, and to permit persons to whom the Software is +// furnished to do so, subject to the following conditions: +// +// The above copyright notice and this permission notice shall be included in +// all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN +// THE SOFTWARE. +// + +import Foundation + +/// Used to store all data associated with an non-serialized response of a data or upload request. +public struct DefaultDataResponse { + /// The URL request sent to the server. + public let request: URLRequest? + + /// The server's response to the URL request. + public let response: HTTPURLResponse? + + /// The data returned by the server. + public let data: Data? + + /// The error encountered while executing or validating the request. + public let error: Error? + + /// The timeline of the complete lifecycle of the request. + public let timeline: Timeline + + var _metrics: AnyObject? + + /// Creates a `DefaultDataResponse` instance from the specified parameters. + /// + /// - Parameters: + /// - request: The URL request sent to the server. + /// - response: The server's response to the URL request. + /// - data: The data returned by the server. + /// - error: The error encountered while executing or validating the request. + /// - timeline: The timeline of the complete lifecycle of the request. `Timeline()` by default. + /// - metrics: The task metrics containing the request / response statistics. `nil` by default. + public init( + request: URLRequest?, + response: HTTPURLResponse?, + data: Data?, + error: Error?, + timeline: Timeline = Timeline(), + metrics: AnyObject? = nil) + { + self.request = request + self.response = response + self.data = data + self.error = error + self.timeline = timeline + } +} + +// MARK: - + +/// Used to store all data associated with a serialized response of a data or upload request. +public struct DataResponse { + /// The URL request sent to the server. + public let request: URLRequest? + + /// The server's response to the URL request. + public let response: HTTPURLResponse? + + /// The data returned by the server. + public let data: Data? + + /// The result of response serialization. + public let result: Result + + /// The timeline of the complete lifecycle of the request. + public let timeline: Timeline + + /// Returns the associated value of the result if it is a success, `nil` otherwise. + public var value: Value? { return result.value } + + /// Returns the associated error value if the result if it is a failure, `nil` otherwise. + public var error: Error? { return result.error } + + var _metrics: AnyObject? + + /// Creates a `DataResponse` instance with the specified parameters derived from response serialization. + /// + /// - parameter request: The URL request sent to the server. + /// - parameter response: The server's response to the URL request. + /// - parameter data: The data returned by the server. + /// - parameter result: The result of response serialization. + /// - parameter timeline: The timeline of the complete lifecycle of the `Request`. Defaults to `Timeline()`. + /// + /// - returns: The new `DataResponse` instance. + public init( + request: URLRequest?, + response: HTTPURLResponse?, + data: Data?, + result: Result, + timeline: Timeline = Timeline()) + { + self.request = request + self.response = response + self.data = data + self.result = result + self.timeline = timeline + } +} + +// MARK: - + +extension DataResponse: CustomStringConvertible, CustomDebugStringConvertible { + /// The textual representation used when written to an output stream, which includes whether the result was a + /// success or failure. + public var description: String { + return result.debugDescription + } + + /// The debug textual representation used when written to an output stream, which includes the URL request, the URL + /// response, the server data, the response serialization result and the timeline. + public var debugDescription: String { + var output: [String] = [] + + output.append(request != nil ? "[Request]: \(request!.httpMethod ?? "GET") \(request!)" : "[Request]: nil") + output.append(response != nil ? "[Response]: \(response!)" : "[Response]: nil") + output.append("[Data]: \(data?.count ?? 0) bytes") + output.append("[Result]: \(result.debugDescription)") + output.append("[Timeline]: \(timeline.debugDescription)") + + return output.joined(separator: "\n") + } +} + +// MARK: - + +extension DataResponse { + /// Evaluates the specified closure when the result of this `DataResponse` is a success, passing the unwrapped + /// result value as a parameter. + /// + /// Use the `map` method with a closure that does not throw. For example: + /// + /// let possibleData: DataResponse = ... + /// let possibleInt = possibleData.map { $0.count } + /// + /// - parameter transform: A closure that takes the success value of the instance's result. + /// + /// - returns: A `DataResponse` whose result wraps the value returned by the given closure. If this instance's + /// result is a failure, returns a response wrapping the same failure. + public func map(_ transform: (Value) -> T) -> DataResponse { + var response = DataResponse( + request: request, + response: self.response, + data: data, + result: result.map(transform), + timeline: timeline + ) + + response._metrics = _metrics + + return response + } + + /// Evaluates the given closure when the result of this `DataResponse` is a success, passing the unwrapped result + /// value as a parameter. + /// + /// Use the `flatMap` method with a closure that may throw an error. For example: + /// + /// let possibleData: DataResponse = ... + /// let possibleObject = possibleData.flatMap { + /// try JSONSerialization.jsonObject(with: $0) + /// } + /// + /// - parameter transform: A closure that takes the success value of the instance's result. + /// + /// - returns: A success or failure `DataResponse` depending on the result of the given closure. If this instance's + /// result is a failure, returns the same failure. + public func flatMap(_ transform: (Value) throws -> T) -> DataResponse { + var response = DataResponse( + request: request, + response: self.response, + data: data, + result: result.flatMap(transform), + timeline: timeline + ) + + response._metrics = _metrics + + return response + } + + /// Evaluates the specified closure when the `DataResponse` is a failure, passing the unwrapped error as a parameter. + /// + /// Use the `mapError` function with a closure that does not throw. For example: + /// + /// let possibleData: DataResponse = ... + /// let withMyError = possibleData.mapError { MyError.error($0) } + /// + /// - Parameter transform: A closure that takes the error of the instance. + /// - Returns: A `DataResponse` instance containing the result of the transform. + public func mapError(_ transform: (Error) -> E) -> DataResponse { + var response = DataResponse( + request: request, + response: self.response, + data: data, + result: result.mapError(transform), + timeline: timeline + ) + + response._metrics = _metrics + + return response + } + + /// Evaluates the specified closure when the `DataResponse` is a failure, passing the unwrapped error as a parameter. + /// + /// Use the `flatMapError` function with a closure that may throw an error. For example: + /// + /// let possibleData: DataResponse = ... + /// let possibleObject = possibleData.flatMapError { + /// try someFailableFunction(taking: $0) + /// } + /// + /// - Parameter transform: A throwing closure that takes the error of the instance. + /// + /// - Returns: A `DataResponse` instance containing the result of the transform. + public func flatMapError(_ transform: (Error) throws -> E) -> DataResponse { + var response = DataResponse( + request: request, + response: self.response, + data: data, + result: result.flatMapError(transform), + timeline: timeline + ) + + response._metrics = _metrics + + return response + } +} + +// MARK: - + +/// Used to store all data associated with an non-serialized response of a download request. +public struct DefaultDownloadResponse { + /// The URL request sent to the server. + public let request: URLRequest? + + /// The server's response to the URL request. + public let response: HTTPURLResponse? + + /// The temporary destination URL of the data returned from the server. + public let temporaryURL: URL? + + /// The final destination URL of the data returned from the server if it was moved. + public let destinationURL: URL? + + /// The resume data generated if the request was cancelled. + public let resumeData: Data? + + /// The error encountered while executing or validating the request. + public let error: Error? + + /// The timeline of the complete lifecycle of the request. + public let timeline: Timeline + + var _metrics: AnyObject? + + /// Creates a `DefaultDownloadResponse` instance from the specified parameters. + /// + /// - Parameters: + /// - request: The URL request sent to the server. + /// - response: The server's response to the URL request. + /// - temporaryURL: The temporary destination URL of the data returned from the server. + /// - destinationURL: The final destination URL of the data returned from the server if it was moved. + /// - resumeData: The resume data generated if the request was cancelled. + /// - error: The error encountered while executing or validating the request. + /// - timeline: The timeline of the complete lifecycle of the request. `Timeline()` by default. + /// - metrics: The task metrics containing the request / response statistics. `nil` by default. + public init( + request: URLRequest?, + response: HTTPURLResponse?, + temporaryURL: URL?, + destinationURL: URL?, + resumeData: Data?, + error: Error?, + timeline: Timeline = Timeline(), + metrics: AnyObject? = nil) + { + self.request = request + self.response = response + self.temporaryURL = temporaryURL + self.destinationURL = destinationURL + self.resumeData = resumeData + self.error = error + self.timeline = timeline + } +} + +// MARK: - + +/// Used to store all data associated with a serialized response of a download request. +public struct DownloadResponse { + /// The URL request sent to the server. + public let request: URLRequest? + + /// The server's response to the URL request. + public let response: HTTPURLResponse? + + /// The temporary destination URL of the data returned from the server. + public let temporaryURL: URL? + + /// The final destination URL of the data returned from the server if it was moved. + public let destinationURL: URL? + + /// The resume data generated if the request was cancelled. + public let resumeData: Data? + + /// The result of response serialization. + public let result: Result + + /// The timeline of the complete lifecycle of the request. + public let timeline: Timeline + + /// Returns the associated value of the result if it is a success, `nil` otherwise. + public var value: Value? { return result.value } + + /// Returns the associated error value if the result if it is a failure, `nil` otherwise. + public var error: Error? { return result.error } + + var _metrics: AnyObject? + + /// Creates a `DownloadResponse` instance with the specified parameters derived from response serialization. + /// + /// - parameter request: The URL request sent to the server. + /// - parameter response: The server's response to the URL request. + /// - parameter temporaryURL: The temporary destination URL of the data returned from the server. + /// - parameter destinationURL: The final destination URL of the data returned from the server if it was moved. + /// - parameter resumeData: The resume data generated if the request was cancelled. + /// - parameter result: The result of response serialization. + /// - parameter timeline: The timeline of the complete lifecycle of the `Request`. Defaults to `Timeline()`. + /// + /// - returns: The new `DownloadResponse` instance. + public init( + request: URLRequest?, + response: HTTPURLResponse?, + temporaryURL: URL?, + destinationURL: URL?, + resumeData: Data?, + result: Result, + timeline: Timeline = Timeline()) + { + self.request = request + self.response = response + self.temporaryURL = temporaryURL + self.destinationURL = destinationURL + self.resumeData = resumeData + self.result = result + self.timeline = timeline + } +} + +// MARK: - + +extension DownloadResponse: CustomStringConvertible, CustomDebugStringConvertible { + /// The textual representation used when written to an output stream, which includes whether the result was a + /// success or failure. + public var description: String { + return result.debugDescription + } + + /// The debug textual representation used when written to an output stream, which includes the URL request, the URL + /// response, the temporary and destination URLs, the resume data, the response serialization result and the + /// timeline. + public var debugDescription: String { + var output: [String] = [] + + output.append(request != nil ? "[Request]: \(request!.httpMethod ?? "GET") \(request!)" : "[Request]: nil") + output.append(response != nil ? "[Response]: \(response!)" : "[Response]: nil") + output.append("[TemporaryURL]: \(temporaryURL?.path ?? "nil")") + output.append("[DestinationURL]: \(destinationURL?.path ?? "nil")") + output.append("[ResumeData]: \(resumeData?.count ?? 0) bytes") + output.append("[Result]: \(result.debugDescription)") + output.append("[Timeline]: \(timeline.debugDescription)") + + return output.joined(separator: "\n") + } +} + +// MARK: - + +extension DownloadResponse { + /// Evaluates the given closure when the result of this `DownloadResponse` is a success, passing the unwrapped + /// result value as a parameter. + /// + /// Use the `map` method with a closure that does not throw. For example: + /// + /// let possibleData: DownloadResponse = ... + /// let possibleInt = possibleData.map { $0.count } + /// + /// - parameter transform: A closure that takes the success value of the instance's result. + /// + /// - returns: A `DownloadResponse` whose result wraps the value returned by the given closure. If this instance's + /// result is a failure, returns a response wrapping the same failure. + public func map(_ transform: (Value) -> T) -> DownloadResponse { + var response = DownloadResponse( + request: request, + response: self.response, + temporaryURL: temporaryURL, + destinationURL: destinationURL, + resumeData: resumeData, + result: result.map(transform), + timeline: timeline + ) + + response._metrics = _metrics + + return response + } + + /// Evaluates the given closure when the result of this `DownloadResponse` is a success, passing the unwrapped + /// result value as a parameter. + /// + /// Use the `flatMap` method with a closure that may throw an error. For example: + /// + /// let possibleData: DownloadResponse = ... + /// let possibleObject = possibleData.flatMap { + /// try JSONSerialization.jsonObject(with: $0) + /// } + /// + /// - parameter transform: A closure that takes the success value of the instance's result. + /// + /// - returns: A success or failure `DownloadResponse` depending on the result of the given closure. If this + /// instance's result is a failure, returns the same failure. + public func flatMap(_ transform: (Value) throws -> T) -> DownloadResponse { + var response = DownloadResponse( + request: request, + response: self.response, + temporaryURL: temporaryURL, + destinationURL: destinationURL, + resumeData: resumeData, + result: result.flatMap(transform), + timeline: timeline + ) + + response._metrics = _metrics + + return response + } + + /// Evaluates the specified closure when the `DownloadResponse` is a failure, passing the unwrapped error as a parameter. + /// + /// Use the `mapError` function with a closure that does not throw. For example: + /// + /// let possibleData: DownloadResponse = ... + /// let withMyError = possibleData.mapError { MyError.error($0) } + /// + /// - Parameter transform: A closure that takes the error of the instance. + /// - Returns: A `DownloadResponse` instance containing the result of the transform. + public func mapError(_ transform: (Error) -> E) -> DownloadResponse { + var response = DownloadResponse( + request: request, + response: self.response, + temporaryURL: temporaryURL, + destinationURL: destinationURL, + resumeData: resumeData, + result: result.mapError(transform), + timeline: timeline + ) + + response._metrics = _metrics + + return response + } + + /// Evaluates the specified closure when the `DownloadResponse` is a failure, passing the unwrapped error as a parameter. + /// + /// Use the `flatMapError` function with a closure that may throw an error. For example: + /// + /// let possibleData: DownloadResponse = ... + /// let possibleObject = possibleData.flatMapError { + /// try someFailableFunction(taking: $0) + /// } + /// + /// - Parameter transform: A throwing closure that takes the error of the instance. + /// + /// - Returns: A `DownloadResponse` instance containing the result of the transform. + public func flatMapError(_ transform: (Error) throws -> E) -> DownloadResponse { + var response = DownloadResponse( + request: request, + response: self.response, + temporaryURL: temporaryURL, + destinationURL: destinationURL, + resumeData: resumeData, + result: result.flatMapError(transform), + timeline: timeline + ) + + response._metrics = _metrics + + return response + } +} + +// MARK: - + +protocol Response { + /// The task metrics containing the request / response statistics. + var _metrics: AnyObject? { get set } + mutating func add(_ metrics: AnyObject?) +} + +extension Response { + mutating func add(_ metrics: AnyObject?) { + #if !os(watchOS) + guard #available(iOS 10.0, macOS 10.12, tvOS 10.0, *) else { return } + guard let metrics = metrics as? URLSessionTaskMetrics else { return } + + _metrics = metrics + #endif + } +} + +// MARK: - + +@available(iOS 10.0, macOS 10.12, tvOS 10.0, *) +extension DefaultDataResponse: Response { +#if !os(watchOS) + /// The task metrics containing the request / response statistics. + public var metrics: URLSessionTaskMetrics? { return _metrics as? URLSessionTaskMetrics } +#endif +} + +@available(iOS 10.0, macOS 10.12, tvOS 10.0, *) +extension DataResponse: Response { +#if !os(watchOS) + /// The task metrics containing the request / response statistics. + public var metrics: URLSessionTaskMetrics? { return _metrics as? URLSessionTaskMetrics } +#endif +} + +@available(iOS 10.0, macOS 10.12, tvOS 10.0, *) +extension DefaultDownloadResponse: Response { +#if !os(watchOS) + /// The task metrics containing the request / response statistics. + public var metrics: URLSessionTaskMetrics? { return _metrics as? URLSessionTaskMetrics } +#endif +} + +@available(iOS 10.0, macOS 10.12, tvOS 10.0, *) +extension DownloadResponse: Response { +#if !os(watchOS) + /// The task metrics containing the request / response statistics. + public var metrics: URLSessionTaskMetrics? { return _metrics as? URLSessionTaskMetrics } +#endif +} diff --git a/Pods/Alamofire/Source/ResponseSerialization.swift b/Pods/Alamofire/Source/ResponseSerialization.swift new file mode 100644 index 0000000..3333726 --- /dev/null +++ b/Pods/Alamofire/Source/ResponseSerialization.swift @@ -0,0 +1,715 @@ +// +// ResponseSerialization.swift +// +// Copyright (c) 2014-2018 Alamofire Software Foundation (http://alamofire.org/) +// +// Permission is hereby granted, free of charge, to any person obtaining a copy +// of this software and associated documentation files (the "Software"), to deal +// in the Software without restriction, including without limitation the rights +// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +// copies of the Software, and to permit persons to whom the Software is +// furnished to do so, subject to the following conditions: +// +// The above copyright notice and this permission notice shall be included in +// all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN +// THE SOFTWARE. +// + +import Foundation + +/// The type in which all data response serializers must conform to in order to serialize a response. +public protocol DataResponseSerializerProtocol { + /// The type of serialized object to be created by this `DataResponseSerializerType`. + associatedtype SerializedObject + + /// A closure used by response handlers that takes a request, response, data and error and returns a result. + var serializeResponse: (URLRequest?, HTTPURLResponse?, Data?, Error?) -> Result { get } +} + +// MARK: - + +/// A generic `DataResponseSerializerType` used to serialize a request, response, and data into a serialized object. +public struct DataResponseSerializer: DataResponseSerializerProtocol { + /// The type of serialized object to be created by this `DataResponseSerializer`. + public typealias SerializedObject = Value + + /// A closure used by response handlers that takes a request, response, data and error and returns a result. + public var serializeResponse: (URLRequest?, HTTPURLResponse?, Data?, Error?) -> Result + + /// Initializes the `ResponseSerializer` instance with the given serialize response closure. + /// + /// - parameter serializeResponse: The closure used to serialize the response. + /// + /// - returns: The new generic response serializer instance. + public init(serializeResponse: @escaping (URLRequest?, HTTPURLResponse?, Data?, Error?) -> Result) { + self.serializeResponse = serializeResponse + } +} + +// MARK: - + +/// The type in which all download response serializers must conform to in order to serialize a response. +public protocol DownloadResponseSerializerProtocol { + /// The type of serialized object to be created by this `DownloadResponseSerializerType`. + associatedtype SerializedObject + + /// A closure used by response handlers that takes a request, response, url and error and returns a result. + var serializeResponse: (URLRequest?, HTTPURLResponse?, URL?, Error?) -> Result { get } +} + +// MARK: - + +/// A generic `DownloadResponseSerializerType` used to serialize a request, response, and data into a serialized object. +public struct DownloadResponseSerializer: DownloadResponseSerializerProtocol { + /// The type of serialized object to be created by this `DownloadResponseSerializer`. + public typealias SerializedObject = Value + + /// A closure used by response handlers that takes a request, response, url and error and returns a result. + public var serializeResponse: (URLRequest?, HTTPURLResponse?, URL?, Error?) -> Result + + /// Initializes the `ResponseSerializer` instance with the given serialize response closure. + /// + /// - parameter serializeResponse: The closure used to serialize the response. + /// + /// - returns: The new generic response serializer instance. + public init(serializeResponse: @escaping (URLRequest?, HTTPURLResponse?, URL?, Error?) -> Result) { + self.serializeResponse = serializeResponse + } +} + +// MARK: - Timeline + +extension Request { + var timeline: Timeline { + let requestStartTime = self.startTime ?? CFAbsoluteTimeGetCurrent() + let requestCompletedTime = self.endTime ?? CFAbsoluteTimeGetCurrent() + let initialResponseTime = self.delegate.initialResponseTime ?? requestCompletedTime + + return Timeline( + requestStartTime: requestStartTime, + initialResponseTime: initialResponseTime, + requestCompletedTime: requestCompletedTime, + serializationCompletedTime: CFAbsoluteTimeGetCurrent() + ) + } +} + +// MARK: - Default + +extension DataRequest { + /// Adds a handler to be called once the request has finished. + /// + /// - parameter queue: The queue on which the completion handler is dispatched. + /// - parameter completionHandler: The code to be executed once the request has finished. + /// + /// - returns: The request. + @discardableResult + public func response(queue: DispatchQueue? = nil, completionHandler: @escaping (DefaultDataResponse) -> Void) -> Self { + delegate.queue.addOperation { + (queue ?? DispatchQueue.main).async { + var dataResponse = DefaultDataResponse( + request: self.request, + response: self.response, + data: self.delegate.data, + error: self.delegate.error, + timeline: self.timeline + ) + + dataResponse.add(self.delegate.metrics) + + completionHandler(dataResponse) + } + } + + return self + } + + /// Adds a handler to be called once the request has finished. + /// + /// - parameter queue: The queue on which the completion handler is dispatched. + /// - parameter responseSerializer: The response serializer responsible for serializing the request, response, + /// and data. + /// - parameter completionHandler: The code to be executed once the request has finished. + /// + /// - returns: The request. + @discardableResult + public func response( + queue: DispatchQueue? = nil, + responseSerializer: T, + completionHandler: @escaping (DataResponse) -> Void) + -> Self + { + delegate.queue.addOperation { + let result = responseSerializer.serializeResponse( + self.request, + self.response, + self.delegate.data, + self.delegate.error + ) + + var dataResponse = DataResponse( + request: self.request, + response: self.response, + data: self.delegate.data, + result: result, + timeline: self.timeline + ) + + dataResponse.add(self.delegate.metrics) + + (queue ?? DispatchQueue.main).async { completionHandler(dataResponse) } + } + + return self + } +} + +extension DownloadRequest { + /// Adds a handler to be called once the request has finished. + /// + /// - parameter queue: The queue on which the completion handler is dispatched. + /// - parameter completionHandler: The code to be executed once the request has finished. + /// + /// - returns: The request. + @discardableResult + public func response( + queue: DispatchQueue? = nil, + completionHandler: @escaping (DefaultDownloadResponse) -> Void) + -> Self + { + delegate.queue.addOperation { + (queue ?? DispatchQueue.main).async { + var downloadResponse = DefaultDownloadResponse( + request: self.request, + response: self.response, + temporaryURL: self.downloadDelegate.temporaryURL, + destinationURL: self.downloadDelegate.destinationURL, + resumeData: self.downloadDelegate.resumeData, + error: self.downloadDelegate.error, + timeline: self.timeline + ) + + downloadResponse.add(self.delegate.metrics) + + completionHandler(downloadResponse) + } + } + + return self + } + + /// Adds a handler to be called once the request has finished. + /// + /// - parameter queue: The queue on which the completion handler is dispatched. + /// - parameter responseSerializer: The response serializer responsible for serializing the request, response, + /// and data contained in the destination url. + /// - parameter completionHandler: The code to be executed once the request has finished. + /// + /// - returns: The request. + @discardableResult + public func response( + queue: DispatchQueue? = nil, + responseSerializer: T, + completionHandler: @escaping (DownloadResponse) -> Void) + -> Self + { + delegate.queue.addOperation { + let result = responseSerializer.serializeResponse( + self.request, + self.response, + self.downloadDelegate.fileURL, + self.downloadDelegate.error + ) + + var downloadResponse = DownloadResponse( + request: self.request, + response: self.response, + temporaryURL: self.downloadDelegate.temporaryURL, + destinationURL: self.downloadDelegate.destinationURL, + resumeData: self.downloadDelegate.resumeData, + result: result, + timeline: self.timeline + ) + + downloadResponse.add(self.delegate.metrics) + + (queue ?? DispatchQueue.main).async { completionHandler(downloadResponse) } + } + + return self + } +} + +// MARK: - Data + +extension Request { + /// Returns a result data type that contains the response data as-is. + /// + /// - parameter response: The response from the server. + /// - parameter data: The data returned from the server. + /// - parameter error: The error already encountered if it exists. + /// + /// - returns: The result data type. + public static func serializeResponseData(response: HTTPURLResponse?, data: Data?, error: Error?) -> Result { + guard error == nil else { return .failure(error!) } + + if let response = response, emptyDataStatusCodes.contains(response.statusCode) { return .success(Data()) } + + guard let validData = data else { + return .failure(AFError.responseSerializationFailed(reason: .inputDataNil)) + } + + return .success(validData) + } +} + +extension DataRequest { + /// Creates a response serializer that returns the associated data as-is. + /// + /// - returns: A data response serializer. + public static func dataResponseSerializer() -> DataResponseSerializer { + return DataResponseSerializer { _, response, data, error in + return Request.serializeResponseData(response: response, data: data, error: error) + } + } + + /// Adds a handler to be called once the request has finished. + /// + /// - parameter completionHandler: The code to be executed once the request has finished. + /// + /// - returns: The request. + @discardableResult + public func responseData( + queue: DispatchQueue? = nil, + completionHandler: @escaping (DataResponse) -> Void) + -> Self + { + return response( + queue: queue, + responseSerializer: DataRequest.dataResponseSerializer(), + completionHandler: completionHandler + ) + } +} + +extension DownloadRequest { + /// Creates a response serializer that returns the associated data as-is. + /// + /// - returns: A data response serializer. + public static func dataResponseSerializer() -> DownloadResponseSerializer { + return DownloadResponseSerializer { _, response, fileURL, error in + guard error == nil else { return .failure(error!) } + + guard let fileURL = fileURL else { + return .failure(AFError.responseSerializationFailed(reason: .inputFileNil)) + } + + do { + let data = try Data(contentsOf: fileURL) + return Request.serializeResponseData(response: response, data: data, error: error) + } catch { + return .failure(AFError.responseSerializationFailed(reason: .inputFileReadFailed(at: fileURL))) + } + } + } + + /// Adds a handler to be called once the request has finished. + /// + /// - parameter completionHandler: The code to be executed once the request has finished. + /// + /// - returns: The request. + @discardableResult + public func responseData( + queue: DispatchQueue? = nil, + completionHandler: @escaping (DownloadResponse) -> Void) + -> Self + { + return response( + queue: queue, + responseSerializer: DownloadRequest.dataResponseSerializer(), + completionHandler: completionHandler + ) + } +} + +// MARK: - String + +extension Request { + /// Returns a result string type initialized from the response data with the specified string encoding. + /// + /// - parameter encoding: The string encoding. If `nil`, the string encoding will be determined from the server + /// response, falling back to the default HTTP default character set, ISO-8859-1. + /// - parameter response: The response from the server. + /// - parameter data: The data returned from the server. + /// - parameter error: The error already encountered if it exists. + /// + /// - returns: The result data type. + public static func serializeResponseString( + encoding: String.Encoding?, + response: HTTPURLResponse?, + data: Data?, + error: Error?) + -> Result + { + guard error == nil else { return .failure(error!) } + + if let response = response, emptyDataStatusCodes.contains(response.statusCode) { return .success("") } + + guard let validData = data else { + return .failure(AFError.responseSerializationFailed(reason: .inputDataNil)) + } + + var convertedEncoding = encoding + + if let encodingName = response?.textEncodingName as CFString?, convertedEncoding == nil { + convertedEncoding = String.Encoding(rawValue: CFStringConvertEncodingToNSStringEncoding( + CFStringConvertIANACharSetNameToEncoding(encodingName)) + ) + } + + let actualEncoding = convertedEncoding ?? .isoLatin1 + + if let string = String(data: validData, encoding: actualEncoding) { + return .success(string) + } else { + return .failure(AFError.responseSerializationFailed(reason: .stringSerializationFailed(encoding: actualEncoding))) + } + } +} + +extension DataRequest { + /// Creates a response serializer that returns a result string type initialized from the response data with + /// the specified string encoding. + /// + /// - parameter encoding: The string encoding. If `nil`, the string encoding will be determined from the server + /// response, falling back to the default HTTP default character set, ISO-8859-1. + /// + /// - returns: A string response serializer. + public static func stringResponseSerializer(encoding: String.Encoding? = nil) -> DataResponseSerializer { + return DataResponseSerializer { _, response, data, error in + return Request.serializeResponseString(encoding: encoding, response: response, data: data, error: error) + } + } + + /// Adds a handler to be called once the request has finished. + /// + /// - parameter encoding: The string encoding. If `nil`, the string encoding will be determined from the + /// server response, falling back to the default HTTP default character set, + /// ISO-8859-1. + /// - parameter completionHandler: A closure to be executed once the request has finished. + /// + /// - returns: The request. + @discardableResult + public func responseString( + queue: DispatchQueue? = nil, + encoding: String.Encoding? = nil, + completionHandler: @escaping (DataResponse) -> Void) + -> Self + { + return response( + queue: queue, + responseSerializer: DataRequest.stringResponseSerializer(encoding: encoding), + completionHandler: completionHandler + ) + } +} + +extension DownloadRequest { + /// Creates a response serializer that returns a result string type initialized from the response data with + /// the specified string encoding. + /// + /// - parameter encoding: The string encoding. If `nil`, the string encoding will be determined from the server + /// response, falling back to the default HTTP default character set, ISO-8859-1. + /// + /// - returns: A string response serializer. + public static func stringResponseSerializer(encoding: String.Encoding? = nil) -> DownloadResponseSerializer { + return DownloadResponseSerializer { _, response, fileURL, error in + guard error == nil else { return .failure(error!) } + + guard let fileURL = fileURL else { + return .failure(AFError.responseSerializationFailed(reason: .inputFileNil)) + } + + do { + let data = try Data(contentsOf: fileURL) + return Request.serializeResponseString(encoding: encoding, response: response, data: data, error: error) + } catch { + return .failure(AFError.responseSerializationFailed(reason: .inputFileReadFailed(at: fileURL))) + } + } + } + + /// Adds a handler to be called once the request has finished. + /// + /// - parameter encoding: The string encoding. If `nil`, the string encoding will be determined from the + /// server response, falling back to the default HTTP default character set, + /// ISO-8859-1. + /// - parameter completionHandler: A closure to be executed once the request has finished. + /// + /// - returns: The request. + @discardableResult + public func responseString( + queue: DispatchQueue? = nil, + encoding: String.Encoding? = nil, + completionHandler: @escaping (DownloadResponse) -> Void) + -> Self + { + return response( + queue: queue, + responseSerializer: DownloadRequest.stringResponseSerializer(encoding: encoding), + completionHandler: completionHandler + ) + } +} + +// MARK: - JSON + +extension Request { + /// Returns a JSON object contained in a result type constructed from the response data using `JSONSerialization` + /// with the specified reading options. + /// + /// - parameter options: The JSON serialization reading options. Defaults to `.allowFragments`. + /// - parameter response: The response from the server. + /// - parameter data: The data returned from the server. + /// - parameter error: The error already encountered if it exists. + /// + /// - returns: The result data type. + public static func serializeResponseJSON( + options: JSONSerialization.ReadingOptions, + response: HTTPURLResponse?, + data: Data?, + error: Error?) + -> Result + { + guard error == nil else { return .failure(error!) } + + if let response = response, emptyDataStatusCodes.contains(response.statusCode) { return .success(NSNull()) } + + guard let validData = data, validData.count > 0 else { + return .failure(AFError.responseSerializationFailed(reason: .inputDataNilOrZeroLength)) + } + + do { + let json = try JSONSerialization.jsonObject(with: validData, options: options) + return .success(json) + } catch { + return .failure(AFError.responseSerializationFailed(reason: .jsonSerializationFailed(error: error))) + } + } +} + +extension DataRequest { + /// Creates a response serializer that returns a JSON object result type constructed from the response data using + /// `JSONSerialization` with the specified reading options. + /// + /// - parameter options: The JSON serialization reading options. Defaults to `.allowFragments`. + /// + /// - returns: A JSON object response serializer. + public static func jsonResponseSerializer( + options: JSONSerialization.ReadingOptions = .allowFragments) + -> DataResponseSerializer + { + return DataResponseSerializer { _, response, data, error in + return Request.serializeResponseJSON(options: options, response: response, data: data, error: error) + } + } + + /// Adds a handler to be called once the request has finished. + /// + /// - parameter options: The JSON serialization reading options. Defaults to `.allowFragments`. + /// - parameter completionHandler: A closure to be executed once the request has finished. + /// + /// - returns: The request. + @discardableResult + public func responseJSON( + queue: DispatchQueue? = nil, + options: JSONSerialization.ReadingOptions = .allowFragments, + completionHandler: @escaping (DataResponse) -> Void) + -> Self + { + return response( + queue: queue, + responseSerializer: DataRequest.jsonResponseSerializer(options: options), + completionHandler: completionHandler + ) + } +} + +extension DownloadRequest { + /// Creates a response serializer that returns a JSON object result type constructed from the response data using + /// `JSONSerialization` with the specified reading options. + /// + /// - parameter options: The JSON serialization reading options. Defaults to `.allowFragments`. + /// + /// - returns: A JSON object response serializer. + public static func jsonResponseSerializer( + options: JSONSerialization.ReadingOptions = .allowFragments) + -> DownloadResponseSerializer + { + return DownloadResponseSerializer { _, response, fileURL, error in + guard error == nil else { return .failure(error!) } + + guard let fileURL = fileURL else { + return .failure(AFError.responseSerializationFailed(reason: .inputFileNil)) + } + + do { + let data = try Data(contentsOf: fileURL) + return Request.serializeResponseJSON(options: options, response: response, data: data, error: error) + } catch { + return .failure(AFError.responseSerializationFailed(reason: .inputFileReadFailed(at: fileURL))) + } + } + } + + /// Adds a handler to be called once the request has finished. + /// + /// - parameter options: The JSON serialization reading options. Defaults to `.allowFragments`. + /// - parameter completionHandler: A closure to be executed once the request has finished. + /// + /// - returns: The request. + @discardableResult + public func responseJSON( + queue: DispatchQueue? = nil, + options: JSONSerialization.ReadingOptions = .allowFragments, + completionHandler: @escaping (DownloadResponse) -> Void) + -> Self + { + return response( + queue: queue, + responseSerializer: DownloadRequest.jsonResponseSerializer(options: options), + completionHandler: completionHandler + ) + } +} + +// MARK: - Property List + +extension Request { + /// Returns a plist object contained in a result type constructed from the response data using + /// `PropertyListSerialization` with the specified reading options. + /// + /// - parameter options: The property list reading options. Defaults to `[]`. + /// - parameter response: The response from the server. + /// - parameter data: The data returned from the server. + /// - parameter error: The error already encountered if it exists. + /// + /// - returns: The result data type. + public static func serializeResponsePropertyList( + options: PropertyListSerialization.ReadOptions, + response: HTTPURLResponse?, + data: Data?, + error: Error?) + -> Result + { + guard error == nil else { return .failure(error!) } + + if let response = response, emptyDataStatusCodes.contains(response.statusCode) { return .success(NSNull()) } + + guard let validData = data, validData.count > 0 else { + return .failure(AFError.responseSerializationFailed(reason: .inputDataNilOrZeroLength)) + } + + do { + let plist = try PropertyListSerialization.propertyList(from: validData, options: options, format: nil) + return .success(plist) + } catch { + return .failure(AFError.responseSerializationFailed(reason: .propertyListSerializationFailed(error: error))) + } + } +} + +extension DataRequest { + /// Creates a response serializer that returns an object constructed from the response data using + /// `PropertyListSerialization` with the specified reading options. + /// + /// - parameter options: The property list reading options. Defaults to `[]`. + /// + /// - returns: A property list object response serializer. + public static func propertyListResponseSerializer( + options: PropertyListSerialization.ReadOptions = []) + -> DataResponseSerializer + { + return DataResponseSerializer { _, response, data, error in + return Request.serializeResponsePropertyList(options: options, response: response, data: data, error: error) + } + } + + /// Adds a handler to be called once the request has finished. + /// + /// - parameter options: The property list reading options. Defaults to `[]`. + /// - parameter completionHandler: A closure to be executed once the request has finished. + /// + /// - returns: The request. + @discardableResult + public func responsePropertyList( + queue: DispatchQueue? = nil, + options: PropertyListSerialization.ReadOptions = [], + completionHandler: @escaping (DataResponse) -> Void) + -> Self + { + return response( + queue: queue, + responseSerializer: DataRequest.propertyListResponseSerializer(options: options), + completionHandler: completionHandler + ) + } +} + +extension DownloadRequest { + /// Creates a response serializer that returns an object constructed from the response data using + /// `PropertyListSerialization` with the specified reading options. + /// + /// - parameter options: The property list reading options. Defaults to `[]`. + /// + /// - returns: A property list object response serializer. + public static func propertyListResponseSerializer( + options: PropertyListSerialization.ReadOptions = []) + -> DownloadResponseSerializer + { + return DownloadResponseSerializer { _, response, fileURL, error in + guard error == nil else { return .failure(error!) } + + guard let fileURL = fileURL else { + return .failure(AFError.responseSerializationFailed(reason: .inputFileNil)) + } + + do { + let data = try Data(contentsOf: fileURL) + return Request.serializeResponsePropertyList(options: options, response: response, data: data, error: error) + } catch { + return .failure(AFError.responseSerializationFailed(reason: .inputFileReadFailed(at: fileURL))) + } + } + } + + /// Adds a handler to be called once the request has finished. + /// + /// - parameter options: The property list reading options. Defaults to `[]`. + /// - parameter completionHandler: A closure to be executed once the request has finished. + /// + /// - returns: The request. + @discardableResult + public func responsePropertyList( + queue: DispatchQueue? = nil, + options: PropertyListSerialization.ReadOptions = [], + completionHandler: @escaping (DownloadResponse) -> Void) + -> Self + { + return response( + queue: queue, + responseSerializer: DownloadRequest.propertyListResponseSerializer(options: options), + completionHandler: completionHandler + ) + } +} + +/// A set of HTTP response status code that do not contain response data. +private let emptyDataStatusCodes: Set = [204, 205] diff --git a/Pods/Alamofire/Source/Result.swift b/Pods/Alamofire/Source/Result.swift new file mode 100644 index 0000000..df62e12 --- /dev/null +++ b/Pods/Alamofire/Source/Result.swift @@ -0,0 +1,300 @@ +// +// Result.swift +// +// Copyright (c) 2014-2018 Alamofire Software Foundation (http://alamofire.org/) +// +// Permission is hereby granted, free of charge, to any person obtaining a copy +// of this software and associated documentation files (the "Software"), to deal +// in the Software without restriction, including without limitation the rights +// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +// copies of the Software, and to permit persons to whom the Software is +// furnished to do so, subject to the following conditions: +// +// The above copyright notice and this permission notice shall be included in +// all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN +// THE SOFTWARE. +// + +import Foundation + +/// Used to represent whether a request was successful or encountered an error. +/// +/// - success: The request and all post processing operations were successful resulting in the serialization of the +/// provided associated value. +/// +/// - failure: The request encountered an error resulting in a failure. The associated values are the original data +/// provided by the server as well as the error that caused the failure. +public enum Result { + case success(Value) + case failure(Error) + + /// Returns `true` if the result is a success, `false` otherwise. + public var isSuccess: Bool { + switch self { + case .success: + return true + case .failure: + return false + } + } + + /// Returns `true` if the result is a failure, `false` otherwise. + public var isFailure: Bool { + return !isSuccess + } + + /// Returns the associated value if the result is a success, `nil` otherwise. + public var value: Value? { + switch self { + case .success(let value): + return value + case .failure: + return nil + } + } + + /// Returns the associated error value if the result is a failure, `nil` otherwise. + public var error: Error? { + switch self { + case .success: + return nil + case .failure(let error): + return error + } + } +} + +// MARK: - CustomStringConvertible + +extension Result: CustomStringConvertible { + /// The textual representation used when written to an output stream, which includes whether the result was a + /// success or failure. + public var description: String { + switch self { + case .success: + return "SUCCESS" + case .failure: + return "FAILURE" + } + } +} + +// MARK: - CustomDebugStringConvertible + +extension Result: CustomDebugStringConvertible { + /// The debug textual representation used when written to an output stream, which includes whether the result was a + /// success or failure in addition to the value or error. + public var debugDescription: String { + switch self { + case .success(let value): + return "SUCCESS: \(value)" + case .failure(let error): + return "FAILURE: \(error)" + } + } +} + +// MARK: - Functional APIs + +extension Result { + /// Creates a `Result` instance from the result of a closure. + /// + /// A failure result is created when the closure throws, and a success result is created when the closure + /// succeeds without throwing an error. + /// + /// func someString() throws -> String { ... } + /// + /// let result = Result(value: { + /// return try someString() + /// }) + /// + /// // The type of result is Result + /// + /// The trailing closure syntax is also supported: + /// + /// let result = Result { try someString() } + /// + /// - parameter value: The closure to execute and create the result for. + public init(value: () throws -> Value) { + do { + self = try .success(value()) + } catch { + self = .failure(error) + } + } + + /// Returns the success value, or throws the failure error. + /// + /// let possibleString: Result = .success("success") + /// try print(possibleString.unwrap()) + /// // Prints "success" + /// + /// let noString: Result = .failure(error) + /// try print(noString.unwrap()) + /// // Throws error + public func unwrap() throws -> Value { + switch self { + case .success(let value): + return value + case .failure(let error): + throw error + } + } + + /// Evaluates the specified closure when the `Result` is a success, passing the unwrapped value as a parameter. + /// + /// Use the `map` method with a closure that does not throw. For example: + /// + /// let possibleData: Result = .success(Data()) + /// let possibleInt = possibleData.map { $0.count } + /// try print(possibleInt.unwrap()) + /// // Prints "0" + /// + /// let noData: Result = .failure(error) + /// let noInt = noData.map { $0.count } + /// try print(noInt.unwrap()) + /// // Throws error + /// + /// - parameter transform: A closure that takes the success value of the `Result` instance. + /// + /// - returns: A `Result` containing the result of the given closure. If this instance is a failure, returns the + /// same failure. + public func map(_ transform: (Value) -> T) -> Result { + switch self { + case .success(let value): + return .success(transform(value)) + case .failure(let error): + return .failure(error) + } + } + + /// Evaluates the specified closure when the `Result` is a success, passing the unwrapped value as a parameter. + /// + /// Use the `flatMap` method with a closure that may throw an error. For example: + /// + /// let possibleData: Result = .success(Data(...)) + /// let possibleObject = possibleData.flatMap { + /// try JSONSerialization.jsonObject(with: $0) + /// } + /// + /// - parameter transform: A closure that takes the success value of the instance. + /// + /// - returns: A `Result` containing the result of the given closure. If this instance is a failure, returns the + /// same failure. + public func flatMap(_ transform: (Value) throws -> T) -> Result { + switch self { + case .success(let value): + do { + return try .success(transform(value)) + } catch { + return .failure(error) + } + case .failure(let error): + return .failure(error) + } + } + + /// Evaluates the specified closure when the `Result` is a failure, passing the unwrapped error as a parameter. + /// + /// Use the `mapError` function with a closure that does not throw. For example: + /// + /// let possibleData: Result = .failure(someError) + /// let withMyError: Result = possibleData.mapError { MyError.error($0) } + /// + /// - Parameter transform: A closure that takes the error of the instance. + /// - Returns: A `Result` instance containing the result of the transform. If this instance is a success, returns + /// the same instance. + public func mapError(_ transform: (Error) -> T) -> Result { + switch self { + case .failure(let error): + return .failure(transform(error)) + case .success: + return self + } + } + + /// Evaluates the specified closure when the `Result` is a failure, passing the unwrapped error as a parameter. + /// + /// Use the `flatMapError` function with a closure that may throw an error. For example: + /// + /// let possibleData: Result = .success(Data(...)) + /// let possibleObject = possibleData.flatMapError { + /// try someFailableFunction(taking: $0) + /// } + /// + /// - Parameter transform: A throwing closure that takes the error of the instance. + /// + /// - Returns: A `Result` instance containing the result of the transform. If this instance is a success, returns + /// the same instance. + public func flatMapError(_ transform: (Error) throws -> T) -> Result { + switch self { + case .failure(let error): + do { + return try .failure(transform(error)) + } catch { + return .failure(error) + } + case .success: + return self + } + } + + /// Evaluates the specified closure when the `Result` is a success, passing the unwrapped value as a parameter. + /// + /// Use the `withValue` function to evaluate the passed closure without modifying the `Result` instance. + /// + /// - Parameter closure: A closure that takes the success value of this instance. + /// - Returns: This `Result` instance, unmodified. + @discardableResult + public func withValue(_ closure: (Value) -> Void) -> Result { + if case let .success(value) = self { closure(value) } + + return self + } + + /// Evaluates the specified closure when the `Result` is a failure, passing the unwrapped error as a parameter. + /// + /// Use the `withError` function to evaluate the passed closure without modifying the `Result` instance. + /// + /// - Parameter closure: A closure that takes the success value of this instance. + /// - Returns: This `Result` instance, unmodified. + @discardableResult + public func withError(_ closure: (Error) -> Void) -> Result { + if case let .failure(error) = self { closure(error) } + + return self + } + + /// Evaluates the specified closure when the `Result` is a success. + /// + /// Use the `ifSuccess` function to evaluate the passed closure without modifying the `Result` instance. + /// + /// - Parameter closure: A `Void` closure. + /// - Returns: This `Result` instance, unmodified. + @discardableResult + public func ifSuccess(_ closure: () -> Void) -> Result { + if isSuccess { closure() } + + return self + } + + /// Evaluates the specified closure when the `Result` is a failure. + /// + /// Use the `ifFailure` function to evaluate the passed closure without modifying the `Result` instance. + /// + /// - Parameter closure: A `Void` closure. + /// - Returns: This `Result` instance, unmodified. + @discardableResult + public func ifFailure(_ closure: () -> Void) -> Result { + if isFailure { closure() } + + return self + } +} diff --git a/Pods/Alamofire/Source/ServerTrustPolicy.swift b/Pods/Alamofire/Source/ServerTrustPolicy.swift new file mode 100644 index 0000000..7f44c8d --- /dev/null +++ b/Pods/Alamofire/Source/ServerTrustPolicy.swift @@ -0,0 +1,307 @@ +// +// ServerTrustPolicy.swift +// +// Copyright (c) 2014-2018 Alamofire Software Foundation (http://alamofire.org/) +// +// Permission is hereby granted, free of charge, to any person obtaining a copy +// of this software and associated documentation files (the "Software"), to deal +// in the Software without restriction, including without limitation the rights +// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +// copies of the Software, and to permit persons to whom the Software is +// furnished to do so, subject to the following conditions: +// +// The above copyright notice and this permission notice shall be included in +// all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN +// THE SOFTWARE. +// + +import Foundation + +/// Responsible for managing the mapping of `ServerTrustPolicy` objects to a given host. +open class ServerTrustPolicyManager { + /// The dictionary of policies mapped to a particular host. + public let policies: [String: ServerTrustPolicy] + + /// Initializes the `ServerTrustPolicyManager` instance with the given policies. + /// + /// Since different servers and web services can have different leaf certificates, intermediate and even root + /// certficates, it is important to have the flexibility to specify evaluation policies on a per host basis. This + /// allows for scenarios such as using default evaluation for host1, certificate pinning for host2, public key + /// pinning for host3 and disabling evaluation for host4. + /// + /// - parameter policies: A dictionary of all policies mapped to a particular host. + /// + /// - returns: The new `ServerTrustPolicyManager` instance. + public init(policies: [String: ServerTrustPolicy]) { + self.policies = policies + } + + /// Returns the `ServerTrustPolicy` for the given host if applicable. + /// + /// By default, this method will return the policy that perfectly matches the given host. Subclasses could override + /// this method and implement more complex mapping implementations such as wildcards. + /// + /// - parameter host: The host to use when searching for a matching policy. + /// + /// - returns: The server trust policy for the given host if found. + open func serverTrustPolicy(forHost host: String) -> ServerTrustPolicy? { + return policies[host] + } +} + +// MARK: - + +extension URLSession { + private struct AssociatedKeys { + static var managerKey = "URLSession.ServerTrustPolicyManager" + } + + var serverTrustPolicyManager: ServerTrustPolicyManager? { + get { + return objc_getAssociatedObject(self, &AssociatedKeys.managerKey) as? ServerTrustPolicyManager + } + set (manager) { + objc_setAssociatedObject(self, &AssociatedKeys.managerKey, manager, .OBJC_ASSOCIATION_RETAIN_NONATOMIC) + } + } +} + +// MARK: - ServerTrustPolicy + +/// The `ServerTrustPolicy` evaluates the server trust generally provided by an `NSURLAuthenticationChallenge` when +/// connecting to a server over a secure HTTPS connection. The policy configuration then evaluates the server trust +/// with a given set of criteria to determine whether the server trust is valid and the connection should be made. +/// +/// Using pinned certificates or public keys for evaluation helps prevent man-in-the-middle (MITM) attacks and other +/// vulnerabilities. Applications dealing with sensitive customer data or financial information are strongly encouraged +/// to route all communication over an HTTPS connection with pinning enabled. +/// +/// - performDefaultEvaluation: Uses the default server trust evaluation while allowing you to control whether to +/// validate the host provided by the challenge. Applications are encouraged to always +/// validate the host in production environments to guarantee the validity of the server's +/// certificate chain. +/// +/// - performRevokedEvaluation: Uses the default and revoked server trust evaluations allowing you to control whether to +/// validate the host provided by the challenge as well as specify the revocation flags for +/// testing for revoked certificates. Apple platforms did not start testing for revoked +/// certificates automatically until iOS 10.1, macOS 10.12 and tvOS 10.1 which is +/// demonstrated in our TLS tests. Applications are encouraged to always validate the host +/// in production environments to guarantee the validity of the server's certificate chain. +/// +/// - pinCertificates: Uses the pinned certificates to validate the server trust. The server trust is +/// considered valid if one of the pinned certificates match one of the server certificates. +/// By validating both the certificate chain and host, certificate pinning provides a very +/// secure form of server trust validation mitigating most, if not all, MITM attacks. +/// Applications are encouraged to always validate the host and require a valid certificate +/// chain in production environments. +/// +/// - pinPublicKeys: Uses the pinned public keys to validate the server trust. The server trust is considered +/// valid if one of the pinned public keys match one of the server certificate public keys. +/// By validating both the certificate chain and host, public key pinning provides a very +/// secure form of server trust validation mitigating most, if not all, MITM attacks. +/// Applications are encouraged to always validate the host and require a valid certificate +/// chain in production environments. +/// +/// - disableEvaluation: Disables all evaluation which in turn will always consider any server trust as valid. +/// +/// - customEvaluation: Uses the associated closure to evaluate the validity of the server trust. +public enum ServerTrustPolicy { + case performDefaultEvaluation(validateHost: Bool) + case performRevokedEvaluation(validateHost: Bool, revocationFlags: CFOptionFlags) + case pinCertificates(certificates: [SecCertificate], validateCertificateChain: Bool, validateHost: Bool) + case pinPublicKeys(publicKeys: [SecKey], validateCertificateChain: Bool, validateHost: Bool) + case disableEvaluation + case customEvaluation((_ serverTrust: SecTrust, _ host: String) -> Bool) + + // MARK: - Bundle Location + + /// Returns all certificates within the given bundle with a `.cer` file extension. + /// + /// - parameter bundle: The bundle to search for all `.cer` files. + /// + /// - returns: All certificates within the given bundle. + public static func certificates(in bundle: Bundle = Bundle.main) -> [SecCertificate] { + var certificates: [SecCertificate] = [] + + let paths = Set([".cer", ".CER", ".crt", ".CRT", ".der", ".DER"].map { fileExtension in + bundle.paths(forResourcesOfType: fileExtension, inDirectory: nil) + }.joined()) + + for path in paths { + if + let certificateData = try? Data(contentsOf: URL(fileURLWithPath: path)) as CFData, + let certificate = SecCertificateCreateWithData(nil, certificateData) + { + certificates.append(certificate) + } + } + + return certificates + } + + /// Returns all public keys within the given bundle with a `.cer` file extension. + /// + /// - parameter bundle: The bundle to search for all `*.cer` files. + /// + /// - returns: All public keys within the given bundle. + public static func publicKeys(in bundle: Bundle = Bundle.main) -> [SecKey] { + var publicKeys: [SecKey] = [] + + for certificate in certificates(in: bundle) { + if let publicKey = publicKey(for: certificate) { + publicKeys.append(publicKey) + } + } + + return publicKeys + } + + // MARK: - Evaluation + + /// Evaluates whether the server trust is valid for the given host. + /// + /// - parameter serverTrust: The server trust to evaluate. + /// - parameter host: The host of the challenge protection space. + /// + /// - returns: Whether the server trust is valid. + public func evaluate(_ serverTrust: SecTrust, forHost host: String) -> Bool { + var serverTrustIsValid = false + + switch self { + case let .performDefaultEvaluation(validateHost): + let policy = SecPolicyCreateSSL(true, validateHost ? host as CFString : nil) + SecTrustSetPolicies(serverTrust, policy) + + serverTrustIsValid = trustIsValid(serverTrust) + case let .performRevokedEvaluation(validateHost, revocationFlags): + let defaultPolicy = SecPolicyCreateSSL(true, validateHost ? host as CFString : nil) + let revokedPolicy = SecPolicyCreateRevocation(revocationFlags) + SecTrustSetPolicies(serverTrust, [defaultPolicy, revokedPolicy] as CFTypeRef) + + serverTrustIsValid = trustIsValid(serverTrust) + case let .pinCertificates(pinnedCertificates, validateCertificateChain, validateHost): + if validateCertificateChain { + let policy = SecPolicyCreateSSL(true, validateHost ? host as CFString : nil) + SecTrustSetPolicies(serverTrust, policy) + + SecTrustSetAnchorCertificates(serverTrust, pinnedCertificates as CFArray) + SecTrustSetAnchorCertificatesOnly(serverTrust, true) + + serverTrustIsValid = trustIsValid(serverTrust) + } else { + let serverCertificatesDataArray = certificateData(for: serverTrust) + let pinnedCertificatesDataArray = certificateData(for: pinnedCertificates) + + outerLoop: for serverCertificateData in serverCertificatesDataArray { + for pinnedCertificateData in pinnedCertificatesDataArray { + if serverCertificateData == pinnedCertificateData { + serverTrustIsValid = true + break outerLoop + } + } + } + } + case let .pinPublicKeys(pinnedPublicKeys, validateCertificateChain, validateHost): + var certificateChainEvaluationPassed = true + + if validateCertificateChain { + let policy = SecPolicyCreateSSL(true, validateHost ? host as CFString : nil) + SecTrustSetPolicies(serverTrust, policy) + + certificateChainEvaluationPassed = trustIsValid(serverTrust) + } + + if certificateChainEvaluationPassed { + outerLoop: for serverPublicKey in ServerTrustPolicy.publicKeys(for: serverTrust) as [AnyObject] { + for pinnedPublicKey in pinnedPublicKeys as [AnyObject] { + if serverPublicKey.isEqual(pinnedPublicKey) { + serverTrustIsValid = true + break outerLoop + } + } + } + } + case .disableEvaluation: + serverTrustIsValid = true + case let .customEvaluation(closure): + serverTrustIsValid = closure(serverTrust, host) + } + + return serverTrustIsValid + } + + // MARK: - Private - Trust Validation + + private func trustIsValid(_ trust: SecTrust) -> Bool { + var isValid = false + + var result = SecTrustResultType.invalid + let status = SecTrustEvaluate(trust, &result) + + if status == errSecSuccess { + let unspecified = SecTrustResultType.unspecified + let proceed = SecTrustResultType.proceed + + + isValid = result == unspecified || result == proceed + } + + return isValid + } + + // MARK: - Private - Certificate Data + + private func certificateData(for trust: SecTrust) -> [Data] { + var certificates: [SecCertificate] = [] + + for index in 0.. [Data] { + return certificates.map { SecCertificateCopyData($0) as Data } + } + + // MARK: - Private - Public Key Extraction + + private static func publicKeys(for trust: SecTrust) -> [SecKey] { + var publicKeys: [SecKey] = [] + + for index in 0.. SecKey? { + var publicKey: SecKey? + + let policy = SecPolicyCreateBasicX509() + var trust: SecTrust? + let trustCreationStatus = SecTrustCreateWithCertificates(certificate, policy, &trust) + + if let trust = trust, trustCreationStatus == errSecSuccess { + publicKey = SecTrustCopyPublicKey(trust) + } + + return publicKey + } +} diff --git a/Pods/Alamofire/Source/SessionDelegate.swift b/Pods/Alamofire/Source/SessionDelegate.swift new file mode 100644 index 0000000..03bcb7c --- /dev/null +++ b/Pods/Alamofire/Source/SessionDelegate.swift @@ -0,0 +1,725 @@ +// +// SessionDelegate.swift +// +// Copyright (c) 2014-2018 Alamofire Software Foundation (http://alamofire.org/) +// +// Permission is hereby granted, free of charge, to any person obtaining a copy +// of this software and associated documentation files (the "Software"), to deal +// in the Software without restriction, including without limitation the rights +// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +// copies of the Software, and to permit persons to whom the Software is +// furnished to do so, subject to the following conditions: +// +// The above copyright notice and this permission notice shall be included in +// all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN +// THE SOFTWARE. +// + +import Foundation + +/// Responsible for handling all delegate callbacks for the underlying session. +open class SessionDelegate: NSObject { + + // MARK: URLSessionDelegate Overrides + + /// Overrides default behavior for URLSessionDelegate method `urlSession(_:didBecomeInvalidWithError:)`. + open var sessionDidBecomeInvalidWithError: ((URLSession, Error?) -> Void)? + + /// Overrides default behavior for URLSessionDelegate method `urlSession(_:didReceive:completionHandler:)`. + open var sessionDidReceiveChallenge: ((URLSession, URLAuthenticationChallenge) -> (URLSession.AuthChallengeDisposition, URLCredential?))? + + /// Overrides all behavior for URLSessionDelegate method `urlSession(_:didReceive:completionHandler:)` and requires the caller to call the `completionHandler`. + open var sessionDidReceiveChallengeWithCompletion: ((URLSession, URLAuthenticationChallenge, @escaping (URLSession.AuthChallengeDisposition, URLCredential?) -> Void) -> Void)? + + /// Overrides default behavior for URLSessionDelegate method `urlSessionDidFinishEvents(forBackgroundURLSession:)`. + open var sessionDidFinishEventsForBackgroundURLSession: ((URLSession) -> Void)? + + // MARK: URLSessionTaskDelegate Overrides + + /// Overrides default behavior for URLSessionTaskDelegate method `urlSession(_:task:willPerformHTTPRedirection:newRequest:completionHandler:)`. + open var taskWillPerformHTTPRedirection: ((URLSession, URLSessionTask, HTTPURLResponse, URLRequest) -> URLRequest?)? + + /// Overrides all behavior for URLSessionTaskDelegate method `urlSession(_:task:willPerformHTTPRedirection:newRequest:completionHandler:)` and + /// requires the caller to call the `completionHandler`. + open var taskWillPerformHTTPRedirectionWithCompletion: ((URLSession, URLSessionTask, HTTPURLResponse, URLRequest, @escaping (URLRequest?) -> Void) -> Void)? + + /// Overrides default behavior for URLSessionTaskDelegate method `urlSession(_:task:didReceive:completionHandler:)`. + open var taskDidReceiveChallenge: ((URLSession, URLSessionTask, URLAuthenticationChallenge) -> (URLSession.AuthChallengeDisposition, URLCredential?))? + + /// Overrides all behavior for URLSessionTaskDelegate method `urlSession(_:task:didReceive:completionHandler:)` and + /// requires the caller to call the `completionHandler`. + open var taskDidReceiveChallengeWithCompletion: ((URLSession, URLSessionTask, URLAuthenticationChallenge, @escaping (URLSession.AuthChallengeDisposition, URLCredential?) -> Void) -> Void)? + + /// Overrides default behavior for URLSessionTaskDelegate method `urlSession(_:task:needNewBodyStream:)`. + open var taskNeedNewBodyStream: ((URLSession, URLSessionTask) -> InputStream?)? + + /// Overrides all behavior for URLSessionTaskDelegate method `urlSession(_:task:needNewBodyStream:)` and + /// requires the caller to call the `completionHandler`. + open var taskNeedNewBodyStreamWithCompletion: ((URLSession, URLSessionTask, @escaping (InputStream?) -> Void) -> Void)? + + /// Overrides default behavior for URLSessionTaskDelegate method `urlSession(_:task:didSendBodyData:totalBytesSent:totalBytesExpectedToSend:)`. + open var taskDidSendBodyData: ((URLSession, URLSessionTask, Int64, Int64, Int64) -> Void)? + + /// Overrides default behavior for URLSessionTaskDelegate method `urlSession(_:task:didCompleteWithError:)`. + open var taskDidComplete: ((URLSession, URLSessionTask, Error?) -> Void)? + + // MARK: URLSessionDataDelegate Overrides + + /// Overrides default behavior for URLSessionDataDelegate method `urlSession(_:dataTask:didReceive:completionHandler:)`. + open var dataTaskDidReceiveResponse: ((URLSession, URLSessionDataTask, URLResponse) -> URLSession.ResponseDisposition)? + + /// Overrides all behavior for URLSessionDataDelegate method `urlSession(_:dataTask:didReceive:completionHandler:)` and + /// requires caller to call the `completionHandler`. + open var dataTaskDidReceiveResponseWithCompletion: ((URLSession, URLSessionDataTask, URLResponse, @escaping (URLSession.ResponseDisposition) -> Void) -> Void)? + + /// Overrides default behavior for URLSessionDataDelegate method `urlSession(_:dataTask:didBecome:)`. + open var dataTaskDidBecomeDownloadTask: ((URLSession, URLSessionDataTask, URLSessionDownloadTask) -> Void)? + + /// Overrides default behavior for URLSessionDataDelegate method `urlSession(_:dataTask:didReceive:)`. + open var dataTaskDidReceiveData: ((URLSession, URLSessionDataTask, Data) -> Void)? + + /// Overrides default behavior for URLSessionDataDelegate method `urlSession(_:dataTask:willCacheResponse:completionHandler:)`. + open var dataTaskWillCacheResponse: ((URLSession, URLSessionDataTask, CachedURLResponse) -> CachedURLResponse?)? + + /// Overrides all behavior for URLSessionDataDelegate method `urlSession(_:dataTask:willCacheResponse:completionHandler:)` and + /// requires caller to call the `completionHandler`. + open var dataTaskWillCacheResponseWithCompletion: ((URLSession, URLSessionDataTask, CachedURLResponse, @escaping (CachedURLResponse?) -> Void) -> Void)? + + // MARK: URLSessionDownloadDelegate Overrides + + /// Overrides default behavior for URLSessionDownloadDelegate method `urlSession(_:downloadTask:didFinishDownloadingTo:)`. + open var downloadTaskDidFinishDownloadingToURL: ((URLSession, URLSessionDownloadTask, URL) -> Void)? + + /// Overrides default behavior for URLSessionDownloadDelegate method `urlSession(_:downloadTask:didWriteData:totalBytesWritten:totalBytesExpectedToWrite:)`. + open var downloadTaskDidWriteData: ((URLSession, URLSessionDownloadTask, Int64, Int64, Int64) -> Void)? + + /// Overrides default behavior for URLSessionDownloadDelegate method `urlSession(_:downloadTask:didResumeAtOffset:expectedTotalBytes:)`. + open var downloadTaskDidResumeAtOffset: ((URLSession, URLSessionDownloadTask, Int64, Int64) -> Void)? + + // MARK: URLSessionStreamDelegate Overrides + +#if !os(watchOS) + + /// Overrides default behavior for URLSessionStreamDelegate method `urlSession(_:readClosedFor:)`. + @available(iOS 9.0, macOS 10.11, tvOS 9.0, *) + open var streamTaskReadClosed: ((URLSession, URLSessionStreamTask) -> Void)? { + get { + return _streamTaskReadClosed as? (URLSession, URLSessionStreamTask) -> Void + } + set { + _streamTaskReadClosed = newValue + } + } + + /// Overrides default behavior for URLSessionStreamDelegate method `urlSession(_:writeClosedFor:)`. + @available(iOS 9.0, macOS 10.11, tvOS 9.0, *) + open var streamTaskWriteClosed: ((URLSession, URLSessionStreamTask) -> Void)? { + get { + return _streamTaskWriteClosed as? (URLSession, URLSessionStreamTask) -> Void + } + set { + _streamTaskWriteClosed = newValue + } + } + + /// Overrides default behavior for URLSessionStreamDelegate method `urlSession(_:betterRouteDiscoveredFor:)`. + @available(iOS 9.0, macOS 10.11, tvOS 9.0, *) + open var streamTaskBetterRouteDiscovered: ((URLSession, URLSessionStreamTask) -> Void)? { + get { + return _streamTaskBetterRouteDiscovered as? (URLSession, URLSessionStreamTask) -> Void + } + set { + _streamTaskBetterRouteDiscovered = newValue + } + } + + /// Overrides default behavior for URLSessionStreamDelegate method `urlSession(_:streamTask:didBecome:outputStream:)`. + @available(iOS 9.0, macOS 10.11, tvOS 9.0, *) + open var streamTaskDidBecomeInputAndOutputStreams: ((URLSession, URLSessionStreamTask, InputStream, OutputStream) -> Void)? { + get { + return _streamTaskDidBecomeInputStream as? (URLSession, URLSessionStreamTask, InputStream, OutputStream) -> Void + } + set { + _streamTaskDidBecomeInputStream = newValue + } + } + + var _streamTaskReadClosed: Any? + var _streamTaskWriteClosed: Any? + var _streamTaskBetterRouteDiscovered: Any? + var _streamTaskDidBecomeInputStream: Any? + +#endif + + // MARK: Properties + + var retrier: RequestRetrier? + weak var sessionManager: SessionManager? + + var requests: [Int: Request] = [:] + private let lock = NSLock() + + /// Access the task delegate for the specified task in a thread-safe manner. + open subscript(task: URLSessionTask) -> Request? { + get { + lock.lock() ; defer { lock.unlock() } + return requests[task.taskIdentifier] + } + set { + lock.lock() ; defer { lock.unlock() } + requests[task.taskIdentifier] = newValue + } + } + + // MARK: Lifecycle + + /// Initializes the `SessionDelegate` instance. + /// + /// - returns: The new `SessionDelegate` instance. + public override init() { + super.init() + } + + // MARK: NSObject Overrides + + /// Returns a `Bool` indicating whether the `SessionDelegate` implements or inherits a method that can respond + /// to a specified message. + /// + /// - parameter selector: A selector that identifies a message. + /// + /// - returns: `true` if the receiver implements or inherits a method that can respond to selector, otherwise `false`. + open override func responds(to selector: Selector) -> Bool { + #if !os(macOS) + if selector == #selector(URLSessionDelegate.urlSessionDidFinishEvents(forBackgroundURLSession:)) { + return sessionDidFinishEventsForBackgroundURLSession != nil + } + #endif + + #if !os(watchOS) + if #available(iOS 9.0, macOS 10.11, tvOS 9.0, *) { + switch selector { + case #selector(URLSessionStreamDelegate.urlSession(_:readClosedFor:)): + return streamTaskReadClosed != nil + case #selector(URLSessionStreamDelegate.urlSession(_:writeClosedFor:)): + return streamTaskWriteClosed != nil + case #selector(URLSessionStreamDelegate.urlSession(_:betterRouteDiscoveredFor:)): + return streamTaskBetterRouteDiscovered != nil + case #selector(URLSessionStreamDelegate.urlSession(_:streamTask:didBecome:outputStream:)): + return streamTaskDidBecomeInputAndOutputStreams != nil + default: + break + } + } + #endif + + switch selector { + case #selector(URLSessionDelegate.urlSession(_:didBecomeInvalidWithError:)): + return sessionDidBecomeInvalidWithError != nil + case #selector(URLSessionDelegate.urlSession(_:didReceive:completionHandler:)): + return (sessionDidReceiveChallenge != nil || sessionDidReceiveChallengeWithCompletion != nil) + case #selector(URLSessionTaskDelegate.urlSession(_:task:willPerformHTTPRedirection:newRequest:completionHandler:)): + return (taskWillPerformHTTPRedirection != nil || taskWillPerformHTTPRedirectionWithCompletion != nil) + case #selector(URLSessionDataDelegate.urlSession(_:dataTask:didReceive:completionHandler:)): + return (dataTaskDidReceiveResponse != nil || dataTaskDidReceiveResponseWithCompletion != nil) + default: + return type(of: self).instancesRespond(to: selector) + } + } +} + +// MARK: - URLSessionDelegate + +extension SessionDelegate: URLSessionDelegate { + /// Tells the delegate that the session has been invalidated. + /// + /// - parameter session: The session object that was invalidated. + /// - parameter error: The error that caused invalidation, or nil if the invalidation was explicit. + open func urlSession(_ session: URLSession, didBecomeInvalidWithError error: Error?) { + sessionDidBecomeInvalidWithError?(session, error) + } + + /// Requests credentials from the delegate in response to a session-level authentication request from the + /// remote server. + /// + /// - parameter session: The session containing the task that requested authentication. + /// - parameter challenge: An object that contains the request for authentication. + /// - parameter completionHandler: A handler that your delegate method must call providing the disposition + /// and credential. + open func urlSession( + _ session: URLSession, + didReceive challenge: URLAuthenticationChallenge, + completionHandler: @escaping (URLSession.AuthChallengeDisposition, URLCredential?) -> Void) + { + guard sessionDidReceiveChallengeWithCompletion == nil else { + sessionDidReceiveChallengeWithCompletion?(session, challenge, completionHandler) + return + } + + var disposition: URLSession.AuthChallengeDisposition = .performDefaultHandling + var credential: URLCredential? + + if let sessionDidReceiveChallenge = sessionDidReceiveChallenge { + (disposition, credential) = sessionDidReceiveChallenge(session, challenge) + } else if challenge.protectionSpace.authenticationMethod == NSURLAuthenticationMethodServerTrust { + let host = challenge.protectionSpace.host + + if + let serverTrustPolicy = session.serverTrustPolicyManager?.serverTrustPolicy(forHost: host), + let serverTrust = challenge.protectionSpace.serverTrust + { + if serverTrustPolicy.evaluate(serverTrust, forHost: host) { + disposition = .useCredential + credential = URLCredential(trust: serverTrust) + } else { + disposition = .cancelAuthenticationChallenge + } + } + } + + completionHandler(disposition, credential) + } + +#if !os(macOS) + + /// Tells the delegate that all messages enqueued for a session have been delivered. + /// + /// - parameter session: The session that no longer has any outstanding requests. + open func urlSessionDidFinishEvents(forBackgroundURLSession session: URLSession) { + sessionDidFinishEventsForBackgroundURLSession?(session) + } + +#endif +} + +// MARK: - URLSessionTaskDelegate + +extension SessionDelegate: URLSessionTaskDelegate { + /// Tells the delegate that the remote server requested an HTTP redirect. + /// + /// - parameter session: The session containing the task whose request resulted in a redirect. + /// - parameter task: The task whose request resulted in a redirect. + /// - parameter response: An object containing the server’s response to the original request. + /// - parameter request: A URL request object filled out with the new location. + /// - parameter completionHandler: A closure that your handler should call with either the value of the request + /// parameter, a modified URL request object, or NULL to refuse the redirect and + /// return the body of the redirect response. + open func urlSession( + _ session: URLSession, + task: URLSessionTask, + willPerformHTTPRedirection response: HTTPURLResponse, + newRequest request: URLRequest, + completionHandler: @escaping (URLRequest?) -> Void) + { + guard taskWillPerformHTTPRedirectionWithCompletion == nil else { + taskWillPerformHTTPRedirectionWithCompletion?(session, task, response, request, completionHandler) + return + } + + var redirectRequest: URLRequest? = request + + if let taskWillPerformHTTPRedirection = taskWillPerformHTTPRedirection { + redirectRequest = taskWillPerformHTTPRedirection(session, task, response, request) + } + + completionHandler(redirectRequest) + } + + /// Requests credentials from the delegate in response to an authentication request from the remote server. + /// + /// - parameter session: The session containing the task whose request requires authentication. + /// - parameter task: The task whose request requires authentication. + /// - parameter challenge: An object that contains the request for authentication. + /// - parameter completionHandler: A handler that your delegate method must call providing the disposition + /// and credential. + open func urlSession( + _ session: URLSession, + task: URLSessionTask, + didReceive challenge: URLAuthenticationChallenge, + completionHandler: @escaping (URLSession.AuthChallengeDisposition, URLCredential?) -> Void) + { + guard taskDidReceiveChallengeWithCompletion == nil else { + taskDidReceiveChallengeWithCompletion?(session, task, challenge, completionHandler) + return + } + + if let taskDidReceiveChallenge = taskDidReceiveChallenge { + let result = taskDidReceiveChallenge(session, task, challenge) + completionHandler(result.0, result.1) + } else if let delegate = self[task]?.delegate { + delegate.urlSession( + session, + task: task, + didReceive: challenge, + completionHandler: completionHandler + ) + } else { + urlSession(session, didReceive: challenge, completionHandler: completionHandler) + } + } + + /// Tells the delegate when a task requires a new request body stream to send to the remote server. + /// + /// - parameter session: The session containing the task that needs a new body stream. + /// - parameter task: The task that needs a new body stream. + /// - parameter completionHandler: A completion handler that your delegate method should call with the new body stream. + open func urlSession( + _ session: URLSession, + task: URLSessionTask, + needNewBodyStream completionHandler: @escaping (InputStream?) -> Void) + { + guard taskNeedNewBodyStreamWithCompletion == nil else { + taskNeedNewBodyStreamWithCompletion?(session, task, completionHandler) + return + } + + if let taskNeedNewBodyStream = taskNeedNewBodyStream { + completionHandler(taskNeedNewBodyStream(session, task)) + } else if let delegate = self[task]?.delegate { + delegate.urlSession(session, task: task, needNewBodyStream: completionHandler) + } + } + + /// Periodically informs the delegate of the progress of sending body content to the server. + /// + /// - parameter session: The session containing the data task. + /// - parameter task: The data task. + /// - parameter bytesSent: The number of bytes sent since the last time this delegate method was called. + /// - parameter totalBytesSent: The total number of bytes sent so far. + /// - parameter totalBytesExpectedToSend: The expected length of the body data. + open func urlSession( + _ session: URLSession, + task: URLSessionTask, + didSendBodyData bytesSent: Int64, + totalBytesSent: Int64, + totalBytesExpectedToSend: Int64) + { + if let taskDidSendBodyData = taskDidSendBodyData { + taskDidSendBodyData(session, task, bytesSent, totalBytesSent, totalBytesExpectedToSend) + } else if let delegate = self[task]?.delegate as? UploadTaskDelegate { + delegate.URLSession( + session, + task: task, + didSendBodyData: bytesSent, + totalBytesSent: totalBytesSent, + totalBytesExpectedToSend: totalBytesExpectedToSend + ) + } + } + +#if !os(watchOS) + + /// Tells the delegate that the session finished collecting metrics for the task. + /// + /// - parameter session: The session collecting the metrics. + /// - parameter task: The task whose metrics have been collected. + /// - parameter metrics: The collected metrics. + @available(iOS 10.0, macOS 10.12, tvOS 10.0, *) + @objc(URLSession:task:didFinishCollectingMetrics:) + open func urlSession(_ session: URLSession, task: URLSessionTask, didFinishCollecting metrics: URLSessionTaskMetrics) { + self[task]?.delegate.metrics = metrics + } + +#endif + + /// Tells the delegate that the task finished transferring data. + /// + /// - parameter session: The session containing the task whose request finished transferring data. + /// - parameter task: The task whose request finished transferring data. + /// - parameter error: If an error occurred, an error object indicating how the transfer failed, otherwise nil. + open func urlSession(_ session: URLSession, task: URLSessionTask, didCompleteWithError error: Error?) { + /// Executed after it is determined that the request is not going to be retried + let completeTask: (URLSession, URLSessionTask, Error?) -> Void = { [weak self] session, task, error in + guard let strongSelf = self else { return } + + strongSelf.taskDidComplete?(session, task, error) + + strongSelf[task]?.delegate.urlSession(session, task: task, didCompleteWithError: error) + + var userInfo: [String: Any] = [Notification.Key.Task: task] + + if let data = (strongSelf[task]?.delegate as? DataTaskDelegate)?.data { + userInfo[Notification.Key.ResponseData] = data + } + + NotificationCenter.default.post( + name: Notification.Name.Task.DidComplete, + object: strongSelf, + userInfo: userInfo + ) + + strongSelf[task] = nil + } + + guard let request = self[task], let sessionManager = sessionManager else { + completeTask(session, task, error) + return + } + + // Run all validations on the request before checking if an error occurred + request.validations.forEach { $0() } + + // Determine whether an error has occurred + var error: Error? = error + + if request.delegate.error != nil { + error = request.delegate.error + } + + /// If an error occurred and the retrier is set, asynchronously ask the retrier if the request + /// should be retried. Otherwise, complete the task by notifying the task delegate. + if let retrier = retrier, let error = error { + retrier.should(sessionManager, retry: request, with: error) { [weak self] shouldRetry, timeDelay in + guard shouldRetry else { completeTask(session, task, error) ; return } + + DispatchQueue.utility.after(timeDelay) { [weak self] in + guard let strongSelf = self else { return } + + let retrySucceeded = strongSelf.sessionManager?.retry(request) ?? false + + if retrySucceeded, let task = request.task { + strongSelf[task] = request + return + } else { + completeTask(session, task, error) + } + } + } + } else { + completeTask(session, task, error) + } + } +} + +// MARK: - URLSessionDataDelegate + +extension SessionDelegate: URLSessionDataDelegate { + /// Tells the delegate that the data task received the initial reply (headers) from the server. + /// + /// - parameter session: The session containing the data task that received an initial reply. + /// - parameter dataTask: The data task that received an initial reply. + /// - parameter response: A URL response object populated with headers. + /// - parameter completionHandler: A completion handler that your code calls to continue the transfer, passing a + /// constant to indicate whether the transfer should continue as a data task or + /// should become a download task. + open func urlSession( + _ session: URLSession, + dataTask: URLSessionDataTask, + didReceive response: URLResponse, + completionHandler: @escaping (URLSession.ResponseDisposition) -> Void) + { + guard dataTaskDidReceiveResponseWithCompletion == nil else { + dataTaskDidReceiveResponseWithCompletion?(session, dataTask, response, completionHandler) + return + } + + var disposition: URLSession.ResponseDisposition = .allow + + if let dataTaskDidReceiveResponse = dataTaskDidReceiveResponse { + disposition = dataTaskDidReceiveResponse(session, dataTask, response) + } + + completionHandler(disposition) + } + + /// Tells the delegate that the data task was changed to a download task. + /// + /// - parameter session: The session containing the task that was replaced by a download task. + /// - parameter dataTask: The data task that was replaced by a download task. + /// - parameter downloadTask: The new download task that replaced the data task. + open func urlSession( + _ session: URLSession, + dataTask: URLSessionDataTask, + didBecome downloadTask: URLSessionDownloadTask) + { + if let dataTaskDidBecomeDownloadTask = dataTaskDidBecomeDownloadTask { + dataTaskDidBecomeDownloadTask(session, dataTask, downloadTask) + } else { + self[downloadTask]?.delegate = DownloadTaskDelegate(task: downloadTask) + } + } + + /// Tells the delegate that the data task has received some of the expected data. + /// + /// - parameter session: The session containing the data task that provided data. + /// - parameter dataTask: The data task that provided data. + /// - parameter data: A data object containing the transferred data. + open func urlSession(_ session: URLSession, dataTask: URLSessionDataTask, didReceive data: Data) { + if let dataTaskDidReceiveData = dataTaskDidReceiveData { + dataTaskDidReceiveData(session, dataTask, data) + } else if let delegate = self[dataTask]?.delegate as? DataTaskDelegate { + delegate.urlSession(session, dataTask: dataTask, didReceive: data) + } + } + + /// Asks the delegate whether the data (or upload) task should store the response in the cache. + /// + /// - parameter session: The session containing the data (or upload) task. + /// - parameter dataTask: The data (or upload) task. + /// - parameter proposedResponse: The default caching behavior. This behavior is determined based on the current + /// caching policy and the values of certain received headers, such as the Pragma + /// and Cache-Control headers. + /// - parameter completionHandler: A block that your handler must call, providing either the original proposed + /// response, a modified version of that response, or NULL to prevent caching the + /// response. If your delegate implements this method, it must call this completion + /// handler; otherwise, your app leaks memory. + open func urlSession( + _ session: URLSession, + dataTask: URLSessionDataTask, + willCacheResponse proposedResponse: CachedURLResponse, + completionHandler: @escaping (CachedURLResponse?) -> Void) + { + guard dataTaskWillCacheResponseWithCompletion == nil else { + dataTaskWillCacheResponseWithCompletion?(session, dataTask, proposedResponse, completionHandler) + return + } + + if let dataTaskWillCacheResponse = dataTaskWillCacheResponse { + completionHandler(dataTaskWillCacheResponse(session, dataTask, proposedResponse)) + } else if let delegate = self[dataTask]?.delegate as? DataTaskDelegate { + delegate.urlSession( + session, + dataTask: dataTask, + willCacheResponse: proposedResponse, + completionHandler: completionHandler + ) + } else { + completionHandler(proposedResponse) + } + } +} + +// MARK: - URLSessionDownloadDelegate + +extension SessionDelegate: URLSessionDownloadDelegate { + /// Tells the delegate that a download task has finished downloading. + /// + /// - parameter session: The session containing the download task that finished. + /// - parameter downloadTask: The download task that finished. + /// - parameter location: A file URL for the temporary file. Because the file is temporary, you must either + /// open the file for reading or move it to a permanent location in your app’s sandbox + /// container directory before returning from this delegate method. + open func urlSession( + _ session: URLSession, + downloadTask: URLSessionDownloadTask, + didFinishDownloadingTo location: URL) + { + if let downloadTaskDidFinishDownloadingToURL = downloadTaskDidFinishDownloadingToURL { + downloadTaskDidFinishDownloadingToURL(session, downloadTask, location) + } else if let delegate = self[downloadTask]?.delegate as? DownloadTaskDelegate { + delegate.urlSession(session, downloadTask: downloadTask, didFinishDownloadingTo: location) + } + } + + /// Periodically informs the delegate about the download’s progress. + /// + /// - parameter session: The session containing the download task. + /// - parameter downloadTask: The download task. + /// - parameter bytesWritten: The number of bytes transferred since the last time this delegate + /// method was called. + /// - parameter totalBytesWritten: The total number of bytes transferred so far. + /// - parameter totalBytesExpectedToWrite: The expected length of the file, as provided by the Content-Length + /// header. If this header was not provided, the value is + /// `NSURLSessionTransferSizeUnknown`. + open func urlSession( + _ session: URLSession, + downloadTask: URLSessionDownloadTask, + didWriteData bytesWritten: Int64, + totalBytesWritten: Int64, + totalBytesExpectedToWrite: Int64) + { + if let downloadTaskDidWriteData = downloadTaskDidWriteData { + downloadTaskDidWriteData(session, downloadTask, bytesWritten, totalBytesWritten, totalBytesExpectedToWrite) + } else if let delegate = self[downloadTask]?.delegate as? DownloadTaskDelegate { + delegate.urlSession( + session, + downloadTask: downloadTask, + didWriteData: bytesWritten, + totalBytesWritten: totalBytesWritten, + totalBytesExpectedToWrite: totalBytesExpectedToWrite + ) + } + } + + /// Tells the delegate that the download task has resumed downloading. + /// + /// - parameter session: The session containing the download task that finished. + /// - parameter downloadTask: The download task that resumed. See explanation in the discussion. + /// - parameter fileOffset: If the file's cache policy or last modified date prevents reuse of the + /// existing content, then this value is zero. Otherwise, this value is an + /// integer representing the number of bytes on disk that do not need to be + /// retrieved again. + /// - parameter expectedTotalBytes: The expected length of the file, as provided by the Content-Length header. + /// If this header was not provided, the value is NSURLSessionTransferSizeUnknown. + open func urlSession( + _ session: URLSession, + downloadTask: URLSessionDownloadTask, + didResumeAtOffset fileOffset: Int64, + expectedTotalBytes: Int64) + { + if let downloadTaskDidResumeAtOffset = downloadTaskDidResumeAtOffset { + downloadTaskDidResumeAtOffset(session, downloadTask, fileOffset, expectedTotalBytes) + } else if let delegate = self[downloadTask]?.delegate as? DownloadTaskDelegate { + delegate.urlSession( + session, + downloadTask: downloadTask, + didResumeAtOffset: fileOffset, + expectedTotalBytes: expectedTotalBytes + ) + } + } +} + +// MARK: - URLSessionStreamDelegate + +#if !os(watchOS) + +@available(iOS 9.0, macOS 10.11, tvOS 9.0, *) +extension SessionDelegate: URLSessionStreamDelegate { + /// Tells the delegate that the read side of the connection has been closed. + /// + /// - parameter session: The session. + /// - parameter streamTask: The stream task. + open func urlSession(_ session: URLSession, readClosedFor streamTask: URLSessionStreamTask) { + streamTaskReadClosed?(session, streamTask) + } + + /// Tells the delegate that the write side of the connection has been closed. + /// + /// - parameter session: The session. + /// - parameter streamTask: The stream task. + open func urlSession(_ session: URLSession, writeClosedFor streamTask: URLSessionStreamTask) { + streamTaskWriteClosed?(session, streamTask) + } + + /// Tells the delegate that the system has determined that a better route to the host is available. + /// + /// - parameter session: The session. + /// - parameter streamTask: The stream task. + open func urlSession(_ session: URLSession, betterRouteDiscoveredFor streamTask: URLSessionStreamTask) { + streamTaskBetterRouteDiscovered?(session, streamTask) + } + + /// Tells the delegate that the stream task has been completed and provides the unopened stream objects. + /// + /// - parameter session: The session. + /// - parameter streamTask: The stream task. + /// - parameter inputStream: The new input stream. + /// - parameter outputStream: The new output stream. + open func urlSession( + _ session: URLSession, + streamTask: URLSessionStreamTask, + didBecome inputStream: InputStream, + outputStream: OutputStream) + { + streamTaskDidBecomeInputAndOutputStreams?(session, streamTask, inputStream, outputStream) + } +} + +#endif diff --git a/Pods/Alamofire/Source/SessionManager.swift b/Pods/Alamofire/Source/SessionManager.swift new file mode 100644 index 0000000..8779efd --- /dev/null +++ b/Pods/Alamofire/Source/SessionManager.swift @@ -0,0 +1,896 @@ +// +// SessionManager.swift +// +// Copyright (c) 2014-2018 Alamofire Software Foundation (http://alamofire.org/) +// +// Permission is hereby granted, free of charge, to any person obtaining a copy +// of this software and associated documentation files (the "Software"), to deal +// in the Software without restriction, including without limitation the rights +// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +// copies of the Software, and to permit persons to whom the Software is +// furnished to do so, subject to the following conditions: +// +// The above copyright notice and this permission notice shall be included in +// all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN +// THE SOFTWARE. +// + +import Foundation + +/// Responsible for creating and managing `Request` objects, as well as their underlying `NSURLSession`. +open class SessionManager { + + // MARK: - Helper Types + + /// Defines whether the `MultipartFormData` encoding was successful and contains result of the encoding as + /// associated values. + /// + /// - Success: Represents a successful `MultipartFormData` encoding and contains the new `UploadRequest` along with + /// streaming information. + /// - Failure: Used to represent a failure in the `MultipartFormData` encoding and also contains the encoding + /// error. + public enum MultipartFormDataEncodingResult { + case success(request: UploadRequest, streamingFromDisk: Bool, streamFileURL: URL?) + case failure(Error) + } + + // MARK: - Properties + + /// A default instance of `SessionManager`, used by top-level Alamofire request methods, and suitable for use + /// directly for any ad hoc requests. + public static let `default`: SessionManager = { + let configuration = URLSessionConfiguration.default + configuration.httpAdditionalHeaders = SessionManager.defaultHTTPHeaders + + return SessionManager(configuration: configuration) + }() + + /// Creates default values for the "Accept-Encoding", "Accept-Language" and "User-Agent" headers. + public static let defaultHTTPHeaders: HTTPHeaders = { + // Accept-Encoding HTTP Header; see https://tools.ietf.org/html/rfc7230#section-4.2.3 + let acceptEncoding: String = "gzip;q=1.0, compress;q=0.5" + + // Accept-Language HTTP Header; see https://tools.ietf.org/html/rfc7231#section-5.3.5 + let acceptLanguage = Locale.preferredLanguages.prefix(6).enumerated().map { index, languageCode in + let quality = 1.0 - (Double(index) * 0.1) + return "\(languageCode);q=\(quality)" + }.joined(separator: ", ") + + // User-Agent Header; see https://tools.ietf.org/html/rfc7231#section-5.5.3 + // Example: `iOS Example/1.0 (org.alamofire.iOS-Example; build:1; iOS 10.0.0) Alamofire/4.0.0` + let userAgent: String = { + if let info = Bundle.main.infoDictionary { + let executable = info[kCFBundleExecutableKey as String] as? String ?? "Unknown" + let bundle = info[kCFBundleIdentifierKey as String] as? String ?? "Unknown" + let appVersion = info["CFBundleShortVersionString"] as? String ?? "Unknown" + let appBuild = info[kCFBundleVersionKey as String] as? String ?? "Unknown" + + let osNameVersion: String = { + let version = ProcessInfo.processInfo.operatingSystemVersion + let versionString = "\(version.majorVersion).\(version.minorVersion).\(version.patchVersion)" + + let osName: String = { + #if os(iOS) + return "iOS" + #elseif os(watchOS) + return "watchOS" + #elseif os(tvOS) + return "tvOS" + #elseif os(macOS) + return "OS X" + #elseif os(Linux) + return "Linux" + #else + return "Unknown" + #endif + }() + + return "\(osName) \(versionString)" + }() + + let alamofireVersion: String = { + guard + let afInfo = Bundle(for: SessionManager.self).infoDictionary, + let build = afInfo["CFBundleShortVersionString"] + else { return "Unknown" } + + return "Alamofire/\(build)" + }() + + return "\(executable)/\(appVersion) (\(bundle); build:\(appBuild); \(osNameVersion)) \(alamofireVersion)" + } + + return "Alamofire" + }() + + return [ + "Accept-Encoding": acceptEncoding, + "Accept-Language": acceptLanguage, + "User-Agent": userAgent + ] + }() + + /// Default memory threshold used when encoding `MultipartFormData` in bytes. + public static let multipartFormDataEncodingMemoryThreshold: UInt64 = 10_000_000 + + /// The underlying session. + public let session: URLSession + + /// The session delegate handling all the task and session delegate callbacks. + public let delegate: SessionDelegate + + /// Whether to start requests immediately after being constructed. `true` by default. + open var startRequestsImmediately: Bool = true + + /// The request adapter called each time a new request is created. + open var adapter: RequestAdapter? + + /// The request retrier called each time a request encounters an error to determine whether to retry the request. + open var retrier: RequestRetrier? { + get { return delegate.retrier } + set { delegate.retrier = newValue } + } + + /// The background completion handler closure provided by the UIApplicationDelegate + /// `application:handleEventsForBackgroundURLSession:completionHandler:` method. By setting the background + /// completion handler, the SessionDelegate `sessionDidFinishEventsForBackgroundURLSession` closure implementation + /// will automatically call the handler. + /// + /// If you need to handle your own events before the handler is called, then you need to override the + /// SessionDelegate `sessionDidFinishEventsForBackgroundURLSession` and manually call the handler when finished. + /// + /// `nil` by default. + open var backgroundCompletionHandler: (() -> Void)? + + let queue = DispatchQueue(label: "org.alamofire.session-manager." + UUID().uuidString) + + // MARK: - Lifecycle + + /// Creates an instance with the specified `configuration`, `delegate` and `serverTrustPolicyManager`. + /// + /// - parameter configuration: The configuration used to construct the managed session. + /// `URLSessionConfiguration.default` by default. + /// - parameter delegate: The delegate used when initializing the session. `SessionDelegate()` by + /// default. + /// - parameter serverTrustPolicyManager: The server trust policy manager to use for evaluating all server trust + /// challenges. `nil` by default. + /// + /// - returns: The new `SessionManager` instance. + public init( + configuration: URLSessionConfiguration = URLSessionConfiguration.default, + delegate: SessionDelegate = SessionDelegate(), + serverTrustPolicyManager: ServerTrustPolicyManager? = nil) + { + self.delegate = delegate + self.session = URLSession(configuration: configuration, delegate: delegate, delegateQueue: nil) + + commonInit(serverTrustPolicyManager: serverTrustPolicyManager) + } + + /// Creates an instance with the specified `session`, `delegate` and `serverTrustPolicyManager`. + /// + /// - parameter session: The URL session. + /// - parameter delegate: The delegate of the URL session. Must equal the URL session's delegate. + /// - parameter serverTrustPolicyManager: The server trust policy manager to use for evaluating all server trust + /// challenges. `nil` by default. + /// + /// - returns: The new `SessionManager` instance if the URL session's delegate matches; `nil` otherwise. + public init?( + session: URLSession, + delegate: SessionDelegate, + serverTrustPolicyManager: ServerTrustPolicyManager? = nil) + { + guard delegate === session.delegate else { return nil } + + self.delegate = delegate + self.session = session + + commonInit(serverTrustPolicyManager: serverTrustPolicyManager) + } + + private func commonInit(serverTrustPolicyManager: ServerTrustPolicyManager?) { + session.serverTrustPolicyManager = serverTrustPolicyManager + + delegate.sessionManager = self + + delegate.sessionDidFinishEventsForBackgroundURLSession = { [weak self] session in + guard let strongSelf = self else { return } + DispatchQueue.main.async { strongSelf.backgroundCompletionHandler?() } + } + } + + deinit { + session.invalidateAndCancel() + } + + // MARK: - Data Request + + /// Creates a `DataRequest` to retrieve the contents of the specified `url`, `method`, `parameters`, `encoding` + /// and `headers`. + /// + /// - parameter url: The URL. + /// - parameter method: The HTTP method. `.get` by default. + /// - parameter parameters: The parameters. `nil` by default. + /// - parameter encoding: The parameter encoding. `URLEncoding.default` by default. + /// - parameter headers: The HTTP headers. `nil` by default. + /// + /// - returns: The created `DataRequest`. + @discardableResult + open func request( + _ url: URLConvertible, + method: HTTPMethod = .get, + parameters: Parameters? = nil, + encoding: ParameterEncoding = URLEncoding.default, + headers: HTTPHeaders? = nil) + -> DataRequest + { + var originalRequest: URLRequest? + + do { + originalRequest = try URLRequest(url: url, method: method, headers: headers) + let encodedURLRequest = try encoding.encode(originalRequest!, with: parameters) + return request(encodedURLRequest) + } catch { + return request(originalRequest, failedWith: error) + } + } + + /// Creates a `DataRequest` to retrieve the contents of a URL based on the specified `urlRequest`. + /// + /// If `startRequestsImmediately` is `true`, the request will have `resume()` called before being returned. + /// + /// - parameter urlRequest: The URL request. + /// + /// - returns: The created `DataRequest`. + @discardableResult + open func request(_ urlRequest: URLRequestConvertible) -> DataRequest { + var originalRequest: URLRequest? + + do { + originalRequest = try urlRequest.asURLRequest() + let originalTask = DataRequest.Requestable(urlRequest: originalRequest!) + + let task = try originalTask.task(session: session, adapter: adapter, queue: queue) + let request = DataRequest(session: session, requestTask: .data(originalTask, task)) + + delegate[task] = request + + if startRequestsImmediately { request.resume() } + + return request + } catch { + return request(originalRequest, failedWith: error) + } + } + + // MARK: Private - Request Implementation + + private func request(_ urlRequest: URLRequest?, failedWith error: Error) -> DataRequest { + var requestTask: Request.RequestTask = .data(nil, nil) + + if let urlRequest = urlRequest { + let originalTask = DataRequest.Requestable(urlRequest: urlRequest) + requestTask = .data(originalTask, nil) + } + + let underlyingError = error.underlyingAdaptError ?? error + let request = DataRequest(session: session, requestTask: requestTask, error: underlyingError) + + if let retrier = retrier, error is AdaptError { + allowRetrier(retrier, toRetry: request, with: underlyingError) + } else { + if startRequestsImmediately { request.resume() } + } + + return request + } + + // MARK: - Download Request + + // MARK: URL Request + + /// Creates a `DownloadRequest` to retrieve the contents the specified `url`, `method`, `parameters`, `encoding`, + /// `headers` and save them to the `destination`. + /// + /// If `destination` is not specified, the contents will remain in the temporary location determined by the + /// underlying URL session. + /// + /// If `startRequestsImmediately` is `true`, the request will have `resume()` called before being returned. + /// + /// - parameter url: The URL. + /// - parameter method: The HTTP method. `.get` by default. + /// - parameter parameters: The parameters. `nil` by default. + /// - parameter encoding: The parameter encoding. `URLEncoding.default` by default. + /// - parameter headers: The HTTP headers. `nil` by default. + /// - parameter destination: The closure used to determine the destination of the downloaded file. `nil` by default. + /// + /// - returns: The created `DownloadRequest`. + @discardableResult + open func download( + _ url: URLConvertible, + method: HTTPMethod = .get, + parameters: Parameters? = nil, + encoding: ParameterEncoding = URLEncoding.default, + headers: HTTPHeaders? = nil, + to destination: DownloadRequest.DownloadFileDestination? = nil) + -> DownloadRequest + { + do { + let urlRequest = try URLRequest(url: url, method: method, headers: headers) + let encodedURLRequest = try encoding.encode(urlRequest, with: parameters) + return download(encodedURLRequest, to: destination) + } catch { + return download(nil, to: destination, failedWith: error) + } + } + + /// Creates a `DownloadRequest` to retrieve the contents of a URL based on the specified `urlRequest` and save + /// them to the `destination`. + /// + /// If `destination` is not specified, the contents will remain in the temporary location determined by the + /// underlying URL session. + /// + /// If `startRequestsImmediately` is `true`, the request will have `resume()` called before being returned. + /// + /// - parameter urlRequest: The URL request + /// - parameter destination: The closure used to determine the destination of the downloaded file. `nil` by default. + /// + /// - returns: The created `DownloadRequest`. + @discardableResult + open func download( + _ urlRequest: URLRequestConvertible, + to destination: DownloadRequest.DownloadFileDestination? = nil) + -> DownloadRequest + { + do { + let urlRequest = try urlRequest.asURLRequest() + return download(.request(urlRequest), to: destination) + } catch { + return download(nil, to: destination, failedWith: error) + } + } + + // MARK: Resume Data + + /// Creates a `DownloadRequest` from the `resumeData` produced from a previous request cancellation to retrieve + /// the contents of the original request and save them to the `destination`. + /// + /// If `destination` is not specified, the contents will remain in the temporary location determined by the + /// underlying URL session. + /// + /// If `startRequestsImmediately` is `true`, the request will have `resume()` called before being returned. + /// + /// On the latest release of all the Apple platforms (iOS 10, macOS 10.12, tvOS 10, watchOS 3), `resumeData` is broken + /// on background URL session configurations. There's an underlying bug in the `resumeData` generation logic where the + /// data is written incorrectly and will always fail to resume the download. For more information about the bug and + /// possible workarounds, please refer to the following Stack Overflow post: + /// + /// - http://stackoverflow.com/a/39347461/1342462 + /// + /// - parameter resumeData: The resume data. This is an opaque data blob produced by `URLSessionDownloadTask` + /// when a task is cancelled. See `URLSession -downloadTask(withResumeData:)` for + /// additional information. + /// - parameter destination: The closure used to determine the destination of the downloaded file. `nil` by default. + /// + /// - returns: The created `DownloadRequest`. + @discardableResult + open func download( + resumingWith resumeData: Data, + to destination: DownloadRequest.DownloadFileDestination? = nil) + -> DownloadRequest + { + return download(.resumeData(resumeData), to: destination) + } + + // MARK: Private - Download Implementation + + private func download( + _ downloadable: DownloadRequest.Downloadable, + to destination: DownloadRequest.DownloadFileDestination?) + -> DownloadRequest + { + do { + let task = try downloadable.task(session: session, adapter: adapter, queue: queue) + let download = DownloadRequest(session: session, requestTask: .download(downloadable, task)) + + download.downloadDelegate.destination = destination + + delegate[task] = download + + if startRequestsImmediately { download.resume() } + + return download + } catch { + return download(downloadable, to: destination, failedWith: error) + } + } + + private func download( + _ downloadable: DownloadRequest.Downloadable?, + to destination: DownloadRequest.DownloadFileDestination?, + failedWith error: Error) + -> DownloadRequest + { + var downloadTask: Request.RequestTask = .download(nil, nil) + + if let downloadable = downloadable { + downloadTask = .download(downloadable, nil) + } + + let underlyingError = error.underlyingAdaptError ?? error + + let download = DownloadRequest(session: session, requestTask: downloadTask, error: underlyingError) + download.downloadDelegate.destination = destination + + if let retrier = retrier, error is AdaptError { + allowRetrier(retrier, toRetry: download, with: underlyingError) + } else { + if startRequestsImmediately { download.resume() } + } + + return download + } + + // MARK: - Upload Request + + // MARK: File + + /// Creates an `UploadRequest` from the specified `url`, `method` and `headers` for uploading the `file`. + /// + /// If `startRequestsImmediately` is `true`, the request will have `resume()` called before being returned. + /// + /// - parameter file: The file to upload. + /// - parameter url: The URL. + /// - parameter method: The HTTP method. `.post` by default. + /// - parameter headers: The HTTP headers. `nil` by default. + /// + /// - returns: The created `UploadRequest`. + @discardableResult + open func upload( + _ fileURL: URL, + to url: URLConvertible, + method: HTTPMethod = .post, + headers: HTTPHeaders? = nil) + -> UploadRequest + { + do { + let urlRequest = try URLRequest(url: url, method: method, headers: headers) + return upload(fileURL, with: urlRequest) + } catch { + return upload(nil, failedWith: error) + } + } + + /// Creates a `UploadRequest` from the specified `urlRequest` for uploading the `file`. + /// + /// If `startRequestsImmediately` is `true`, the request will have `resume()` called before being returned. + /// + /// - parameter file: The file to upload. + /// - parameter urlRequest: The URL request. + /// + /// - returns: The created `UploadRequest`. + @discardableResult + open func upload(_ fileURL: URL, with urlRequest: URLRequestConvertible) -> UploadRequest { + do { + let urlRequest = try urlRequest.asURLRequest() + return upload(.file(fileURL, urlRequest)) + } catch { + return upload(nil, failedWith: error) + } + } + + // MARK: Data + + /// Creates an `UploadRequest` from the specified `url`, `method` and `headers` for uploading the `data`. + /// + /// If `startRequestsImmediately` is `true`, the request will have `resume()` called before being returned. + /// + /// - parameter data: The data to upload. + /// - parameter url: The URL. + /// - parameter method: The HTTP method. `.post` by default. + /// - parameter headers: The HTTP headers. `nil` by default. + /// + /// - returns: The created `UploadRequest`. + @discardableResult + open func upload( + _ data: Data, + to url: URLConvertible, + method: HTTPMethod = .post, + headers: HTTPHeaders? = nil) + -> UploadRequest + { + do { + let urlRequest = try URLRequest(url: url, method: method, headers: headers) + return upload(data, with: urlRequest) + } catch { + return upload(nil, failedWith: error) + } + } + + /// Creates an `UploadRequest` from the specified `urlRequest` for uploading the `data`. + /// + /// If `startRequestsImmediately` is `true`, the request will have `resume()` called before being returned. + /// + /// - parameter data: The data to upload. + /// - parameter urlRequest: The URL request. + /// + /// - returns: The created `UploadRequest`. + @discardableResult + open func upload(_ data: Data, with urlRequest: URLRequestConvertible) -> UploadRequest { + do { + let urlRequest = try urlRequest.asURLRequest() + return upload(.data(data, urlRequest)) + } catch { + return upload(nil, failedWith: error) + } + } + + // MARK: InputStream + + /// Creates an `UploadRequest` from the specified `url`, `method` and `headers` for uploading the `stream`. + /// + /// If `startRequestsImmediately` is `true`, the request will have `resume()` called before being returned. + /// + /// - parameter stream: The stream to upload. + /// - parameter url: The URL. + /// - parameter method: The HTTP method. `.post` by default. + /// - parameter headers: The HTTP headers. `nil` by default. + /// + /// - returns: The created `UploadRequest`. + @discardableResult + open func upload( + _ stream: InputStream, + to url: URLConvertible, + method: HTTPMethod = .post, + headers: HTTPHeaders? = nil) + -> UploadRequest + { + do { + let urlRequest = try URLRequest(url: url, method: method, headers: headers) + return upload(stream, with: urlRequest) + } catch { + return upload(nil, failedWith: error) + } + } + + /// Creates an `UploadRequest` from the specified `urlRequest` for uploading the `stream`. + /// + /// If `startRequestsImmediately` is `true`, the request will have `resume()` called before being returned. + /// + /// - parameter stream: The stream to upload. + /// - parameter urlRequest: The URL request. + /// + /// - returns: The created `UploadRequest`. + @discardableResult + open func upload(_ stream: InputStream, with urlRequest: URLRequestConvertible) -> UploadRequest { + do { + let urlRequest = try urlRequest.asURLRequest() + return upload(.stream(stream, urlRequest)) + } catch { + return upload(nil, failedWith: error) + } + } + + // MARK: MultipartFormData + + /// Encodes `multipartFormData` using `encodingMemoryThreshold` and calls `encodingCompletion` with new + /// `UploadRequest` using the `url`, `method` and `headers`. + /// + /// It is important to understand the memory implications of uploading `MultipartFormData`. If the cummulative + /// payload is small, encoding the data in-memory and directly uploading to a server is the by far the most + /// efficient approach. However, if the payload is too large, encoding the data in-memory could cause your app to + /// be terminated. Larger payloads must first be written to disk using input and output streams to keep the memory + /// footprint low, then the data can be uploaded as a stream from the resulting file. Streaming from disk MUST be + /// used for larger payloads such as video content. + /// + /// The `encodingMemoryThreshold` parameter allows Alamofire to automatically determine whether to encode in-memory + /// or stream from disk. If the content length of the `MultipartFormData` is below the `encodingMemoryThreshold`, + /// encoding takes place in-memory. If the content length exceeds the threshold, the data is streamed to disk + /// during the encoding process. Then the result is uploaded as data or as a stream depending on which encoding + /// technique was used. + /// + /// If `startRequestsImmediately` is `true`, the request will have `resume()` called before being returned. + /// + /// - parameter multipartFormData: The closure used to append body parts to the `MultipartFormData`. + /// - parameter encodingMemoryThreshold: The encoding memory threshold in bytes. + /// `multipartFormDataEncodingMemoryThreshold` by default. + /// - parameter url: The URL. + /// - parameter method: The HTTP method. `.post` by default. + /// - parameter headers: The HTTP headers. `nil` by default. + /// - parameter encodingCompletion: The closure called when the `MultipartFormData` encoding is complete. + open func upload( + multipartFormData: @escaping (MultipartFormData) -> Void, + usingThreshold encodingMemoryThreshold: UInt64 = SessionManager.multipartFormDataEncodingMemoryThreshold, + to url: URLConvertible, + method: HTTPMethod = .post, + headers: HTTPHeaders? = nil, + encodingCompletion: ((MultipartFormDataEncodingResult) -> Void)?) + { + do { + let urlRequest = try URLRequest(url: url, method: method, headers: headers) + + return upload( + multipartFormData: multipartFormData, + usingThreshold: encodingMemoryThreshold, + with: urlRequest, + encodingCompletion: encodingCompletion + ) + } catch { + DispatchQueue.main.async { encodingCompletion?(.failure(error)) } + } + } + + /// Encodes `multipartFormData` using `encodingMemoryThreshold` and calls `encodingCompletion` with new + /// `UploadRequest` using the `urlRequest`. + /// + /// It is important to understand the memory implications of uploading `MultipartFormData`. If the cummulative + /// payload is small, encoding the data in-memory and directly uploading to a server is the by far the most + /// efficient approach. However, if the payload is too large, encoding the data in-memory could cause your app to + /// be terminated. Larger payloads must first be written to disk using input and output streams to keep the memory + /// footprint low, then the data can be uploaded as a stream from the resulting file. Streaming from disk MUST be + /// used for larger payloads such as video content. + /// + /// The `encodingMemoryThreshold` parameter allows Alamofire to automatically determine whether to encode in-memory + /// or stream from disk. If the content length of the `MultipartFormData` is below the `encodingMemoryThreshold`, + /// encoding takes place in-memory. If the content length exceeds the threshold, the data is streamed to disk + /// during the encoding process. Then the result is uploaded as data or as a stream depending on which encoding + /// technique was used. + /// + /// If `startRequestsImmediately` is `true`, the request will have `resume()` called before being returned. + /// + /// - parameter multipartFormData: The closure used to append body parts to the `MultipartFormData`. + /// - parameter encodingMemoryThreshold: The encoding memory threshold in bytes. + /// `multipartFormDataEncodingMemoryThreshold` by default. + /// - parameter urlRequest: The URL request. + /// - parameter encodingCompletion: The closure called when the `MultipartFormData` encoding is complete. + open func upload( + multipartFormData: @escaping (MultipartFormData) -> Void, + usingThreshold encodingMemoryThreshold: UInt64 = SessionManager.multipartFormDataEncodingMemoryThreshold, + with urlRequest: URLRequestConvertible, + encodingCompletion: ((MultipartFormDataEncodingResult) -> Void)?) + { + DispatchQueue.global(qos: .utility).async { + let formData = MultipartFormData() + multipartFormData(formData) + + var tempFileURL: URL? + + do { + var urlRequestWithContentType = try urlRequest.asURLRequest() + urlRequestWithContentType.setValue(formData.contentType, forHTTPHeaderField: "Content-Type") + + let isBackgroundSession = self.session.configuration.identifier != nil + + if formData.contentLength < encodingMemoryThreshold && !isBackgroundSession { + let data = try formData.encode() + + let encodingResult = MultipartFormDataEncodingResult.success( + request: self.upload(data, with: urlRequestWithContentType), + streamingFromDisk: false, + streamFileURL: nil + ) + + DispatchQueue.main.async { encodingCompletion?(encodingResult) } + } else { + let fileManager = FileManager.default + let tempDirectoryURL = URL(fileURLWithPath: NSTemporaryDirectory()) + let directoryURL = tempDirectoryURL.appendingPathComponent("org.alamofire.manager/multipart.form.data") + let fileName = UUID().uuidString + let fileURL = directoryURL.appendingPathComponent(fileName) + + tempFileURL = fileURL + + var directoryError: Error? + + // Create directory inside serial queue to ensure two threads don't do this in parallel + self.queue.sync { + do { + try fileManager.createDirectory(at: directoryURL, withIntermediateDirectories: true, attributes: nil) + } catch { + directoryError = error + } + } + + if let directoryError = directoryError { throw directoryError } + + try formData.writeEncodedData(to: fileURL) + + let upload = self.upload(fileURL, with: urlRequestWithContentType) + + // Cleanup the temp file once the upload is complete + upload.delegate.queue.addOperation { + do { + try FileManager.default.removeItem(at: fileURL) + } catch { + // No-op + } + } + + DispatchQueue.main.async { + let encodingResult = MultipartFormDataEncodingResult.success( + request: upload, + streamingFromDisk: true, + streamFileURL: fileURL + ) + + encodingCompletion?(encodingResult) + } + } + } catch { + // Cleanup the temp file in the event that the multipart form data encoding failed + if let tempFileURL = tempFileURL { + do { + try FileManager.default.removeItem(at: tempFileURL) + } catch { + // No-op + } + } + + DispatchQueue.main.async { encodingCompletion?(.failure(error)) } + } + } + } + + // MARK: Private - Upload Implementation + + private func upload(_ uploadable: UploadRequest.Uploadable) -> UploadRequest { + do { + let task = try uploadable.task(session: session, adapter: adapter, queue: queue) + let upload = UploadRequest(session: session, requestTask: .upload(uploadable, task)) + + if case let .stream(inputStream, _) = uploadable { + upload.delegate.taskNeedNewBodyStream = { _, _ in inputStream } + } + + delegate[task] = upload + + if startRequestsImmediately { upload.resume() } + + return upload + } catch { + return upload(uploadable, failedWith: error) + } + } + + private func upload(_ uploadable: UploadRequest.Uploadable?, failedWith error: Error) -> UploadRequest { + var uploadTask: Request.RequestTask = .upload(nil, nil) + + if let uploadable = uploadable { + uploadTask = .upload(uploadable, nil) + } + + let underlyingError = error.underlyingAdaptError ?? error + let upload = UploadRequest(session: session, requestTask: uploadTask, error: underlyingError) + + if let retrier = retrier, error is AdaptError { + allowRetrier(retrier, toRetry: upload, with: underlyingError) + } else { + if startRequestsImmediately { upload.resume() } + } + + return upload + } + +#if !os(watchOS) + + // MARK: - Stream Request + + // MARK: Hostname and Port + + /// Creates a `StreamRequest` for bidirectional streaming using the `hostname` and `port`. + /// + /// If `startRequestsImmediately` is `true`, the request will have `resume()` called before being returned. + /// + /// - parameter hostName: The hostname of the server to connect to. + /// - parameter port: The port of the server to connect to. + /// + /// - returns: The created `StreamRequest`. + @discardableResult + @available(iOS 9.0, macOS 10.11, tvOS 9.0, *) + open func stream(withHostName hostName: String, port: Int) -> StreamRequest { + return stream(.stream(hostName: hostName, port: port)) + } + + // MARK: NetService + + /// Creates a `StreamRequest` for bidirectional streaming using the `netService`. + /// + /// If `startRequestsImmediately` is `true`, the request will have `resume()` called before being returned. + /// + /// - parameter netService: The net service used to identify the endpoint. + /// + /// - returns: The created `StreamRequest`. + @discardableResult + @available(iOS 9.0, macOS 10.11, tvOS 9.0, *) + open func stream(with netService: NetService) -> StreamRequest { + return stream(.netService(netService)) + } + + // MARK: Private - Stream Implementation + + @available(iOS 9.0, macOS 10.11, tvOS 9.0, *) + private func stream(_ streamable: StreamRequest.Streamable) -> StreamRequest { + do { + let task = try streamable.task(session: session, adapter: adapter, queue: queue) + let request = StreamRequest(session: session, requestTask: .stream(streamable, task)) + + delegate[task] = request + + if startRequestsImmediately { request.resume() } + + return request + } catch { + return stream(failedWith: error) + } + } + + @available(iOS 9.0, macOS 10.11, tvOS 9.0, *) + private func stream(failedWith error: Error) -> StreamRequest { + let stream = StreamRequest(session: session, requestTask: .stream(nil, nil), error: error) + if startRequestsImmediately { stream.resume() } + return stream + } + +#endif + + // MARK: - Internal - Retry Request + + func retry(_ request: Request) -> Bool { + guard let originalTask = request.originalTask else { return false } + + do { + let task = try originalTask.task(session: session, adapter: adapter, queue: queue) + + if let originalTask = request.task { + delegate[originalTask] = nil // removes the old request to avoid endless growth + } + + request.delegate.task = task // resets all task delegate data + + request.retryCount += 1 + request.startTime = CFAbsoluteTimeGetCurrent() + request.endTime = nil + + task.resume() + + return true + } catch { + request.delegate.error = error.underlyingAdaptError ?? error + return false + } + } + + private func allowRetrier(_ retrier: RequestRetrier, toRetry request: Request, with error: Error) { + DispatchQueue.utility.async { [weak self] in + guard let strongSelf = self else { return } + + retrier.should(strongSelf, retry: request, with: error) { shouldRetry, timeDelay in + guard let strongSelf = self else { return } + + guard shouldRetry else { + if strongSelf.startRequestsImmediately { request.resume() } + return + } + + DispatchQueue.utility.after(timeDelay) { + guard let strongSelf = self else { return } + + let retrySucceeded = strongSelf.retry(request) + + if retrySucceeded, let task = request.task { + strongSelf.delegate[task] = request + } else { + if strongSelf.startRequestsImmediately { request.resume() } + } + } + } + } + } +} diff --git a/Pods/Alamofire/Source/TaskDelegate.swift b/Pods/Alamofire/Source/TaskDelegate.swift new file mode 100644 index 0000000..8e19888 --- /dev/null +++ b/Pods/Alamofire/Source/TaskDelegate.swift @@ -0,0 +1,466 @@ +// +// TaskDelegate.swift +// +// Copyright (c) 2014-2018 Alamofire Software Foundation (http://alamofire.org/) +// +// Permission is hereby granted, free of charge, to any person obtaining a copy +// of this software and associated documentation files (the "Software"), to deal +// in the Software without restriction, including without limitation the rights +// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +// copies of the Software, and to permit persons to whom the Software is +// furnished to do so, subject to the following conditions: +// +// The above copyright notice and this permission notice shall be included in +// all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN +// THE SOFTWARE. +// + +import Foundation + +/// The task delegate is responsible for handling all delegate callbacks for the underlying task as well as +/// executing all operations attached to the serial operation queue upon task completion. +open class TaskDelegate: NSObject { + + // MARK: Properties + + /// The serial operation queue used to execute all operations after the task completes. + public let queue: OperationQueue + + /// The data returned by the server. + public var data: Data? { return nil } + + /// The error generated throughout the lifecyle of the task. + public var error: Error? + + var task: URLSessionTask? { + set { + taskLock.lock(); defer { taskLock.unlock() } + _task = newValue + } + get { + taskLock.lock(); defer { taskLock.unlock() } + return _task + } + } + + var initialResponseTime: CFAbsoluteTime? + var credential: URLCredential? + var metrics: AnyObject? // URLSessionTaskMetrics + + private var _task: URLSessionTask? { + didSet { reset() } + } + + private let taskLock = NSLock() + + // MARK: Lifecycle + + init(task: URLSessionTask?) { + _task = task + + self.queue = { + let operationQueue = OperationQueue() + + operationQueue.maxConcurrentOperationCount = 1 + operationQueue.isSuspended = true + operationQueue.qualityOfService = .utility + + return operationQueue + }() + } + + func reset() { + error = nil + initialResponseTime = nil + } + + // MARK: URLSessionTaskDelegate + + var taskWillPerformHTTPRedirection: ((URLSession, URLSessionTask, HTTPURLResponse, URLRequest) -> URLRequest?)? + var taskDidReceiveChallenge: ((URLSession, URLSessionTask, URLAuthenticationChallenge) -> (URLSession.AuthChallengeDisposition, URLCredential?))? + var taskNeedNewBodyStream: ((URLSession, URLSessionTask) -> InputStream?)? + var taskDidCompleteWithError: ((URLSession, URLSessionTask, Error?) -> Void)? + + @objc(URLSession:task:willPerformHTTPRedirection:newRequest:completionHandler:) + func urlSession( + _ session: URLSession, + task: URLSessionTask, + willPerformHTTPRedirection response: HTTPURLResponse, + newRequest request: URLRequest, + completionHandler: @escaping (URLRequest?) -> Void) + { + var redirectRequest: URLRequest? = request + + if let taskWillPerformHTTPRedirection = taskWillPerformHTTPRedirection { + redirectRequest = taskWillPerformHTTPRedirection(session, task, response, request) + } + + completionHandler(redirectRequest) + } + + @objc(URLSession:task:didReceiveChallenge:completionHandler:) + func urlSession( + _ session: URLSession, + task: URLSessionTask, + didReceive challenge: URLAuthenticationChallenge, + completionHandler: @escaping (URLSession.AuthChallengeDisposition, URLCredential?) -> Void) + { + var disposition: URLSession.AuthChallengeDisposition = .performDefaultHandling + var credential: URLCredential? + + if let taskDidReceiveChallenge = taskDidReceiveChallenge { + (disposition, credential) = taskDidReceiveChallenge(session, task, challenge) + } else if challenge.protectionSpace.authenticationMethod == NSURLAuthenticationMethodServerTrust { + let host = challenge.protectionSpace.host + + if + let serverTrustPolicy = session.serverTrustPolicyManager?.serverTrustPolicy(forHost: host), + let serverTrust = challenge.protectionSpace.serverTrust + { + if serverTrustPolicy.evaluate(serverTrust, forHost: host) { + disposition = .useCredential + credential = URLCredential(trust: serverTrust) + } else { + disposition = .cancelAuthenticationChallenge + } + } + } else { + if challenge.previousFailureCount > 0 { + disposition = .rejectProtectionSpace + } else { + credential = self.credential ?? session.configuration.urlCredentialStorage?.defaultCredential(for: challenge.protectionSpace) + + if credential != nil { + disposition = .useCredential + } + } + } + + completionHandler(disposition, credential) + } + + @objc(URLSession:task:needNewBodyStream:) + func urlSession( + _ session: URLSession, + task: URLSessionTask, + needNewBodyStream completionHandler: @escaping (InputStream?) -> Void) + { + var bodyStream: InputStream? + + if let taskNeedNewBodyStream = taskNeedNewBodyStream { + bodyStream = taskNeedNewBodyStream(session, task) + } + + completionHandler(bodyStream) + } + + @objc(URLSession:task:didCompleteWithError:) + func urlSession(_ session: URLSession, task: URLSessionTask, didCompleteWithError error: Error?) { + if let taskDidCompleteWithError = taskDidCompleteWithError { + taskDidCompleteWithError(session, task, error) + } else { + if let error = error { + if self.error == nil { self.error = error } + + if + let downloadDelegate = self as? DownloadTaskDelegate, + let resumeData = (error as NSError).userInfo[NSURLSessionDownloadTaskResumeData] as? Data + { + downloadDelegate.resumeData = resumeData + } + } + + queue.isSuspended = false + } + } +} + +// MARK: - + +class DataTaskDelegate: TaskDelegate, URLSessionDataDelegate { + + // MARK: Properties + + var dataTask: URLSessionDataTask { return task as! URLSessionDataTask } + + override var data: Data? { + if dataStream != nil { + return nil + } else { + return mutableData + } + } + + var progress: Progress + var progressHandler: (closure: Request.ProgressHandler, queue: DispatchQueue)? + + var dataStream: ((_ data: Data) -> Void)? + + private var totalBytesReceived: Int64 = 0 + private var mutableData: Data + + private var expectedContentLength: Int64? + + // MARK: Lifecycle + + override init(task: URLSessionTask?) { + mutableData = Data() + progress = Progress(totalUnitCount: 0) + + super.init(task: task) + } + + override func reset() { + super.reset() + + progress = Progress(totalUnitCount: 0) + totalBytesReceived = 0 + mutableData = Data() + expectedContentLength = nil + } + + // MARK: URLSessionDataDelegate + + var dataTaskDidReceiveResponse: ((URLSession, URLSessionDataTask, URLResponse) -> URLSession.ResponseDisposition)? + var dataTaskDidBecomeDownloadTask: ((URLSession, URLSessionDataTask, URLSessionDownloadTask) -> Void)? + var dataTaskDidReceiveData: ((URLSession, URLSessionDataTask, Data) -> Void)? + var dataTaskWillCacheResponse: ((URLSession, URLSessionDataTask, CachedURLResponse) -> CachedURLResponse?)? + + func urlSession( + _ session: URLSession, + dataTask: URLSessionDataTask, + didReceive response: URLResponse, + completionHandler: @escaping (URLSession.ResponseDisposition) -> Void) + { + var disposition: URLSession.ResponseDisposition = .allow + + expectedContentLength = response.expectedContentLength + + if let dataTaskDidReceiveResponse = dataTaskDidReceiveResponse { + disposition = dataTaskDidReceiveResponse(session, dataTask, response) + } + + completionHandler(disposition) + } + + func urlSession( + _ session: URLSession, + dataTask: URLSessionDataTask, + didBecome downloadTask: URLSessionDownloadTask) + { + dataTaskDidBecomeDownloadTask?(session, dataTask, downloadTask) + } + + func urlSession(_ session: URLSession, dataTask: URLSessionDataTask, didReceive data: Data) { + if initialResponseTime == nil { initialResponseTime = CFAbsoluteTimeGetCurrent() } + + if let dataTaskDidReceiveData = dataTaskDidReceiveData { + dataTaskDidReceiveData(session, dataTask, data) + } else { + if let dataStream = dataStream { + dataStream(data) + } else { + mutableData.append(data) + } + + let bytesReceived = Int64(data.count) + totalBytesReceived += bytesReceived + let totalBytesExpected = dataTask.response?.expectedContentLength ?? NSURLSessionTransferSizeUnknown + + progress.totalUnitCount = totalBytesExpected + progress.completedUnitCount = totalBytesReceived + + if let progressHandler = progressHandler { + progressHandler.queue.async { progressHandler.closure(self.progress) } + } + } + } + + func urlSession( + _ session: URLSession, + dataTask: URLSessionDataTask, + willCacheResponse proposedResponse: CachedURLResponse, + completionHandler: @escaping (CachedURLResponse?) -> Void) + { + var cachedResponse: CachedURLResponse? = proposedResponse + + if let dataTaskWillCacheResponse = dataTaskWillCacheResponse { + cachedResponse = dataTaskWillCacheResponse(session, dataTask, proposedResponse) + } + + completionHandler(cachedResponse) + } +} + +// MARK: - + +class DownloadTaskDelegate: TaskDelegate, URLSessionDownloadDelegate { + + // MARK: Properties + + var downloadTask: URLSessionDownloadTask { return task as! URLSessionDownloadTask } + + var progress: Progress + var progressHandler: (closure: Request.ProgressHandler, queue: DispatchQueue)? + + var resumeData: Data? + override var data: Data? { return resumeData } + + var destination: DownloadRequest.DownloadFileDestination? + + var temporaryURL: URL? + var destinationURL: URL? + + var fileURL: URL? { return destination != nil ? destinationURL : temporaryURL } + + // MARK: Lifecycle + + override init(task: URLSessionTask?) { + progress = Progress(totalUnitCount: 0) + super.init(task: task) + } + + override func reset() { + super.reset() + + progress = Progress(totalUnitCount: 0) + resumeData = nil + } + + // MARK: URLSessionDownloadDelegate + + var downloadTaskDidFinishDownloadingToURL: ((URLSession, URLSessionDownloadTask, URL) -> URL)? + var downloadTaskDidWriteData: ((URLSession, URLSessionDownloadTask, Int64, Int64, Int64) -> Void)? + var downloadTaskDidResumeAtOffset: ((URLSession, URLSessionDownloadTask, Int64, Int64) -> Void)? + + func urlSession( + _ session: URLSession, + downloadTask: URLSessionDownloadTask, + didFinishDownloadingTo location: URL) + { + temporaryURL = location + + guard + let destination = destination, + let response = downloadTask.response as? HTTPURLResponse + else { return } + + let result = destination(location, response) + let destinationURL = result.destinationURL + let options = result.options + + self.destinationURL = destinationURL + + do { + if options.contains(.removePreviousFile), FileManager.default.fileExists(atPath: destinationURL.path) { + try FileManager.default.removeItem(at: destinationURL) + } + + if options.contains(.createIntermediateDirectories) { + let directory = destinationURL.deletingLastPathComponent() + try FileManager.default.createDirectory(at: directory, withIntermediateDirectories: true) + } + + try FileManager.default.moveItem(at: location, to: destinationURL) + } catch { + self.error = error + } + } + + func urlSession( + _ session: URLSession, + downloadTask: URLSessionDownloadTask, + didWriteData bytesWritten: Int64, + totalBytesWritten: Int64, + totalBytesExpectedToWrite: Int64) + { + if initialResponseTime == nil { initialResponseTime = CFAbsoluteTimeGetCurrent() } + + if let downloadTaskDidWriteData = downloadTaskDidWriteData { + downloadTaskDidWriteData( + session, + downloadTask, + bytesWritten, + totalBytesWritten, + totalBytesExpectedToWrite + ) + } else { + progress.totalUnitCount = totalBytesExpectedToWrite + progress.completedUnitCount = totalBytesWritten + + if let progressHandler = progressHandler { + progressHandler.queue.async { progressHandler.closure(self.progress) } + } + } + } + + func urlSession( + _ session: URLSession, + downloadTask: URLSessionDownloadTask, + didResumeAtOffset fileOffset: Int64, + expectedTotalBytes: Int64) + { + if let downloadTaskDidResumeAtOffset = downloadTaskDidResumeAtOffset { + downloadTaskDidResumeAtOffset(session, downloadTask, fileOffset, expectedTotalBytes) + } else { + progress.totalUnitCount = expectedTotalBytes + progress.completedUnitCount = fileOffset + } + } +} + +// MARK: - + +class UploadTaskDelegate: DataTaskDelegate { + + // MARK: Properties + + var uploadTask: URLSessionUploadTask { return task as! URLSessionUploadTask } + + var uploadProgress: Progress + var uploadProgressHandler: (closure: Request.ProgressHandler, queue: DispatchQueue)? + + // MARK: Lifecycle + + override init(task: URLSessionTask?) { + uploadProgress = Progress(totalUnitCount: 0) + super.init(task: task) + } + + override func reset() { + super.reset() + uploadProgress = Progress(totalUnitCount: 0) + } + + // MARK: URLSessionTaskDelegate + + var taskDidSendBodyData: ((URLSession, URLSessionTask, Int64, Int64, Int64) -> Void)? + + func URLSession( + _ session: URLSession, + task: URLSessionTask, + didSendBodyData bytesSent: Int64, + totalBytesSent: Int64, + totalBytesExpectedToSend: Int64) + { + if initialResponseTime == nil { initialResponseTime = CFAbsoluteTimeGetCurrent() } + + if let taskDidSendBodyData = taskDidSendBodyData { + taskDidSendBodyData(session, task, bytesSent, totalBytesSent, totalBytesExpectedToSend) + } else { + uploadProgress.totalUnitCount = totalBytesExpectedToSend + uploadProgress.completedUnitCount = totalBytesSent + + if let uploadProgressHandler = uploadProgressHandler { + uploadProgressHandler.queue.async { uploadProgressHandler.closure(self.uploadProgress) } + } + } + } +} diff --git a/Pods/Alamofire/Source/Timeline.swift b/Pods/Alamofire/Source/Timeline.swift new file mode 100644 index 0000000..181c988 --- /dev/null +++ b/Pods/Alamofire/Source/Timeline.swift @@ -0,0 +1,136 @@ +// +// Timeline.swift +// +// Copyright (c) 2014-2018 Alamofire Software Foundation (http://alamofire.org/) +// +// Permission is hereby granted, free of charge, to any person obtaining a copy +// of this software and associated documentation files (the "Software"), to deal +// in the Software without restriction, including without limitation the rights +// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +// copies of the Software, and to permit persons to whom the Software is +// furnished to do so, subject to the following conditions: +// +// The above copyright notice and this permission notice shall be included in +// all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN +// THE SOFTWARE. +// + +import Foundation + +/// Responsible for computing the timing metrics for the complete lifecycle of a `Request`. +public struct Timeline { + /// The time the request was initialized. + public let requestStartTime: CFAbsoluteTime + + /// The time the first bytes were received from or sent to the server. + public let initialResponseTime: CFAbsoluteTime + + /// The time when the request was completed. + public let requestCompletedTime: CFAbsoluteTime + + /// The time when the response serialization was completed. + public let serializationCompletedTime: CFAbsoluteTime + + /// The time interval in seconds from the time the request started to the initial response from the server. + public let latency: TimeInterval + + /// The time interval in seconds from the time the request started to the time the request completed. + public let requestDuration: TimeInterval + + /// The time interval in seconds from the time the request completed to the time response serialization completed. + public let serializationDuration: TimeInterval + + /// The time interval in seconds from the time the request started to the time response serialization completed. + public let totalDuration: TimeInterval + + /// Creates a new `Timeline` instance with the specified request times. + /// + /// - parameter requestStartTime: The time the request was initialized. Defaults to `0.0`. + /// - parameter initialResponseTime: The time the first bytes were received from or sent to the server. + /// Defaults to `0.0`. + /// - parameter requestCompletedTime: The time when the request was completed. Defaults to `0.0`. + /// - parameter serializationCompletedTime: The time when the response serialization was completed. Defaults + /// to `0.0`. + /// + /// - returns: The new `Timeline` instance. + public init( + requestStartTime: CFAbsoluteTime = 0.0, + initialResponseTime: CFAbsoluteTime = 0.0, + requestCompletedTime: CFAbsoluteTime = 0.0, + serializationCompletedTime: CFAbsoluteTime = 0.0) + { + self.requestStartTime = requestStartTime + self.initialResponseTime = initialResponseTime + self.requestCompletedTime = requestCompletedTime + self.serializationCompletedTime = serializationCompletedTime + + self.latency = initialResponseTime - requestStartTime + self.requestDuration = requestCompletedTime - requestStartTime + self.serializationDuration = serializationCompletedTime - requestCompletedTime + self.totalDuration = serializationCompletedTime - requestStartTime + } +} + +// MARK: - CustomStringConvertible + +extension Timeline: CustomStringConvertible { + /// The textual representation used when written to an output stream, which includes the latency, the request + /// duration and the total duration. + public var description: String { + let latency = String(format: "%.3f", self.latency) + let requestDuration = String(format: "%.3f", self.requestDuration) + let serializationDuration = String(format: "%.3f", self.serializationDuration) + let totalDuration = String(format: "%.3f", self.totalDuration) + + // NOTE: Had to move to string concatenation due to memory leak filed as rdar://26761490. Once memory leak is + // fixed, we should move back to string interpolation by reverting commit 7d4a43b1. + let timings = [ + "\"Latency\": " + latency + " secs", + "\"Request Duration\": " + requestDuration + " secs", + "\"Serialization Duration\": " + serializationDuration + " secs", + "\"Total Duration\": " + totalDuration + " secs" + ] + + return "Timeline: { " + timings.joined(separator: ", ") + " }" + } +} + +// MARK: - CustomDebugStringConvertible + +extension Timeline: CustomDebugStringConvertible { + /// The textual representation used when written to an output stream, which includes the request start time, the + /// initial response time, the request completed time, the serialization completed time, the latency, the request + /// duration and the total duration. + public var debugDescription: String { + let requestStartTime = String(format: "%.3f", self.requestStartTime) + let initialResponseTime = String(format: "%.3f", self.initialResponseTime) + let requestCompletedTime = String(format: "%.3f", self.requestCompletedTime) + let serializationCompletedTime = String(format: "%.3f", self.serializationCompletedTime) + let latency = String(format: "%.3f", self.latency) + let requestDuration = String(format: "%.3f", self.requestDuration) + let serializationDuration = String(format: "%.3f", self.serializationDuration) + let totalDuration = String(format: "%.3f", self.totalDuration) + + // NOTE: Had to move to string concatenation due to memory leak filed as rdar://26761490. Once memory leak is + // fixed, we should move back to string interpolation by reverting commit 7d4a43b1. + let timings = [ + "\"Request Start Time\": " + requestStartTime, + "\"Initial Response Time\": " + initialResponseTime, + "\"Request Completed Time\": " + requestCompletedTime, + "\"Serialization Completed Time\": " + serializationCompletedTime, + "\"Latency\": " + latency + " secs", + "\"Request Duration\": " + requestDuration + " secs", + "\"Serialization Duration\": " + serializationDuration + " secs", + "\"Total Duration\": " + totalDuration + " secs" + ] + + return "Timeline: { " + timings.joined(separator: ", ") + " }" + } +} diff --git a/Pods/Alamofire/Source/Validation.swift b/Pods/Alamofire/Source/Validation.swift new file mode 100644 index 0000000..ec2c5c3 --- /dev/null +++ b/Pods/Alamofire/Source/Validation.swift @@ -0,0 +1,315 @@ +// +// Validation.swift +// +// Copyright (c) 2014-2018 Alamofire Software Foundation (http://alamofire.org/) +// +// Permission is hereby granted, free of charge, to any person obtaining a copy +// of this software and associated documentation files (the "Software"), to deal +// in the Software without restriction, including without limitation the rights +// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +// copies of the Software, and to permit persons to whom the Software is +// furnished to do so, subject to the following conditions: +// +// The above copyright notice and this permission notice shall be included in +// all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN +// THE SOFTWARE. +// + +import Foundation + +extension Request { + + // MARK: Helper Types + + fileprivate typealias ErrorReason = AFError.ResponseValidationFailureReason + + /// Used to represent whether validation was successful or encountered an error resulting in a failure. + /// + /// - success: The validation was successful. + /// - failure: The validation failed encountering the provided error. + public enum ValidationResult { + case success + case failure(Error) + } + + fileprivate struct MIMEType { + let type: String + let subtype: String + + var isWildcard: Bool { return type == "*" && subtype == "*" } + + init?(_ string: String) { + let components: [String] = { + let stripped = string.trimmingCharacters(in: .whitespacesAndNewlines) + + #if swift(>=3.2) + let split = stripped[..<(stripped.range(of: ";")?.lowerBound ?? stripped.endIndex)] + #else + let split = stripped.substring(to: stripped.range(of: ";")?.lowerBound ?? stripped.endIndex) + #endif + + return split.components(separatedBy: "/") + }() + + if let type = components.first, let subtype = components.last { + self.type = type + self.subtype = subtype + } else { + return nil + } + } + + func matches(_ mime: MIMEType) -> Bool { + switch (type, subtype) { + case (mime.type, mime.subtype), (mime.type, "*"), ("*", mime.subtype), ("*", "*"): + return true + default: + return false + } + } + } + + // MARK: Properties + + fileprivate var acceptableStatusCodes: [Int] { return Array(200..<300) } + + fileprivate var acceptableContentTypes: [String] { + if let accept = request?.value(forHTTPHeaderField: "Accept") { + return accept.components(separatedBy: ",") + } + + return ["*/*"] + } + + // MARK: Status Code + + fileprivate func validate( + statusCode acceptableStatusCodes: S, + response: HTTPURLResponse) + -> ValidationResult + where S.Iterator.Element == Int + { + if acceptableStatusCodes.contains(response.statusCode) { + return .success + } else { + let reason: ErrorReason = .unacceptableStatusCode(code: response.statusCode) + return .failure(AFError.responseValidationFailed(reason: reason)) + } + } + + // MARK: Content Type + + fileprivate func validate( + contentType acceptableContentTypes: S, + response: HTTPURLResponse, + data: Data?) + -> ValidationResult + where S.Iterator.Element == String + { + guard let data = data, data.count > 0 else { return .success } + + guard + let responseContentType = response.mimeType, + let responseMIMEType = MIMEType(responseContentType) + else { + for contentType in acceptableContentTypes { + if let mimeType = MIMEType(contentType), mimeType.isWildcard { + return .success + } + } + + let error: AFError = { + let reason: ErrorReason = .missingContentType(acceptableContentTypes: Array(acceptableContentTypes)) + return AFError.responseValidationFailed(reason: reason) + }() + + return .failure(error) + } + + for contentType in acceptableContentTypes { + if let acceptableMIMEType = MIMEType(contentType), acceptableMIMEType.matches(responseMIMEType) { + return .success + } + } + + let error: AFError = { + let reason: ErrorReason = .unacceptableContentType( + acceptableContentTypes: Array(acceptableContentTypes), + responseContentType: responseContentType + ) + + return AFError.responseValidationFailed(reason: reason) + }() + + return .failure(error) + } +} + +// MARK: - + +extension DataRequest { + /// A closure used to validate a request that takes a URL request, a URL response and data, and returns whether the + /// request was valid. + public typealias Validation = (URLRequest?, HTTPURLResponse, Data?) -> ValidationResult + + /// Validates the request, using the specified closure. + /// + /// If validation fails, subsequent calls to response handlers will have an associated error. + /// + /// - parameter validation: A closure to validate the request. + /// + /// - returns: The request. + @discardableResult + public func validate(_ validation: @escaping Validation) -> Self { + let validationExecution: () -> Void = { [unowned self] in + if + let response = self.response, + self.delegate.error == nil, + case let .failure(error) = validation(self.request, response, self.delegate.data) + { + self.delegate.error = error + } + } + + validations.append(validationExecution) + + return self + } + + /// Validates that the response has a status code in the specified sequence. + /// + /// If validation fails, subsequent calls to response handlers will have an associated error. + /// + /// - parameter range: The range of acceptable status codes. + /// + /// - returns: The request. + @discardableResult + public func validate(statusCode acceptableStatusCodes: S) -> Self where S.Iterator.Element == Int { + return validate { [unowned self] _, response, _ in + return self.validate(statusCode: acceptableStatusCodes, response: response) + } + } + + /// Validates that the response has a content type in the specified sequence. + /// + /// If validation fails, subsequent calls to response handlers will have an associated error. + /// + /// - parameter contentType: The acceptable content types, which may specify wildcard types and/or subtypes. + /// + /// - returns: The request. + @discardableResult + public func validate(contentType acceptableContentTypes: S) -> Self where S.Iterator.Element == String { + return validate { [unowned self] _, response, data in + return self.validate(contentType: acceptableContentTypes, response: response, data: data) + } + } + + /// Validates that the response has a status code in the default acceptable range of 200...299, and that the content + /// type matches any specified in the Accept HTTP header field. + /// + /// If validation fails, subsequent calls to response handlers will have an associated error. + /// + /// - returns: The request. + @discardableResult + public func validate() -> Self { + return validate(statusCode: self.acceptableStatusCodes).validate(contentType: self.acceptableContentTypes) + } +} + +// MARK: - + +extension DownloadRequest { + /// A closure used to validate a request that takes a URL request, a URL response, a temporary URL and a + /// destination URL, and returns whether the request was valid. + public typealias Validation = ( + _ request: URLRequest?, + _ response: HTTPURLResponse, + _ temporaryURL: URL?, + _ destinationURL: URL?) + -> ValidationResult + + /// Validates the request, using the specified closure. + /// + /// If validation fails, subsequent calls to response handlers will have an associated error. + /// + /// - parameter validation: A closure to validate the request. + /// + /// - returns: The request. + @discardableResult + public func validate(_ validation: @escaping Validation) -> Self { + let validationExecution: () -> Void = { [unowned self] in + let request = self.request + let temporaryURL = self.downloadDelegate.temporaryURL + let destinationURL = self.downloadDelegate.destinationURL + + if + let response = self.response, + self.delegate.error == nil, + case let .failure(error) = validation(request, response, temporaryURL, destinationURL) + { + self.delegate.error = error + } + } + + validations.append(validationExecution) + + return self + } + + /// Validates that the response has a status code in the specified sequence. + /// + /// If validation fails, subsequent calls to response handlers will have an associated error. + /// + /// - parameter range: The range of acceptable status codes. + /// + /// - returns: The request. + @discardableResult + public func validate(statusCode acceptableStatusCodes: S) -> Self where S.Iterator.Element == Int { + return validate { [unowned self] _, response, _, _ in + return self.validate(statusCode: acceptableStatusCodes, response: response) + } + } + + /// Validates that the response has a content type in the specified sequence. + /// + /// If validation fails, subsequent calls to response handlers will have an associated error. + /// + /// - parameter contentType: The acceptable content types, which may specify wildcard types and/or subtypes. + /// + /// - returns: The request. + @discardableResult + public func validate(contentType acceptableContentTypes: S) -> Self where S.Iterator.Element == String { + return validate { [unowned self] _, response, _, _ in + let fileURL = self.downloadDelegate.fileURL + + guard let validFileURL = fileURL else { + return .failure(AFError.responseValidationFailed(reason: .dataFileNil)) + } + + do { + let data = try Data(contentsOf: validFileURL) + return self.validate(contentType: acceptableContentTypes, response: response, data: data) + } catch { + return .failure(AFError.responseValidationFailed(reason: .dataFileReadFailed(at: validFileURL))) + } + } + } + + /// Validates that the response has a status code in the default acceptable range of 200...299, and that the content + /// type matches any specified in the Accept HTTP header field. + /// + /// If validation fails, subsequent calls to response handlers will have an associated error. + /// + /// - returns: The request. + @discardableResult + public func validate() -> Self { + return validate(statusCode: self.acceptableStatusCodes).validate(contentType: self.acceptableContentTypes) + } +} diff --git a/Pods/AlamofireImage/LICENSE b/Pods/AlamofireImage/LICENSE new file mode 100644 index 0000000..5769f92 --- /dev/null +++ b/Pods/AlamofireImage/LICENSE @@ -0,0 +1,19 @@ +Copyright (c) 2015-2018 Alamofire Software Foundation (http://alamofire.org/) + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in +all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN +THE SOFTWARE. diff --git a/Pods/AlamofireImage/README.md b/Pods/AlamofireImage/README.md new file mode 100644 index 0000000..0e36800 --- /dev/null +++ b/Pods/AlamofireImage/README.md @@ -0,0 +1,590 @@ +# AlamofireImage + +[![Build Status](https://travis-ci.org/Alamofire/AlamofireImage.svg?branch=master)](https://travis-ci.org/Alamofire/AlamofireImage) +[![CocoaPods Compatible](https://img.shields.io/cocoapods/v/AlamofireImage.svg)](https://img.shields.io/cocoapods/v/AlamofireImage.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/AlamofireImage.svg?style=flat)](http://cocoadocs.org/docsets/AlamofireImage) +[![Twitter](https://img.shields.io/badge/twitter-@AlamofireSF-blue.svg?style=flat)](http://twitter.com/AlamofireSF) +[![Gitter](https://badges.gitter.im/Alamofire/Alamofire.svg)](https://gitter.im/Alamofire/Alamofire?utm_source=badge&utm_medium=badge&utm_campaign=pr-badge) + +AlamofireImage is an image component library for Alamofire. + +## Features + +- [x] Image Response Serializers +- [x] UIImage Extensions for Inflation / Scaling / Rounding / CoreImage +- [x] Single and Multi-Pass Image Filters +- [x] Auto-Purging In-Memory Image Cache +- [x] Prioritized Queue Order Image Downloading +- [x] Authentication with URLCredential +- [x] UIImageView Async Remote Downloads with Placeholders +- [x] UIImageView Filters and Transitions +- [x] Comprehensive Test Coverage +- [x] [Complete Documentation](http://cocoadocs.org/docsets/AlamofireImage) + +## Requirements + +- iOS 8.0+ / macOS 10.10+ / tvOS 9.0+ / watchOS 2.0+ +- Xcode 8.3+ +- Swift 3.1+ + +## Migration Guides + +- [AlamofireImage 2.0 Migration Guide](https://github.com/Alamofire/AlamofireImage/blob/master/Documentation/AlamofireImage%202.0%20Migration%20Guide.md) +- [AlamofireImage 3.0 Migration Guide](https://github.com/Alamofire/AlamofireImage/blob/master/Documentation/AlamofireImage%203.0%20Migration%20Guide.md) + +## Dependencies + +- [Alamofire 4.7+](https://github.com/Alamofire/Alamofire) + +## Communication + +- If you need to **find or understand an API**, check [our documentation](https://alamofire.github.io/AlamofireImage/). +- If you need **help with an AlamofireImage feature**, use [our forum on swift.org](https://forums.swift.org/c/related-projects/alamofire). +- If you'd like to **discuss AlamofireImage best practices**, use [our forum on swift.org](https://forums.swift.org/c/related-projects/alamofire). +- If you'd like to **discuss a feature request**, use [our forum on swift.org](https://forums.swift.org/c/related-projects/alamofire). +- If you **found a bug**, open an issue and follow the guide. The more detail the better! +- If you **want to contribute**, submit a pull request. + +## Installation + +### CocoaPods + +[CocoaPods](http://cocoapods.org) is a dependency manager for Cocoa projects. You can install it with the following command: + +```bash +$ gem install cocoapods +``` + +> CocoaPods 1.1+ is required. + +To integrate AlamofireImage 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 'AlamofireImage', '~> 3.4' +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 AlamofireImage into your Xcode project using Carthage, specify it in your `Cartfile`: + +```ogdl +github "Alamofire/AlamofireImage" ~> 3.4 +``` + +Run `carthage update` to build the framework and drag the built `AlamofireImage.framework` into your Xcode project. + +### Manually + +If you prefer not to use either of the aforementioned dependency managers, you can integrate AlamofireImage 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 AlamofireImage as a git [submodule](http://git-scm.com/docs/git-submodule) by running the following command: + +```bash +$ git submodule add https://github.com/Alamofire/AlamofireImage.git +``` + +- Open the new `AlamofireImage` folder, and drag the `AlamofireImage.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 `AlamofireImage.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 `AlamofireImage.xcodeproj` folders each with two different versions of the `AlamofireImage.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 `AlamofireImage.framework`. + +- Select the top `AlamofireImage.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 `AlamofireImage` will be listed as either `AlamofireImage iOS`, `AlamofireImage macOS`, `AlamofireImage tvOS` or `AlamofireImage watchOS`. + +- And that's it! + + > The `AlamofireImage.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 + +### Image Response Serializers + +```swift +import Alamofire +import AlamofireImage + +Alamofire.request("https://httpbin.org/image/png").responseImage { response in + debugPrint(response) + + print(response.request) + print(response.response) + debugPrint(response.result) + + if let image = response.result.value { + print("image downloaded: \(image)") + } +} +``` + +The AlamofireImage response image serializers support a wide range of image types including: + +- `image/png` +- `image/jpeg` +- `image/tiff` +- `image/gif` +- `image/ico` +- `image/x-icon` +- `image/bmp` +- `image/x-bmp` +- `image/x-xbitmap` +- `image/x-win-bitmap` + +> If the image you are attempting to download is an invalid MIME type not in the list, you can add custom acceptable content types using the `addAcceptableImageContentTypes` extension on the `DataRequest` type. + +### UIImage Extensions + +There are several `UIImage` extensions designed to make the common image manipulation operations as simple as possible. + +#### Inflation + +```swift +let url = Bundle.main.url(forResource: "unicorn", withExtension: "png")! +let data = try! Data(contentsOf: url) +let image = UIImage(data: data, scale: UIScreen.main.scale)! + +image.af_inflate() +``` + +> Inflating compressed image formats (such as PNG or JPEG) in a background queue can significantly improve drawing performance on the main thread. + +#### Scaling + +```swift +let image = UIImage(named: "unicorn")! +let size = CGSize(width: 100.0, height: 100.0) + +// Scale image to size disregarding aspect ratio +let scaledImage = image.af_imageScaled(to: size) + +// Scale image to fit within specified size while maintaining aspect ratio +let aspectScaledToFitImage = image.af_imageAspectScaled(toFit: size) + +// Scale image to fill specified size while maintaining aspect ratio +let aspectScaledToFillImage = image.af_imageAspectScaled(toFill: size) +``` + +#### Rounded Corners + +```swift +let image = UIImage(named: "unicorn")! +let radius: CGFloat = 20.0 + +let roundedImage = image.af_imageRounded(withCornerRadius: radius) +let circularImage = image.af_imageRoundedIntoCircle() +``` + +#### Core Image Filters + +```swift +let image = UIImage(named: "unicorn")! + +let sepiaImage = image.af_imageFiltered(withCoreImageFilter: "CISepiaTone") + +let blurredImage = image.af_imageFiltered( + withCoreImageFilter: "CIGaussianBlur", + parameters: ["inputRadius": 25] +) +``` + +### Image Filters + +The `ImageFilter` protocol was designed to make it easy to apply a filter operation and cache the result after an image finished downloading. It defines two properties to facilitate this functionality. + +```swift +public protocol ImageFilter { + var filter: Image -> Image { get } + var identifier: String { get } +} +``` + +The `filter` closure contains the operation used to create a modified version of the specified image. The `identifier` property is a string used to uniquely identify the filter operation. This is useful when adding filtered versions of an image to a cache. All identifier properties inside AlamofireImage are implemented using protocol extensions. + +#### Single Pass + +The single pass image filters only perform a single operation on the specified image. + +```swift +let image = UIImage(named: "unicorn")! +let imageFilter = RoundedCornersFilter(radius: 10.0) + +let roundedImage = imageFilter.filter(image) +``` + +The current list of single pass image filters includes: + +- `ScaledToSizeFilter` - Scales an image to a specified size. +- `AspectScaledToFitSizeFilter` - Scales an image from the center while maintaining the aspect ratio to fit within a specified size. +- `AspectScaledToFillSizeFilter` - Scales an image from the center while maintaining the aspect ratio to fill a specified size. Any pixels that fall outside the specified size are clipped. +- `RoundedCornersFilter` - Rounds the corners of an image to the specified radius. +- `CircleFilter` - Rounds the corners of an image into a circle. +- `BlurFilter` - Blurs an image using a `CIGaussianBlur` filter with the specified blur radius. + +> Each image filter is built ontop of the `UIImage` extensions. + +#### Multi-Pass + +The multi-pass image filters perform multiple operations on the specified image. + +```swift +let image = UIImage(named: "avatar")! +let size = CGSize(width: 100.0, height: 100.0) +let imageFilter = AspectScaledToFillSizeCircleFilter(size: size) + +let avatarImage = imageFilter.filter(image) +``` + +The current list of multi-pass image filters includes: + +- `ScaledToSizeWithRoundedCornersFilter` - Scales an image to a specified size, then rounds the corners to the specified radius. +- `AspectScaledToFillSizeWithRoundedCornersFilter` - Scales an image from the center while maintaining the aspect ratio to fit within a specified size, then rounds the corners to the specified radius. +- `ScaledToSizeCircleFilter` - Scales an image to a specified size, then rounds the corners into a circle. +- `AspectScaledToFillSizeCircleFilter` - Scales an image from the center while maintaining the aspect ratio to fit within a specified size, then rounds the corners into a circle. + +### Image Cache + +Image caching can become complicated when it comes to network images. `URLCache` is quite powerful and does a great job reasoning through the various cache policies and `Cache-Control` headers. However, it is not equipped to handle caching multiple modified versions of those images. + +For example, let's say you need to download an album of images. Your app needs to display both the thumbnail version as well as the full size version at various times. Due to performance issues, you want to scale down the thumbnails to a reasonable size before rendering them on-screen. You also need to apply a global CoreImage filter to the full size images when displayed. While `URLCache` can easily handle storing the original downloaded image, it cannot store these different variants. What you really need is another caching layer designed to handle these different variants. + +```swift +let imageCache = AutoPurgingImageCache( + memoryCapacity: 100_000_000, + preferredMemoryUsageAfterPurge: 60_000_000 +) +``` + +The `AutoPurgingImageCache` in AlamofireImage fills the role of that additional caching layer. It is an in-memory image cache used to store images up to a given memory capacity. When the memory capacity is reached, the image cache is sorted by last access date, then the oldest image is continuously purged until the preferred memory usage after purge is met. Each time an image is accessed through the cache, the internal access date of the image is updated. + +#### Add / Remove / Fetch Images + +Interacting with the `ImageCache` protocol APIs is very straightforward. + +```swift +let imageCache = AutoPurgingImageCache() +let avatarImage = UIImage(data: data)! + +// Add +imageCache.add(avatarImage, withIdentifier: "avatar") + +// Fetch +let cachedAvatar = imageCache.image(withIdentifier: "avatar") + +// Remove +imageCache.removeImage(withIdentifier: "avatar") +``` + +#### URL Requests + +The `ImageRequestCache` protocol extends the `ImageCache` protocol by adding support for `URLRequest` caching. This allows a `URLRequest` and an additional identifier to generate the unique identifier for the image in the cache. + +```swift +let imageCache = AutoPurgingImageCache() + +let urlRequest = URLRequest(url: URL(string: "https://httpbin.org/image/png")!) +let avatarImage = UIImage(named: "avatar")!.af_imageRoundedIntoCircle() + +// Add +imageCache.add(avatarImage, for: urlRequest, withIdentifier: "circle") + +// Fetch +let cachedAvatarImage = imageCache.image(for: urlRequest, withIdentifier: "circle") + +// Remove +imageCache.removeImage(for: urlRequest, withIdentifier: "circle") +``` + +#### Auto-Purging + +Each time an image is fetched from the cache, the cache internally updates the last access date for that image. + +```swift +let avatar = imageCache.image(withIdentifier: "avatar") +let circularAvatar = imageCache.image(for: urlRequest, withIdentifier: "circle") +``` + +By updating the last access date for each image, the image cache can make more informed decisions about which images to purge when the memory capacity is reached. The `AutoPurgingImageCache` automatically evicts images from the cache in order from oldest last access date to newest until the memory capacity drops below the `preferredMemoryCapacityAfterPurge`. + +> It is important to set reasonable default values for the `memoryCapacity` and `preferredMemoryCapacityAfterPurge` when you are initializing your image cache. By default, the `memoryCapacity` equals 100 MB and the `preferredMemoryCapacityAfterPurge` equals 60 MB. + +#### Memory Warnings + +The `AutoPurgingImageCache` also listens for memory warnings from your application and will purge all images from the cache if a memory warning is observed. + +### Image Downloader + +The `ImageDownloader` class is responsible for downloading images in parallel on a prioritized queue. It uses an internal Alamofire `SessionManager` instance to handle all the downloading and response image serialization. By default, the initialization of an `ImageDownloader` uses a default `URLSessionConfiguration` with the most common parameter values. + +```swift +let imageDownloader = ImageDownloader( + configuration: ImageDownloader.defaultURLSessionConfiguration(), + downloadPrioritization: .fifo, + maximumActiveDownloads: 4, + imageCache: AutoPurgingImageCache() +) +``` + +> If you need to customize the `URLSessionConfiguration` type or parameters, then simply provide your own rather than using the default. + +#### Downloading an Image + +```swift +let downloader = ImageDownloader() +let urlRequest = URLRequest(url: URL(string: "https://httpbin.org/image/jpeg")!) + +downloader.download(urlRequest) { response in + print(response.request) + print(response.response) + debugPrint(response.result) + + if let image = response.result.value { + print(image) + } +} +``` + +> Make sure to keep a strong reference to the `ImageDownloader` instance, otherwise the `completion` closure will not be called because the `downloader` reference will go out of scope before the `completion` closure can be called. + +#### Applying an ImageFilter + +```swift +let downloader = ImageDownloader() +let urlRequest = URLRequest(url: URL(string: "https://httpbin.org/image/jpeg")!) +let filter = AspectScaledToFillSizeCircleFilter(size: CGSize(width: 100.0, height: 100.0)) + +downloader.download(urlRequest, filter: filter) { response in + print(response.request) + print(response.response) + debugPrint(response.result) + + if let image = response.result.value { + print(image) + } +} +``` + +#### Authentication + +If your images are behind HTTP Basic Auth, you can append the `user:password:` or the `credential` to the `ImageDownloader` instance. The credentials will be applied to all future download requests. + +```swift +let downloader = ImageDownloader() +downloader.addAuthentication(user: "username", password: "password") +``` + +#### Download Prioritization + +The `ImageDownloader` maintains an internal queue of pending download requests. Depending on your situation, you may want incoming downloads to be inserted at the front or the back of the queue. The `DownloadPrioritization` enumeration allows you to specify which behavior you would prefer. + +```swift +public enum DownloadPrioritization { + case fifo, lifo +} +``` + +> The `ImageDownloader` is initialized with a `.fifo` queue by default. + +#### Image Caching + +The `ImageDownloader` uses a combination of an `URLCache` and `AutoPurgingImageCache` to create a very robust, high performance image caching system. + +##### URLCache + +The `URLCache` is used to cache all the original image content downloaded from the server. By default, it is initialized with a memory capacity of 20 MB and a disk capacity of 150 MB. This allows up to 150 MB of original image data to be stored on disk at any given time. While these defaults have been carefully set, it is very important to consider your application's needs and performance requirements and whether these values are right for you. + +> If you wish to disable this caching layer, create a custom `URLSessionConfiguration` with the `urlCache` property set to `nil` and use that configuration when initializing the `ImageDownloader`. + +##### Image Cache + +The `ImageCache` is used to cache all the potentially filtered image content after it has been downloaded from the server. This allows multiple variants of the same image to also be cached, rather than having to re-apply the image filters to the original image each time it is required. By default, an `AutoPurgingImageCache` is initialized with a memory capacity of 100 MB and a preferred memory usage after purge limit of 60 MB. This allows up to 100 MB of most recently accessed filtered image content to be stored in-memory at a given time. + +##### Setting Ideal Capacity Limits + +Determining the ideal the in-memory and on-disk capacity limits of the `URLCache` and `AutoPurgingImageCache` requires a bit of forethought. You must carefully consider your application's needs, and tailor the limits accordingly. By default, the combination of caches offers the following storage capacities: + +- 150 MB of on-disk storage +- 20 MB of in-memory original image data storage +- 100 MB of in-memory storage of filtered image content +- 60 MB preferred memory capacity after purge of filtered image content + +> If you do not use image filters, it is advised to set the memory capacity of the `URLCache` to zero to avoid storing the same content in-memory twice. + +#### Duplicate Downloads + +Sometimes application logic can end up attempting to download an image more than once before the initial download request is complete. Most often, this results in the image being downloaded more than once. AlamofireImage handles this case elegantly by merging the duplicate downloads. The image will only be downloaded once, yet both completion handlers will be called. + +##### Image Filter Reuse + +In addition to merging duplicate downloads, AlamofireImage can also merge duplicate image filters. If two image filters with the same identifier are attached to the same download, the image filter is only executed once and both completion handlers are called with the same resulting image. This can save large amounts of time and resources for computationally expensive filters such as ones leveraging CoreImage. + +##### Request Receipts + +Sometimes it is necessary to cancel an image download for various reasons. AlamofireImage can intelligently handle cancellation logic in the `ImageDownloader` by leveraging the `RequestReceipt` type along with the `cancelRequestForRequestReceipt` method. Each download request vends a `RequestReceipt` which can be later used to cancel the request. + +By cancelling the request through the `ImageDownloader` using the `RequestReceipt`, AlamofireImage is able to determine how to best handle the cancellation. The cancelled download will always receive a cancellation error, while duplicate downloads are allowed to complete. If the download is already active, it is allowed to complete even though the completion handler will be called with a cancellation error. This greatly improves performance of table and collection views displaying large amounts of images. + +> It is NOT recommended to directly call `cancel` on the `request` in the `RequestReceipt`. Doing so can lead to issues such as duplicate downloads never being allowed to complete. + +### UIImageView Extension + +The [UIImage Extensions](#uiimage-extensions), [Image Filters](#image-filters), [Image Cache](#image-cache) and [Image Downloader](#image-downloader) were all designed to be flexible and standalone, yet also to provide the foundation of the `UIImageView` extension. Due to the powerful support of these classes, protocols and extensions, the `UIImageView` APIs are concise, easy to use and contain a large amount of functionality. + +#### Setting Image with URL + +Setting the image with a URL will asynchronously download the image and set it once the request is finished. + +```swift +let imageView = UIImageView(frame: frame) +let url = URL(string: "https://httpbin.org/image/png")! + +imageView.af_setImage(withURL: url) +``` + +> If the image is cached locally, the image is set immediately. + +#### Placeholder Images + +By specifying a placeholder image, the image view uses the placeholder image until the remote image is downloaded. + +```swift +let imageView = UIImageView(frame: frame) +let url = URL(string: "https://httpbin.org/image/png")! +let placeholderImage = UIImage(named: "placeholder")! + +imageView.af_setImage(withURL: url, placeholderImage: placeholderImage) +``` + +> If the remote image is cached locally, the placeholder image is never set. + +#### Image Filters + +If an image filter is specified, it is applied asynchronously after the remote image is downloaded. Once the filter execution is complete, the resulting image is set on the image view. + +```swift +let imageView = UIImageView(frame: frame) + +let url = URL(string: "https://httpbin.org/image/png")! +let placeholderImage = UIImage(named: "placeholder")! + +let filter = AspectScaledToFillSizeWithRoundedCornersFilter( + size: imageView.frame.size, + radius: 20.0 +) + +imageView.af_setImage( + withURL: url, + placeholderImage: placeholderImage, + filter: filter +) +``` + +> If the remote image with the applied filter is cached locally, the image is set immediately. + +#### Image Transitions + +By default, there is no image transition animation when setting the image on the image view. If you wish to add a cross dissolve or flip-from-bottom animation, then specify an `ImageTransition` with the preferred duration. + +```swift +let imageView = UIImageView(frame: frame) + +let url = URL(string: "https://httpbin.org/image/png")! +let placeholderImage = UIImage(named: "placeholder")! + +let filter = AspectScaledToFillSizeWithRoundedCornersFilter( + size: imageView.frame.size, + radius: 20.0 +) + +imageView.af_setImage( + withURL: url, + placeholderImage: placeholderImage, + filter: filter, + imageTransition: .crossDissolve(0.2) +) +``` + +> If the remote image is cached locally, the image transition is ignored. + +#### Image Downloader + +The `UIImageView` extension is powered by the default `ImageDownloader` instance. To customize cache capacities, download priorities, request cache policies, timeout durations, etc., please refer to the [Image Downloader](#image-downloader) documentation. + +##### Authentication + +If an image requires and authentication credential from the `UIImageView` extension, it can be provided as follows: + +```swift +ImageDownloader.default.addAuthentication(user: "user", password: "password") +``` + +--- + +## 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 AlamofireImage, you should report it as soon as possible via email to security@alamofire.org. Please do not post it to a public issue tracker. + +## Donations + +The [ASF](https://github.com/Alamofire/Foundation#members) is looking to raise money to officially stay registered as a federal non-profit organization. +Registering will allow us members to gain some legal protections and also allow us to put donations to use, tax free. +Donating to the ASF will enable us to: + +- Pay our yearly legal fees to keep the non-profit in good status +- Pay for our mail servers to help us stay on top of all questions and security issues +- Potentially fund test servers to make it easier for us to test the edge cases +- Potentially fund developers to work on one of our projects full-time + +The community adoption of the ASF libraries has been amazing. +We are greatly humbled by your enthusiasm around the projects, and want to continue to do everything we can to move the needle forward. +With your continued support, the ASF will be able to improve its reach and also provide better legal safety for the core members. +If you use any of our libraries for work, see if your employers would be interested in donating. +Any amount you can donate today to help us reach our goal would be greatly appreciated. + +[![paypal](https://www.paypalobjects.com/en_US/i/btn/btn_donateCC_LG.gif)](https://www.paypal.com/cgi-bin/webscr?cmd=_s-xclick&hosted_button_id=W34WPEE74APJQ) + +## License + +AlamofireImage is released under the MIT license. See LICENSE for details. diff --git a/Pods/AlamofireImage/Source/AFIError.swift b/Pods/AlamofireImage/Source/AFIError.swift new file mode 100644 index 0000000..ed152e6 --- /dev/null +++ b/Pods/AlamofireImage/Source/AFIError.swift @@ -0,0 +1,63 @@ +// +// AFIError.swift +// +// Copyright (c) 2015-2018 Alamofire Software Foundation (http://alamofire.org/) +// +// Permission is hereby granted, free of charge, to any person obtaining a copy +// of this software and associated documentation files (the "Software"), to deal +// in the Software without restriction, including without limitation the rights +// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +// copies of the Software, and to permit persons to whom the Software is +// furnished to do so, subject to the following conditions: +// +// The above copyright notice and this permission notice shall be included in +// all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN +// THE SOFTWARE. +// + +import Foundation + +/// `AFIError` is the error type returned by AlamofireImage. +/// +/// - requestCancelled: The request was explicitly cancelled. +/// - imageSerializationFailed: Response data could not be serialized into an image. +public enum AFIError: Error { + case requestCancelled + case imageSerializationFailed +} + +// MARK: - Error Booleans + +extension AFIError { + /// Returns `true` if the `AFIError` is a request cancellation error, `false` otherwise. + public var isRequestCancelledError: Bool { + if case .requestCancelled = self { return true } + return false + } + + /// Returns `true` if the `AFIError` is an image serialization error, `false` otherwise. + public var isImageSerializationFailedError: Bool { + if case .imageSerializationFailed = self { return true } + return false + } +} + +// MARK: - Error Descriptions + +extension AFIError: LocalizedError { + public var errorDescription: String? { + switch self { + case .requestCancelled: + return "The request was explicitly cancelled." + case .imageSerializationFailed: + return "Response data could not be serialized into an image." + } + } +} diff --git a/Pods/AlamofireImage/Source/Image.swift b/Pods/AlamofireImage/Source/Image.swift new file mode 100644 index 0000000..e221390 --- /dev/null +++ b/Pods/AlamofireImage/Source/Image.swift @@ -0,0 +1,33 @@ +// +// Image.swift +// +// Copyright (c) 2015-2018 Alamofire Software Foundation (http://alamofire.org/) +// +// Permission is hereby granted, free of charge, to any person obtaining a copy +// of this software and associated documentation files (the "Software"), to deal +// in the Software without restriction, including without limitation the rights +// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +// copies of the Software, and to permit persons to whom the Software is +// furnished to do so, subject to the following conditions: +// +// The above copyright notice and this permission notice shall be included in +// all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN +// THE SOFTWARE. +// + +import Foundation + +#if os(iOS) || os(tvOS) || os(watchOS) +import UIKit +public typealias Image = UIImage +#elseif os(macOS) +import Cocoa +public typealias Image = NSImage +#endif diff --git a/Pods/AlamofireImage/Source/ImageCache.swift b/Pods/AlamofireImage/Source/ImageCache.swift new file mode 100644 index 0000000..21f3c9a --- /dev/null +++ b/Pods/AlamofireImage/Source/ImageCache.swift @@ -0,0 +1,350 @@ +// +// ImageCache.swift +// +// Copyright (c) 2015-2018 Alamofire Software Foundation (http://alamofire.org/) +// +// Permission is hereby granted, free of charge, to any person obtaining a copy +// of this software and associated documentation files (the "Software"), to deal +// in the Software without restriction, including without limitation the rights +// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +// copies of the Software, and to permit persons to whom the Software is +// furnished to do so, subject to the following conditions: +// +// The above copyright notice and this permission notice shall be included in +// all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN +// THE SOFTWARE. +// + +import Alamofire +import Foundation + +#if os(iOS) || os(tvOS) || os(watchOS) +import UIKit +#elseif os(macOS) +import Cocoa +#endif + +// MARK: ImageCache + +/// The `ImageCache` protocol defines a set of APIs for adding, removing and fetching images from a cache. +public protocol ImageCache { + /// Adds the image to the cache with the given identifier. + func add(_ image: Image, withIdentifier identifier: String) + + /// Removes the image from the cache matching the given identifier. + func removeImage(withIdentifier identifier: String) -> Bool + + /// Removes all images stored in the cache. + @discardableResult + func removeAllImages() -> Bool + + /// Returns the image in the cache associated with the given identifier. + func image(withIdentifier identifier: String) -> Image? +} + +/// The `ImageRequestCache` protocol extends the `ImageCache` protocol by adding methods for adding, removing and +/// fetching images from a cache given an `URLRequest` and additional identifier. +public protocol ImageRequestCache: ImageCache { + /// Adds the image to the cache using an identifier created from the request and identifier. + func add(_ image: Image, for request: URLRequest, withIdentifier identifier: String?) + + /// Removes the image from the cache using an identifier created from the request and identifier. + func removeImage(for request: URLRequest, withIdentifier identifier: String?) -> Bool + + /// Returns the image from the cache associated with an identifier created from the request and identifier. + func image(for request: URLRequest, withIdentifier identifier: String?) -> Image? +} + +// MARK: - + +/// The `AutoPurgingImageCache` in an in-memory image cache used to store images up to a given memory capacity. When +/// the memory capacity is reached, the image cache is sorted by last access date, then the oldest image is continuously +/// purged until the preferred memory usage after purge is met. Each time an image is accessed through the cache, the +/// internal access date of the image is updated. +open class AutoPurgingImageCache: ImageRequestCache { + class CachedImage { + let image: Image + let identifier: String + let totalBytes: UInt64 + var lastAccessDate: Date + + init(_ image: Image, identifier: String) { + self.image = image + self.identifier = identifier + self.lastAccessDate = Date() + + self.totalBytes = { + #if os(iOS) || os(tvOS) || os(watchOS) + let size = CGSize(width: image.size.width * image.scale, height: image.size.height * image.scale) + #elseif os(macOS) + let size = CGSize(width: image.size.width, height: image.size.height) + #endif + + let bytesPerPixel: CGFloat = 4.0 + let bytesPerRow = size.width * bytesPerPixel + let totalBytes = UInt64(bytesPerRow) * UInt64(size.height) + + return totalBytes + }() + } + + func accessImage() -> Image { + lastAccessDate = Date() + return image + } + } + + // MARK: Properties + + /// The current total memory usage in bytes of all images stored within the cache. + open var memoryUsage: UInt64 { + var memoryUsage: UInt64 = 0 + synchronizationQueue.sync { memoryUsage = self.currentMemoryUsage } + + return memoryUsage + } + + /// The total memory capacity of the cache in bytes. + public let memoryCapacity: UInt64 + + /// The preferred memory usage after purge in bytes. During a purge, images will be purged until the memory + /// capacity drops below this limit. + public let preferredMemoryUsageAfterPurge: UInt64 + + private let synchronizationQueue: DispatchQueue + private var cachedImages: [String: CachedImage] + private var currentMemoryUsage: UInt64 + + // MARK: Initialization + + /// Initialies the `AutoPurgingImageCache` instance with the given memory capacity and preferred memory usage + /// after purge limit. + /// + /// Please note, the memory capacity must always be greater than or equal to the preferred memory usage after purge. + /// + /// - parameter memoryCapacity: The total memory capacity of the cache in bytes. `100 MB` by default. + /// - parameter preferredMemoryUsageAfterPurge: The preferred memory usage after purge in bytes. `60 MB` by default. + /// + /// - returns: The new `AutoPurgingImageCache` instance. + public init(memoryCapacity: UInt64 = 100_000_000, preferredMemoryUsageAfterPurge: UInt64 = 60_000_000) { + self.memoryCapacity = memoryCapacity + self.preferredMemoryUsageAfterPurge = preferredMemoryUsageAfterPurge + + precondition( + memoryCapacity >= preferredMemoryUsageAfterPurge, + "The `memoryCapacity` must be greater than or equal to `preferredMemoryUsageAfterPurge`" + ) + + self.cachedImages = [:] + self.currentMemoryUsage = 0 + + self.synchronizationQueue = { + let name = String(format: "org.alamofire.autopurgingimagecache-%08x%08x", arc4random(), arc4random()) + return DispatchQueue(label: name, attributes: .concurrent) + }() + + #if os(iOS) || os(tvOS) + #if swift(>=4.2) + let notification = UIApplication.didReceiveMemoryWarningNotification + #else + let notification = Notification.Name.UIApplicationDidReceiveMemoryWarning + #endif + NotificationCenter.default.addObserver( + self, + selector: #selector(AutoPurgingImageCache.removeAllImages), + name: notification, + object: nil + ) + #endif + } + + deinit { + NotificationCenter.default.removeObserver(self) + } + + // MARK: Add Image to Cache + + /// Adds the image to the cache using an identifier created from the request and optional identifier. + /// + /// - parameter image: The image to add to the cache. + /// - parameter request: The request used to generate the image's unique identifier. + /// - parameter identifier: The additional identifier to append to the image's unique identifier. + open func add(_ image: Image, for request: URLRequest, withIdentifier identifier: String? = nil) { + let requestIdentifier = imageCacheKey(for: request, withIdentifier: identifier) + add(image, withIdentifier: requestIdentifier) + } + + /// Adds the image to the cache with the given identifier. + /// + /// - parameter image: The image to add to the cache. + /// - parameter identifier: The identifier to use to uniquely identify the image. + open func add(_ image: Image, withIdentifier identifier: String) { + synchronizationQueue.async(flags: [.barrier]) { + let cachedImage = CachedImage(image, identifier: identifier) + + if let previousCachedImage = self.cachedImages[identifier] { + self.currentMemoryUsage -= previousCachedImage.totalBytes + } + + self.cachedImages[identifier] = cachedImage + self.currentMemoryUsage += cachedImage.totalBytes + } + + synchronizationQueue.async(flags: [.barrier]) { + if self.currentMemoryUsage > self.memoryCapacity { + let bytesToPurge = self.currentMemoryUsage - self.preferredMemoryUsageAfterPurge + + var sortedImages = self.cachedImages.map { $1 } + + sortedImages.sort { + let date1 = $0.lastAccessDate + let date2 = $1.lastAccessDate + + return date1.timeIntervalSince(date2) < 0.0 + } + + var bytesPurged = UInt64(0) + + for cachedImage in sortedImages { + self.cachedImages.removeValue(forKey: cachedImage.identifier) + bytesPurged += cachedImage.totalBytes + + if bytesPurged >= bytesToPurge { + break + } + } + + self.currentMemoryUsage -= bytesPurged + } + } + } + + // MARK: Remove Image from Cache + + /// Removes the image from the cache using an identifier created from the request and optional identifier. + /// + /// - parameter request: The request used to generate the image's unique identifier. + /// - parameter identifier: The additional identifier to append to the image's unique identifier. + /// + /// - returns: `true` if the image was removed, `false` otherwise. + @discardableResult + open func removeImage(for request: URLRequest, withIdentifier identifier: String?) -> Bool { + let requestIdentifier = imageCacheKey(for: request, withIdentifier: identifier) + return removeImage(withIdentifier: requestIdentifier) + } + + /// Removes all images from the cache created from the request. + /// + /// - parameter request: The request used to generate the image's unique identifier. + /// + /// - returns: `true` if any images were removed, `false` otherwise. + @discardableResult + open func removeImages(matching request: URLRequest) -> Bool { + let requestIdentifier = imageCacheKey(for: request, withIdentifier: nil) + var removed = false + + synchronizationQueue.sync { + for key in self.cachedImages.keys where key.hasPrefix(requestIdentifier) { + if let cachedImage = self.cachedImages.removeValue(forKey: key) { + self.currentMemoryUsage -= cachedImage.totalBytes + removed = true + } + } + } + + return removed + } + + /// Removes the image from the cache matching the given identifier. + /// + /// - parameter identifier: The unique identifier for the image. + /// + /// - returns: `true` if the image was removed, `false` otherwise. + @discardableResult + open func removeImage(withIdentifier identifier: String) -> Bool { + var removed = false + + synchronizationQueue.sync { + if let cachedImage = self.cachedImages.removeValue(forKey: identifier) { + self.currentMemoryUsage -= cachedImage.totalBytes + removed = true + } + } + + return removed + } + + /// Removes all images stored in the cache. + /// + /// - returns: `true` if images were removed from the cache, `false` otherwise. + @discardableResult @objc + open func removeAllImages() -> Bool { + var removed = false + + synchronizationQueue.sync { + if !self.cachedImages.isEmpty { + self.cachedImages.removeAll() + self.currentMemoryUsage = 0 + + removed = true + } + } + + return removed + } + + // MARK: Fetch Image from Cache + + /// Returns the image from the cache associated with an identifier created from the request and optional identifier. + /// + /// - parameter request: The request used to generate the image's unique identifier. + /// - parameter identifier: The additional identifier to append to the image's unique identifier. + /// + /// - returns: The image if it is stored in the cache, `nil` otherwise. + open func image(for request: URLRequest, withIdentifier identifier: String? = nil) -> Image? { + let requestIdentifier = imageCacheKey(for: request, withIdentifier: identifier) + return image(withIdentifier: requestIdentifier) + } + + /// Returns the image in the cache associated with the given identifier. + /// + /// - parameter identifier: The unique identifier for the image. + /// + /// - returns: The image if it is stored in the cache, `nil` otherwise. + open func image(withIdentifier identifier: String) -> Image? { + var image: Image? + + synchronizationQueue.sync { + if let cachedImage = self.cachedImages[identifier] { + image = cachedImage.accessImage() + } + } + + return image + } + + // MARK: Image Cache Keys + + /// Returns the unique image cache key for the specified request and additional identifier. + /// + /// - parameter request: The request. + /// - parameter identifier: The additional identifier. + /// + /// - returns: The unique image cache key. + open func imageCacheKey(for request: URLRequest, withIdentifier identifier: String?) -> String { + var key = request.url?.absoluteString ?? "" + + if let identifier = identifier { + key += "-\(identifier)" + } + + return key + } +} diff --git a/Pods/AlamofireImage/Source/ImageDownloader.swift b/Pods/AlamofireImage/Source/ImageDownloader.swift new file mode 100644 index 0000000..e4b318a --- /dev/null +++ b/Pods/AlamofireImage/Source/ImageDownloader.swift @@ -0,0 +1,559 @@ +// +// ImageDownloader.swift +// +// Copyright (c) 2015-2018 Alamofire Software Foundation (http://alamofire.org/) +// +// Permission is hereby granted, free of charge, to any person obtaining a copy +// of this software and associated documentation files (the "Software"), to deal +// in the Software without restriction, including without limitation the rights +// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +// copies of the Software, and to permit persons to whom the Software is +// furnished to do so, subject to the following conditions: +// +// The above copyright notice and this permission notice shall be included in +// all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN +// THE SOFTWARE. +// + +import Alamofire +import Foundation + +#if os(iOS) || os(tvOS) || os(watchOS) +import UIKit +#elseif os(macOS) +import Cocoa +#endif + +/// The `RequestReceipt` is an object vended by the `ImageDownloader` when starting a download request. It can be used +/// to cancel active requests running on the `ImageDownloader` session. As a general rule, image download requests +/// should be cancelled using the `RequestReceipt` instead of calling `cancel` directly on the `request` itself. The +/// `ImageDownloader` is optimized to handle duplicate request scenarios as well as pending versus active downloads. +open class RequestReceipt { + /// The download request created by the `ImageDownloader`. + public let request: Request + + /// The unique identifier for the image filters and completion handlers when duplicate requests are made. + public let receiptID: String + + init(request: Request, receiptID: String) { + self.request = request + self.receiptID = receiptID + } +} + +// MARK: - + +/// The `ImageDownloader` class is responsible for downloading images in parallel on a prioritized queue. Incoming +/// downloads are added to the front or back of the queue depending on the download prioritization. Each downloaded +/// image is cached in the underlying `NSURLCache` as well as the in-memory image cache that supports image filters. +/// By default, any download request with a cached image equivalent in the image cache will automatically be served the +/// cached image representation. Additional advanced features include supporting multiple image filters and completion +/// handlers for a single request. +open class ImageDownloader { + /// The completion handler closure used when an image download completes. + public typealias CompletionHandler = (DataResponse) -> Void + + /// The progress handler closure called periodically during an image download. + public typealias ProgressHandler = DataRequest.ProgressHandler + + // MARK: Helper Types + + /// Defines the order prioritization of incoming download requests being inserted into the queue. + /// + /// - fifo: All incoming downloads are added to the back of the queue. + /// - lifo: All incoming downloads are added to the front of the queue. + public enum DownloadPrioritization { + case fifo, lifo + } + + class ResponseHandler { + let urlID: String + let handlerID: String + let request: DataRequest + var operations: [(receiptID: String, filter: ImageFilter?, completion: CompletionHandler?)] + + init( + request: DataRequest, + handlerID: String, + receiptID: String, + filter: ImageFilter?, + completion: CompletionHandler?) + { + self.request = request + self.urlID = ImageDownloader.urlIdentifier(for: request.request!) + self.handlerID = handlerID + self.operations = [(receiptID: receiptID, filter: filter, completion: completion)] + } + } + + // MARK: Properties + + /// The image cache used to store all downloaded images in. + public let imageCache: ImageRequestCache? + + /// The credential used for authenticating each download request. + open private(set) var credential: URLCredential? + + /// Response serializer used to convert the image data to UIImage. + public var imageResponseSerializer = DataRequest.imageResponseSerializer() + + /// The underlying Alamofire `Manager` instance used to handle all download requests. + public let sessionManager: SessionManager + + let downloadPrioritization: DownloadPrioritization + let maximumActiveDownloads: Int + + var activeRequestCount = 0 + var queuedRequests: [Request] = [] + var responseHandlers: [String: ResponseHandler] = [:] + + private let synchronizationQueue: DispatchQueue = { + let name = String(format: "org.alamofire.imagedownloader.synchronizationqueue-%08x%08x", arc4random(), arc4random()) + return DispatchQueue(label: name) + }() + + private let responseQueue: DispatchQueue = { + let name = String(format: "org.alamofire.imagedownloader.responsequeue-%08x%08x", arc4random(), arc4random()) + return DispatchQueue(label: name, attributes: .concurrent) + }() + + // MARK: Initialization + + /// The default instance of `ImageDownloader` initialized with default values. + public static let `default` = ImageDownloader() + + /// Creates a default `URLSessionConfiguration` with common usage parameter values. + /// + /// - returns: The default `URLSessionConfiguration` instance. + open class func defaultURLSessionConfiguration() -> URLSessionConfiguration { + let configuration = URLSessionConfiguration.default + + configuration.httpAdditionalHeaders = SessionManager.defaultHTTPHeaders + configuration.httpShouldSetCookies = true + configuration.httpShouldUsePipelining = false + + configuration.requestCachePolicy = .useProtocolCachePolicy + configuration.allowsCellularAccess = true + configuration.timeoutIntervalForRequest = 60 + + configuration.urlCache = ImageDownloader.defaultURLCache() + + return configuration + } + + /// Creates a default `URLCache` with common usage parameter values. + /// + /// - returns: The default `URLCache` instance. + open class func defaultURLCache() -> URLCache { + return URLCache( + memoryCapacity: 20 * 1024 * 1024, // 20 MB + diskCapacity: 150 * 1024 * 1024, // 150 MB + diskPath: "org.alamofire.imagedownloader" + ) + } + + /// Initializes the `ImageDownloader` instance with the given configuration, download prioritization, maximum active + /// download count and image cache. + /// + /// - parameter configuration: The `URLSessionConfiguration` to use to create the underlying Alamofire + /// `SessionManager` instance. + /// - parameter downloadPrioritization: The download prioritization of the download queue. `.fifo` by default. + /// - parameter maximumActiveDownloads: The maximum number of active downloads allowed at any given time. + /// - parameter imageCache: The image cache used to store all downloaded images in. + /// + /// - returns: The new `ImageDownloader` instance. + public init( + configuration: URLSessionConfiguration = ImageDownloader.defaultURLSessionConfiguration(), + downloadPrioritization: DownloadPrioritization = .fifo, + maximumActiveDownloads: Int = 4, + imageCache: ImageRequestCache? = AutoPurgingImageCache()) + { + self.sessionManager = SessionManager(configuration: configuration) + self.sessionManager.startRequestsImmediately = false + + self.downloadPrioritization = downloadPrioritization + self.maximumActiveDownloads = maximumActiveDownloads + self.imageCache = imageCache + } + + /// Initializes the `ImageDownloader` instance with the given session manager, download prioritization, maximum + /// active download count and image cache. + /// + /// - parameter sessionManager: The Alamofire `SessionManager` instance to handle all download requests. + /// - parameter downloadPrioritization: The download prioritization of the download queue. `.fifo` by default. + /// - parameter maximumActiveDownloads: The maximum number of active downloads allowed at any given time. + /// - parameter imageCache: The image cache used to store all downloaded images in. + /// + /// - returns: The new `ImageDownloader` instance. + public init( + sessionManager: SessionManager, + downloadPrioritization: DownloadPrioritization = .fifo, + maximumActiveDownloads: Int = 4, + imageCache: ImageRequestCache? = AutoPurgingImageCache()) + { + self.sessionManager = sessionManager + self.sessionManager.startRequestsImmediately = false + + self.downloadPrioritization = downloadPrioritization + self.maximumActiveDownloads = maximumActiveDownloads + self.imageCache = imageCache + } + + // MARK: Authentication + + /// Associates an HTTP Basic Auth credential with all future download requests. + /// + /// - parameter user: The user. + /// - parameter password: The password. + /// - parameter persistence: The URL credential persistence. `.forSession` by default. + open func addAuthentication( + user: String, + password: String, + persistence: URLCredential.Persistence = .forSession) + { + let credential = URLCredential(user: user, password: password, persistence: persistence) + addAuthentication(usingCredential: credential) + } + + /// Associates the specified credential with all future download requests. + /// + /// - parameter credential: The credential. + open func addAuthentication(usingCredential credential: URLCredential) { + synchronizationQueue.sync { + self.credential = credential + } + } + + // MARK: Download + + /// Creates a download request using the internal Alamofire `SessionManager` instance for the specified URL request. + /// + /// If the same download request is already in the queue or currently being downloaded, the filter and completion + /// handler are appended to the already existing request. Once the request completes, all filters and completion + /// handlers attached to the request are executed in the order they were added. Additionally, any filters attached + /// to the request with the same identifiers are only executed once. The resulting image is then passed into each + /// completion handler paired with the filter. + /// + /// You should not attempt to directly cancel the `request` inside the request receipt since other callers may be + /// relying on the completion of that request. Instead, you should call `cancelRequestForRequestReceipt` with the + /// returned request receipt to allow the `ImageDownloader` to optimize the cancellation on behalf of all active + /// callers. + /// + /// - parameter urlRequest: The URL request. + /// - parameter receiptID: The `identifier` for the `RequestReceipt` returned. Defaults to a new, randomly + /// generated UUID. + /// - parameter filter: The image filter to apply to the image after the download is complete. Defaults + /// to `nil`. + /// - parameter progress: The closure to be executed periodically during the lifecycle of the request. + /// Defaults to `nil`. + /// - parameter progressQueue: The dispatch queue to call the progress closure on. Defaults to the main queue. + /// - parameter completion: The closure called when the download request is complete. Defaults to `nil`. + /// + /// - returns: The request receipt for the download request if available. `nil` if the image is stored in the image + /// cache and the URL request cache policy allows the cache to be used. + @discardableResult + open func download( + _ urlRequest: URLRequestConvertible, + receiptID: String = UUID().uuidString, + filter: ImageFilter? = nil, + progress: ProgressHandler? = nil, + progressQueue: DispatchQueue = DispatchQueue.main, + completion: CompletionHandler?) + -> RequestReceipt? + { + var request: DataRequest! + + synchronizationQueue.sync { + // 1) Append the filter and completion handler to a pre-existing request if it already exists + let urlID = ImageDownloader.urlIdentifier(for: urlRequest) + + if let responseHandler = self.responseHandlers[urlID] { + responseHandler.operations.append((receiptID: receiptID, filter: filter, completion: completion)) + request = responseHandler.request + return + } + + // 2) Attempt to load the image from the image cache if the cache policy allows it + if let request = urlRequest.urlRequest { + switch request.cachePolicy { + case .useProtocolCachePolicy, .returnCacheDataElseLoad, .returnCacheDataDontLoad: + if let image = self.imageCache?.image(for: request, withIdentifier: filter?.identifier) { + DispatchQueue.main.async { + let response = DataResponse( + request: urlRequest.urlRequest, + response: nil, + data: nil, + result: .success(image) + ) + + completion?(response) + } + + return + } + default: + break + } + } + + // 3) Create the request and set up authentication, validation and response serialization + request = self.sessionManager.request(urlRequest) + + if let credential = self.credential { + request.authenticate(usingCredential: credential) + } + + request.validate() + + if let progress = progress { + request.downloadProgress(queue: progressQueue, closure: progress) + } + + // Generate a unique handler id to check whether the active request has changed while downloading + let handlerID = UUID().uuidString + + request.response( + queue: self.responseQueue, + responseSerializer: imageResponseSerializer, + completionHandler: { [weak self] response in + guard let strongSelf = self, let request = response.request else { return } + + defer { + strongSelf.safelyDecrementActiveRequestCount() + strongSelf.safelyStartNextRequestIfNecessary() + } + + // Early out if the request has changed out from under us + let handler = strongSelf.safelyFetchResponseHandler(withURLIdentifier: urlID) + guard handler?.handlerID == handlerID else { return } + + guard let responseHandler = strongSelf.safelyRemoveResponseHandler(withURLIdentifier: urlID) else { + return + } + + switch response.result { + case .success(let image): + var filteredImages: [String: Image] = [:] + + for (_, filter, completion) in responseHandler.operations { + var filteredImage: Image + + if let filter = filter { + if let alreadyFilteredImage = filteredImages[filter.identifier] { + filteredImage = alreadyFilteredImage + } else { + filteredImage = filter.filter(image) + filteredImages[filter.identifier] = filteredImage + } + } else { + filteredImage = image + } + + strongSelf.imageCache?.add(filteredImage, for: request, withIdentifier: filter?.identifier) + + DispatchQueue.main.async { + let response = DataResponse( + request: response.request, + response: response.response, + data: response.data, + result: .success(filteredImage), + timeline: response.timeline + ) + + completion?(response) + } + } + case .failure: + for (_, _, completion) in responseHandler.operations { + DispatchQueue.main.async { completion?(response) } + } + } + } + ) + + // 4) Store the response handler for use when the request completes + let responseHandler = ResponseHandler( + request: request, + handlerID: handlerID, + receiptID: receiptID, + filter: filter, + completion: completion + ) + + self.responseHandlers[urlID] = responseHandler + + // 5) Either start the request or enqueue it depending on the current active request count + if self.isActiveRequestCountBelowMaximumLimit() { + self.start(request) + } else { + self.enqueue(request) + } + } + + if let request = request { + return RequestReceipt(request: request, receiptID: receiptID) + } + + return nil + } + + /// Creates a download request using the internal Alamofire `SessionManager` instance for each specified URL request. + /// + /// For each request, if the same download request is already in the queue or currently being downloaded, the + /// filter and completion handler are appended to the already existing request. Once the request completes, all + /// filters and completion handlers attached to the request are executed in the order they were added. + /// Additionally, any filters attached to the request with the same identifiers are only executed once. The + /// resulting image is then passed into each completion handler paired with the filter. + /// + /// You should not attempt to directly cancel any of the `request`s inside the request receipts array since other + /// callers may be relying on the completion of that request. Instead, you should call + /// `cancelRequestForRequestReceipt` with the returned request receipt to allow the `ImageDownloader` to optimize + /// the cancellation on behalf of all active callers. + /// + /// - parameter urlRequests: The URL requests. + /// - parameter filter The image filter to apply to the image after each download is complete. + /// - parameter progress: The closure to be executed periodically during the lifecycle of the request. Defaults + /// to `nil`. + /// - parameter progressQueue: The dispatch queue to call the progress closure on. Defaults to the main queue. + /// - parameter completion: The closure called when each download request is complete. + /// + /// - returns: The request receipts for the download requests if available. If an image is stored in the image + /// cache and the URL request cache policy allows the cache to be used, a receipt will not be returned + /// for that request. + @discardableResult + open func download( + _ urlRequests: [URLRequestConvertible], + filter: ImageFilter? = nil, + progress: ProgressHandler? = nil, + progressQueue: DispatchQueue = DispatchQueue.main, + completion: CompletionHandler? = nil) + -> [RequestReceipt] + { + #if swift(>=4.1) + return urlRequests.compactMap { + download($0, filter: filter, progress: progress, progressQueue: progressQueue, completion: completion) + } + #else + return urlRequests.flatMap { + download($0, filter: filter, progress: progress, progressQueue: progressQueue, completion: completion) + } + #endif + } + + /// Cancels the request in the receipt by removing the response handler and cancelling the request if necessary. + /// + /// If the request is pending in the queue, it will be cancelled if no other response handlers are registered with + /// the request. If the request is currently executing or is already completed, the response handler is removed and + /// will not be called. + /// + /// - parameter requestReceipt: The request receipt to cancel. + open func cancelRequest(with requestReceipt: RequestReceipt) { + synchronizationQueue.sync { + let urlID = ImageDownloader.urlIdentifier(for: requestReceipt.request.request!) + guard let responseHandler = self.responseHandlers[urlID] else { return } + + if let index = responseHandler.operations.index(where: { $0.receiptID == requestReceipt.receiptID }) { + let operation = responseHandler.operations.remove(at: index) + + let response: DataResponse = { + let urlRequest = requestReceipt.request.request + let error = AFIError.requestCancelled + + return DataResponse(request: urlRequest, response: nil, data: nil, result: .failure(error)) + }() + + DispatchQueue.main.async { operation.completion?(response) } + } + + if responseHandler.operations.isEmpty && requestReceipt.request.task?.state == .suspended { + requestReceipt.request.cancel() + self.responseHandlers.removeValue(forKey: urlID) + } + } + } + + // MARK: Internal - Thread-Safe Request Methods + + func safelyFetchResponseHandler(withURLIdentifier urlIdentifier: String) -> ResponseHandler? { + var responseHandler: ResponseHandler? + + synchronizationQueue.sync { + responseHandler = self.responseHandlers[urlIdentifier] + } + + return responseHandler + } + + func safelyRemoveResponseHandler(withURLIdentifier identifier: String) -> ResponseHandler? { + var responseHandler: ResponseHandler? + + synchronizationQueue.sync { + responseHandler = self.responseHandlers.removeValue(forKey: identifier) + } + + return responseHandler + } + + func safelyStartNextRequestIfNecessary() { + synchronizationQueue.sync { + guard self.isActiveRequestCountBelowMaximumLimit() else { return } + + while !self.queuedRequests.isEmpty { + if let request = self.dequeue(), request.task?.state == .suspended { + self.start(request) + break + } + } + } + } + + func safelyDecrementActiveRequestCount() { + self.synchronizationQueue.sync { + if self.activeRequestCount > 0 { + self.activeRequestCount -= 1 + } + } + } + + // MARK: Internal - Non Thread-Safe Request Methods + + func start(_ request: Request) { + request.resume() + activeRequestCount += 1 + } + + func enqueue(_ request: Request) { + switch downloadPrioritization { + case .fifo: + queuedRequests.append(request) + case .lifo: + queuedRequests.insert(request, at: 0) + } + } + + @discardableResult + func dequeue() -> Request? { + var request: Request? + + if !queuedRequests.isEmpty { + request = queuedRequests.removeFirst() + } + + return request + } + + func isActiveRequestCountBelowMaximumLimit() -> Bool { + return activeRequestCount < maximumActiveDownloads + } + + static func urlIdentifier(for urlRequest: URLRequestConvertible) -> String { + return urlRequest.urlRequest?.url?.absoluteString ?? "" + } +} diff --git a/Pods/AlamofireImage/Source/ImageFilter.swift b/Pods/AlamofireImage/Source/ImageFilter.swift new file mode 100644 index 0000000..65dfab9 --- /dev/null +++ b/Pods/AlamofireImage/Source/ImageFilter.swift @@ -0,0 +1,423 @@ +// +// ImageFilter.swift +// +// Copyright (c) 2015-2018 Alamofire Software Foundation (http://alamofire.org/) +// +// Permission is hereby granted, free of charge, to any person obtaining a copy +// of this software and associated documentation files (the "Software"), to deal +// in the Software without restriction, including without limitation the rights +// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +// copies of the Software, and to permit persons to whom the Software is +// furnished to do so, subject to the following conditions: +// +// The above copyright notice and this permission notice shall be included in +// all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN +// THE SOFTWARE. +// + +import Foundation + +#if os(iOS) || os(tvOS) || os(watchOS) +import UIKit +#elseif os(macOS) +import Cocoa +#endif + +// MARK: ImageFilter + +/// The `ImageFilter` protocol defines properties for filtering an image as well as identification of the filter. +public protocol ImageFilter { + /// A closure used to create an alternative representation of the given image. + var filter: (Image) -> Image { get } + + /// The string used to uniquely identify the filter operation. + var identifier: String { get } +} + +extension ImageFilter { + /// The unique identifier for any `ImageFilter` type. + public var identifier: String { return "\(type(of: self))" } +} + +// MARK: - Sizable + +/// The `Sizable` protocol defines a size property intended for use with `ImageFilter` types. +public protocol Sizable { + /// The size of the type. + var size: CGSize { get } +} + +extension ImageFilter where Self: Sizable { + /// The unique idenitifier for an `ImageFilter` conforming to the `Sizable` protocol. + public var identifier: String { + let width = Int64(size.width.rounded()) + let height = Int64(size.height.rounded()) + + return "\(type(of: self))-size:(\(width)x\(height))" + } +} + +// MARK: - Roundable + +/// The `Roundable` protocol defines a radius property intended for use with `ImageFilter` types. +public protocol Roundable { + /// The radius of the type. + var radius: CGFloat { get } +} + +extension ImageFilter where Self: Roundable { + /// The unique idenitifier for an `ImageFilter` conforming to the `Roundable` protocol. + public var identifier: String { + let radius = Int64(self.radius.rounded()) + return "\(type(of: self))-radius:(\(radius))" + } +} + +// MARK: - DynamicImageFilter + +/// The `DynamicImageFilter` class simplifies custom image filter creation by using a trailing closure initializer. +public struct DynamicImageFilter: ImageFilter { + /// The string used to uniquely identify the image filter operation. + public let identifier: String + + /// A closure used to create an alternative representation of the given image. + public let filter: (Image) -> Image + + /// Initializes the `DynamicImageFilter` instance with the specified identifier and filter closure. + /// + /// - parameter identifier: The unique identifier of the filter. + /// - parameter filter: A closure used to create an alternative representation of the given image. + /// + /// - returns: The new `DynamicImageFilter` instance. + public init(_ identifier: String, filter: @escaping (Image) -> Image) { + self.identifier = identifier + self.filter = filter + } +} + +// MARK: - CompositeImageFilter + +/// The `CompositeImageFilter` protocol defines an additional `filters` property to support multiple composite filters. +public protocol CompositeImageFilter: ImageFilter { + /// The image filters to apply to the image in sequential order. + var filters: [ImageFilter] { get } +} + +public extension CompositeImageFilter { + /// The unique idenitifier for any `CompositeImageFilter` type. + var identifier: String { + return filters.map { $0.identifier }.joined(separator: "_") + } + + /// The filter closure for any `CompositeImageFilter` type. + var filter: (Image) -> Image { + return { image in + return self.filters.reduce(image) { $1.filter($0) } + } + } +} + +// MARK: - DynamicCompositeImageFilter + +/// The `DynamicCompositeImageFilter` class is a composite image filter based on a specified array of filters. +public struct DynamicCompositeImageFilter: CompositeImageFilter { + /// The image filters to apply to the image in sequential order. + public let filters: [ImageFilter] + + /// Initializes the `DynamicCompositeImageFilter` instance with the given filters. + /// + /// - parameter filters: The filters taking part in the composite image filter. + /// + /// - returns: The new `DynamicCompositeImageFilter` instance. + public init(_ filters: [ImageFilter]) { + self.filters = filters + } + + /// Initializes the `DynamicCompositeImageFilter` instance with the given filters. + /// + /// - parameter filters: The filters taking part in the composite image filter. + /// + /// - returns: The new `DynamicCompositeImageFilter` instance. + public init(_ filters: ImageFilter...) { + self.init(filters) + } +} + +#if os(iOS) || os(tvOS) || os(watchOS) + +// MARK: - Single Pass Image Filters (iOS, tvOS and watchOS only) - + +/// Scales an image to a specified size. +public struct ScaledToSizeFilter: ImageFilter, Sizable { + /// The size of the filter. + public let size: CGSize + + /// Initializes the `ScaledToSizeFilter` instance with the given size. + /// + /// - parameter size: The size. + /// + /// - returns: The new `ScaledToSizeFilter` instance. + public init(size: CGSize) { + self.size = size + } + + /// The filter closure used to create the modified representation of the given image. + public var filter: (Image) -> Image { + return { image in + return image.af_imageScaled(to: self.size) + } + } +} + +// MARK: - + +/// Scales an image from the center while maintaining the aspect ratio to fit within a specified size. +public struct AspectScaledToFitSizeFilter: ImageFilter, Sizable { + /// The size of the filter. + public let size: CGSize + + /// Initializes the `AspectScaledToFitSizeFilter` instance with the given size. + /// + /// - parameter size: The size. + /// + /// - returns: The new `AspectScaledToFitSizeFilter` instance. + public init(size: CGSize) { + self.size = size + } + + /// The filter closure used to create the modified representation of the given image. + public var filter: (Image) -> Image { + return { image in + return image.af_imageAspectScaled(toFit: self.size) + } + } +} + +// MARK: - + +/// Scales an image from the center while maintaining the aspect ratio to fill a specified size. Any pixels that fall +/// outside the specified size are clipped. +public struct AspectScaledToFillSizeFilter: ImageFilter, Sizable { + /// The size of the filter. + public let size: CGSize + + /// Initializes the `AspectScaledToFillSizeFilter` instance with the given size. + /// + /// - parameter size: The size. + /// + /// - returns: The new `AspectScaledToFillSizeFilter` instance. + public init(size: CGSize) { + self.size = size + } + + /// The filter closure used to create the modified representation of the given image. + public var filter: (Image) -> Image { + return { image in + return image.af_imageAspectScaled(toFill: self.size) + } + } +} + +// MARK: - + +/// Rounds the corners of an image to the specified radius. +public struct RoundedCornersFilter: ImageFilter, Roundable { + /// The radius of the filter. + public let radius: CGFloat + + /// Whether to divide the radius by the image scale. + public let divideRadiusByImageScale: Bool + + /// Initializes the `RoundedCornersFilter` instance with the given radius. + /// + /// - parameter radius: The radius. + /// - parameter divideRadiusByImageScale: Whether to divide the radius by the image scale. Set to `true` when the + /// image has the same resolution for all screen scales such as @1x, @2x and + /// @3x (i.e. single image from web server). Set to `false` for images loaded + /// from an asset catalog with varying resolutions for each screen scale. + /// `false` by default. + /// + /// - returns: The new `RoundedCornersFilter` instance. + public init(radius: CGFloat, divideRadiusByImageScale: Bool = false) { + self.radius = radius + self.divideRadiusByImageScale = divideRadiusByImageScale + } + + /// The filter closure used to create the modified representation of the given image. + public var filter: (Image) -> Image { + return { image in + return image.af_imageRounded( + withCornerRadius: self.radius, + divideRadiusByImageScale: self.divideRadiusByImageScale + ) + } + } + + /// The unique idenitifier for an `ImageFilter` conforming to the `Roundable` protocol. + public var identifier: String { + let radius = Int64(self.radius.rounded()) + return "\(type(of: self))-radius:(\(radius))-divided:(\(divideRadiusByImageScale))" + } +} + +// MARK: - + +/// Rounds the corners of an image into a circle. +public struct CircleFilter: ImageFilter { + /// Initializes the `CircleFilter` instance. + /// + /// - returns: The new `CircleFilter` instance. + public init() {} + + /// The filter closure used to create the modified representation of the given image. + public var filter: (Image) -> Image { + return { image in + return image.af_imageRoundedIntoCircle() + } + } +} + +// MARK: - + +#if os(iOS) || os(tvOS) + +/// The `CoreImageFilter` protocol defines `parameters`, `filterName` properties used by CoreImage. +@available(iOS 9.0, *) +public protocol CoreImageFilter: ImageFilter { + /// The filter name of the CoreImage filter. + var filterName: String { get } + + /// The image filter parameters passed to CoreImage. + var parameters: [String: Any] { get } +} + +@available(iOS 9.0, *) +public extension ImageFilter where Self: CoreImageFilter { + /// The filter closure used to create the modified representation of the given image. + public var filter: (Image) -> Image { + return { image in + return image.af_imageFiltered(withCoreImageFilter: self.filterName, parameters: self.parameters) ?? image + } + } + + /// The unique idenitifier for an `ImageFilter` conforming to the `CoreImageFilter` protocol. + public var identifier: String { return "\(type(of: self))-parameters:(\(self.parameters))" } +} + +/// Blurs an image using a `CIGaussianBlur` filter with the specified blur radius. +@available(iOS 9.0, *) +public struct BlurFilter: ImageFilter, CoreImageFilter { + /// The filter name. + public let filterName = "CIGaussianBlur" + + /// The image filter parameters passed to CoreImage. + public let parameters: [String: Any] + + /// Initializes the `BlurFilter` instance with the given blur radius. + /// + /// - parameter blurRadius: The blur radius. + /// + /// - returns: The new `BlurFilter` instance. + public init(blurRadius: UInt = 10) { + self.parameters = ["inputRadius": blurRadius] + } +} + +#endif + +// MARK: - Composite Image Filters (iOS, tvOS and watchOS only) - + +/// Scales an image to a specified size, then rounds the corners to the specified radius. +public struct ScaledToSizeWithRoundedCornersFilter: CompositeImageFilter { + /// Initializes the `ScaledToSizeWithRoundedCornersFilter` instance with the given size and radius. + /// + /// - parameter size: The size. + /// - parameter radius: The radius. + /// - parameter divideRadiusByImageScale: Whether to divide the radius by the image scale. Set to `true` when the + /// image has the same resolution for all screen scales such as @1x, @2x and + /// @3x (i.e. single image from web server). Set to `false` for images loaded + /// from an asset catalog with varying resolutions for each screen scale. + /// `false` by default. + /// + /// - returns: The new `ScaledToSizeWithRoundedCornersFilter` instance. + public init(size: CGSize, radius: CGFloat, divideRadiusByImageScale: Bool = false) { + self.filters = [ + ScaledToSizeFilter(size: size), + RoundedCornersFilter(radius: radius, divideRadiusByImageScale: divideRadiusByImageScale) + ] + } + + /// The image filters to apply to the image in sequential order. + public let filters: [ImageFilter] +} + +// MARK: - + +/// Scales an image from the center while maintaining the aspect ratio to fit within a specified size, then rounds the +/// corners to the specified radius. +public struct AspectScaledToFillSizeWithRoundedCornersFilter: CompositeImageFilter { + /// Initializes the `AspectScaledToFillSizeWithRoundedCornersFilter` instance with the given size and radius. + /// + /// - parameter size: The size. + /// - parameter radius: The radius. + /// - parameter divideRadiusByImageScale: Whether to divide the radius by the image scale. Set to `true` when the + /// image has the same resolution for all screen scales such as @1x, @2x and + /// @3x (i.e. single image from web server). Set to `false` for images loaded + /// from an asset catalog with varying resolutions for each screen scale. + /// `false` by default. + /// + /// - returns: The new `AspectScaledToFillSizeWithRoundedCornersFilter` instance. + public init(size: CGSize, radius: CGFloat, divideRadiusByImageScale: Bool = false) { + self.filters = [ + AspectScaledToFillSizeFilter(size: size), + RoundedCornersFilter(radius: radius, divideRadiusByImageScale: divideRadiusByImageScale) + ] + } + + /// The image filters to apply to the image in sequential order. + public let filters: [ImageFilter] +} + +// MARK: - + +/// Scales an image to a specified size, then rounds the corners into a circle. +public struct ScaledToSizeCircleFilter: CompositeImageFilter { + /// Initializes the `ScaledToSizeCircleFilter` instance with the given size. + /// + /// - parameter size: The size. + /// + /// - returns: The new `ScaledToSizeCircleFilter` instance. + public init(size: CGSize) { + self.filters = [ScaledToSizeFilter(size: size), CircleFilter()] + } + + /// The image filters to apply to the image in sequential order. + public let filters: [ImageFilter] +} + +// MARK: - + +/// Scales an image from the center while maintaining the aspect ratio to fit within a specified size, then rounds the +/// corners into a circle. +public struct AspectScaledToFillSizeCircleFilter: CompositeImageFilter { + /// Initializes the `AspectScaledToFillSizeCircleFilter` instance with the given size. + /// + /// - parameter size: The size. + /// + /// - returns: The new `AspectScaledToFillSizeCircleFilter` instance. + public init(size: CGSize) { + self.filters = [AspectScaledToFillSizeFilter(size: size), CircleFilter()] + } + + /// The image filters to apply to the image in sequential order. + public let filters: [ImageFilter] +} + +#endif diff --git a/Pods/AlamofireImage/Source/Request+AlamofireImage.swift b/Pods/AlamofireImage/Source/Request+AlamofireImage.swift new file mode 100644 index 0000000..f528c61 --- /dev/null +++ b/Pods/AlamofireImage/Source/Request+AlamofireImage.swift @@ -0,0 +1,327 @@ +// +// Request+AlamofireImage.swift +// +// Copyright (c) 2015-2018 Alamofire Software Foundation (http://alamofire.org/) +// +// Permission is hereby granted, free of charge, to any person obtaining a copy +// of this software and associated documentation files (the "Software"), to deal +// in the Software without restriction, including without limitation the rights +// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +// copies of the Software, and to permit persons to whom the Software is +// furnished to do so, subject to the following conditions: +// +// The above copyright notice and this permission notice shall be included in +// all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN +// THE SOFTWARE. +// + +import Alamofire +import Foundation + +#if os(iOS) || os(tvOS) +import UIKit +#elseif os(watchOS) +import UIKit +import WatchKit +#elseif os(macOS) +import Cocoa +#endif + +extension DataRequest { + static var acceptableImageContentTypes: Set = [ + "image/tiff", + "image/jpeg", + "image/gif", + "image/png", + "image/ico", + "image/x-icon", + "image/bmp", + "image/x-bmp", + "image/x-xbitmap", + "image/x-ms-bmp", + "image/x-win-bitmap" + ] + + static let streamImageInitialBytePattern = Data(bytes: [255, 216]) // 0xffd8 + + /// Adds the content types specified to the list of acceptable images content types for validation. + /// + /// - parameter contentTypes: The additional content types. + public class func addAcceptableImageContentTypes(_ contentTypes: Set) { + DataRequest.acceptableImageContentTypes.formUnion(contentTypes) + } + + // MARK: - iOS, tvOS and watchOS + +#if os(iOS) || os(tvOS) || os(watchOS) + + /// Creates a response serializer that returns an image initialized from the response data using the specified + /// image options. + /// + /// - parameter imageScale: The scale factor used when interpreting the image data to construct + /// `responseImage`. Specifying a scale factor of 1.0 results in an image whose + /// size matches the pixel-based dimensions of the image. Applying a different + /// scale factor changes the size of the image as reported by the size property. + /// `Screen.scale` by default. + /// - parameter inflateResponseImage: Whether to automatically inflate response image data for compressed formats + /// (such as PNG or JPEG). Enabling this can significantly improve drawing + /// performance as it allows a bitmap representation to be constructed in the + /// background rather than on the main thread. `true` by default. + /// + /// - returns: An image response serializer. + public class func imageResponseSerializer( + imageScale: CGFloat = DataRequest.imageScale, + inflateResponseImage: Bool = true) + -> DataResponseSerializer + { + return DataResponseSerializer { request, response, data, error in + let result = serializeResponseData(response: response, data: data, error: error) + + guard case let .success(data) = result else { return .failure(result.error!) } + + do { + try DataRequest.validateContentType(for: request, response: response) + + let image = try DataRequest.image(from: data, withImageScale: imageScale) + if inflateResponseImage { image.af_inflate() } + + return .success(image) + } catch { + return .failure(error) + } + } + } + + /// Adds a response handler to be called once the request has finished. + /// + /// - parameter imageScale: The scale factor used when interpreting the image data to construct + /// `responseImage`. Specifying a scale factor of 1.0 results in an image whose + /// size matches the pixel-based dimensions of the image. Applying a different + /// scale factor changes the size of the image as reported by the size property. + /// This is set to the value of scale of the main screen by default, which + /// automatically scales images for retina displays, for instance. + /// `Screen.scale` by default. + /// - parameter inflateResponseImage: Whether to automatically inflate response image data for compressed formats + /// (such as PNG or JPEG). Enabling this can significantly improve drawing + /// performance as it allows a bitmap representation to be constructed in the + /// background rather than on the main thread. `true` by default. + /// - parameter queue: The queue on which the completion handler is dispatched. `nil` by default, + /// which results in using `DispatchQueue.main`. + /// - parameter completionHandler: A closure to be executed once the request has finished. The closure takes 4 + /// arguments: the URL request, the URL response, if one was received, the image, + /// if one could be created from the URL response and data, and any error produced + /// while creating the image. + /// + /// - returns: The request. + @discardableResult + public func responseImage( + imageScale: CGFloat = DataRequest.imageScale, + inflateResponseImage: Bool = true, + queue: DispatchQueue? = nil, + completionHandler: @escaping (DataResponse) -> Void) + -> Self + { + return response( + queue: queue, + responseSerializer: DataRequest.imageResponseSerializer( + imageScale: imageScale, + inflateResponseImage: inflateResponseImage + ), + completionHandler: completionHandler + ) + } + + /// Sets a closure to be called periodically during the lifecycle of the request as data is read from the server + /// and converted into images. + /// + /// - parameter imageScale: The scale factor used when interpreting the image data to construct + /// `responseImage`. Specifying a scale factor of 1.0 results in an image whose + /// size matches the pixel-based dimensions of the image. Applying a different + /// scale factor changes the size of the image as reported by the size property. + /// This is set to the value of scale of the main screen by default, which + /// automatically scales images for retina displays, for instance. + /// `Screen.scale` by default. + /// - parameter inflateResponseImage: Whether to automatically inflate response image data for compressed formats + /// (such as PNG or JPEG). Enabling this can significantly improve drawing + /// performance as it allows a bitmap representation to be constructed in the + /// background rather than on the main thread. `true` by default. + /// - parameter completionHandler: A closure to be executed when the request has new image. The closure takes 1 + /// argument: the image, if one could be created from the data. + /// + /// - returns: The request. + @discardableResult + public func streamImage( + imageScale: CGFloat = DataRequest.imageScale, + inflateResponseImage: Bool = true, + completionHandler: @escaping (Image) -> Void) + -> Self + { + var imageData = Data() + + return stream { chunkData in + if chunkData.starts(with: DataRequest.streamImageInitialBytePattern) { + imageData = Data() + } + + imageData.append(chunkData) + + if let image = DataRequest.serializeImage(from: imageData) { + completionHandler(image) + } + } + } + + private class func serializeImage( + from data: Data, + imageScale: CGFloat = DataRequest.imageScale, + inflateResponseImage: Bool = true) + -> UIImage? + { + guard data.count > 0 else { return nil } + + do { + let image = try DataRequest.image(from: data, withImageScale: imageScale) + if inflateResponseImage { image.af_inflate() } + + return image + } catch { + return nil + } + } + + private class func image(from data: Data, withImageScale imageScale: CGFloat) throws -> UIImage { + if let image = UIImage.af_threadSafeImage(with: data, scale: imageScale) { + return image + } + + throw AFIError.imageSerializationFailed + } + + public class var imageScale: CGFloat { + #if os(iOS) || os(tvOS) + return UIScreen.main.scale + #elseif os(watchOS) + return WKInterfaceDevice.current().screenScale + #endif + } + +#elseif os(macOS) + + // MARK: - macOS + + /// Creates a response serializer that returns an image initialized from the response data. + /// + /// - returns: An image response serializer. + public class func imageResponseSerializer() -> DataResponseSerializer { + return DataResponseSerializer { request, response, data, error in + let result = serializeResponseData(response: response, data: data, error: error) + + guard case let .success(data) = result else { return .failure(result.error!) } + + do { + try DataRequest.validateContentType(for: request, response: response) + } catch { + return .failure(error) + } + + guard let bitmapImage = NSBitmapImageRep(data: data) else { + return .failure(AFIError.imageSerializationFailed) + } + + let image = NSImage(size: NSSize(width: bitmapImage.pixelsWide, height: bitmapImage.pixelsHigh)) + image.addRepresentation(bitmapImage) + + return .success(image) + } + } + + /// Adds a response handler to be called once the request has finished. + /// + /// - parameter completionHandler: A closure to be executed once the request has finished. The closure takes 4 + /// arguments: the URL request, the URL response, if one was received, the image, if + /// one could be created from the URL response and data, and any error produced while + /// creating the image. + /// - parameter queue: The queue on which the completion handler is dispatched. `nil` by default, + /// which results in using `DispatchQueue.main`. + /// + /// - returns: The request. + @discardableResult + public func responseImage( + queue: DispatchQueue? = nil, + completionHandler: @escaping (DataResponse) -> Void) + -> Self { + return response( + queue: queue, + responseSerializer: DataRequest.imageResponseSerializer(), + completionHandler: completionHandler + ) + } + + /// Sets a closure to be called periodically during the lifecycle of the request as data is read from the server + /// and converted into images. + /// + /// - parameter completionHandler: A closure to be executed when the request has new image. The closure takes 1 + /// argument: the image, if one could be created from the data. + /// + /// - returns: The request. + @discardableResult + public func streamImage(completionHandler: @escaping (Image) -> Void) -> Self { + var imageData = Data() + + return stream { chunkData in + if chunkData.starts(with: DataRequest.streamImageInitialBytePattern) { + imageData = Data() + } + + imageData.append(chunkData) + + if let image = DataRequest.serializeImage(from: imageData) { + completionHandler(image) + } + } + } + + private class func serializeImage(from data: Data) -> NSImage? { + guard data.count > 0 else { return nil } + guard let bitmapImage = NSBitmapImageRep(data: data) else { return nil } + + let image = NSImage(size: NSSize(width: bitmapImage.pixelsWide, height: bitmapImage.pixelsHigh)) + image.addRepresentation(bitmapImage) + + return image + } + +#endif + + // MARK: - Content Type Validation + + /// Returns whether the content type of the response matches one of the acceptable content types. + /// + /// - parameter request: The request. + /// - parameter response: The server response. + /// + /// - throws: An `AFError` response validation failure when an error is encountered. + public class func validateContentType(for request: URLRequest?, response: HTTPURLResponse?) throws { + if let url = request?.url, url.isFileURL { return } + + guard let mimeType = response?.mimeType else { + let contentTypes = Array(DataRequest.acceptableImageContentTypes) + throw AFError.responseValidationFailed(reason: .missingContentType(acceptableContentTypes: contentTypes)) + } + + guard DataRequest.acceptableImageContentTypes.contains(mimeType) else { + let contentTypes = Array(DataRequest.acceptableImageContentTypes) + + throw AFError.responseValidationFailed( + reason: .unacceptableContentType(acceptableContentTypes: contentTypes, responseContentType: mimeType) + ) + } + } +} diff --git a/Pods/AlamofireImage/Source/UIButton+AlamofireImage.swift b/Pods/AlamofireImage/Source/UIButton+AlamofireImage.swift new file mode 100644 index 0000000..1aceb90 --- /dev/null +++ b/Pods/AlamofireImage/Source/UIButton+AlamofireImage.swift @@ -0,0 +1,479 @@ +// +// UIButton+AlamofireImage.swift +// +// Copyright (c) 2015-2018 Alamofire Software Foundation (http://alamofire.org/) +// +// Permission is hereby granted, free of charge, to any person obtaining a copy +// of this software and associated documentation files (the "Software"), to deal +// in the Software without restriction, including without limitation the rights +// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +// copies of the Software, and to permit persons to whom the Software is +// furnished to do so, subject to the following conditions: +// +// The above copyright notice and this permission notice shall be included in +// all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN +// THE SOFTWARE. +// + +import Alamofire +import Foundation + +#if os(iOS) || os(tvOS) + +import UIKit + +#if swift(>=4.2) +public typealias ControlState = UIControl.State +#else +public typealias ControlState = UIControlState +#endif + +extension UIButton { + + // MARK: - Private - AssociatedKeys + + private struct AssociatedKey { + static var imageDownloader = "af_UIButton.ImageDownloader" + static var sharedImageDownloader = "af_UIButton.SharedImageDownloader" + static var imageReceipts = "af_UIButton.ImageReceipts" + static var backgroundImageReceipts = "af_UIButton.BackgroundImageReceipts" + } + + // MARK: - Properties + + /// The instance image downloader used to download all images. If this property is `nil`, the `UIButton` will + /// fallback on the `af_sharedImageDownloader` for all downloads. The most common use case for needing to use a + /// custom instance image downloader is when images are behind different basic auth credentials. + public var af_imageDownloader: ImageDownloader? { + get { + return objc_getAssociatedObject(self, &AssociatedKey.imageDownloader) as? ImageDownloader + } + set { + objc_setAssociatedObject(self, &AssociatedKey.imageDownloader, newValue, .OBJC_ASSOCIATION_RETAIN_NONATOMIC) + } + } + + /// The shared image downloader used to download all images. By default, this is the default `ImageDownloader` + /// instance backed with an `AutoPurgingImageCache` which automatically evicts images from the cache when the memory + /// capacity is reached or memory warning notifications occur. The shared image downloader is only used if the + /// `af_imageDownloader` is `nil`. + public class var af_sharedImageDownloader: ImageDownloader { + get { + guard let + downloader = objc_getAssociatedObject(self, &AssociatedKey.sharedImageDownloader) as? ImageDownloader + else { + return ImageDownloader.default + } + + return downloader + } + set { + objc_setAssociatedObject(self, &AssociatedKey.sharedImageDownloader, newValue, .OBJC_ASSOCIATION_RETAIN_NONATOMIC) + } + } + + private var imageRequestReceipts: [UInt: RequestReceipt] { + get { + guard let + receipts = objc_getAssociatedObject(self, &AssociatedKey.imageReceipts) as? [UInt: RequestReceipt] + else { + return [:] + } + + return receipts + } + set { + objc_setAssociatedObject(self, &AssociatedKey.imageReceipts, newValue, .OBJC_ASSOCIATION_RETAIN_NONATOMIC) + } + } + + private var backgroundImageRequestReceipts: [UInt: RequestReceipt] { + get { + guard let + receipts = objc_getAssociatedObject(self, &AssociatedKey.backgroundImageReceipts) as? [UInt: RequestReceipt] + else { + return [:] + } + + return receipts + } + set { + objc_setAssociatedObject(self, &AssociatedKey.backgroundImageReceipts, newValue, .OBJC_ASSOCIATION_RETAIN_NONATOMIC) + } + } + + // MARK: - Image Downloads + + /// Asynchronously downloads an image from the specified URL and sets it once the request is finished. + /// + /// If the image is cached locally, the image is set immediately. Otherwise the specified placeholder image will be + /// set immediately, and then the remote image will be set once the image request is finished. + /// + /// - parameter state: The control state of the button to set the image on. + /// - parameter url: The URL used for your image request. + /// - parameter placeholderImage: The image to be set initially until the image request finished. If `nil`, the + /// image will not change its image until the image request finishes. Defaults + /// to `nil`. + /// - parameter filter: The image filter applied to the image after the image request is finished. + /// Defaults to `nil`. + /// - parameter progress: The closure to be executed periodically during the lifecycle of the request. + /// Defaults to `nil`. + /// - parameter progressQueue: The dispatch queue to call the progress closure on. Defaults to the main queue. + /// - parameter completion: A closure to be executed when the image request finishes. The closure takes a + /// single response value containing either the image or the error that occurred. If + /// the image was returned from the image cache, the response will be `nil`. Defaults + /// to `nil`. + public func af_setImage( + for state: ControlState, + url: URL, + placeholderImage: UIImage? = nil, + filter: ImageFilter? = nil, + progress: ImageDownloader.ProgressHandler? = nil, + progressQueue: DispatchQueue = DispatchQueue.main, + completion: ((DataResponse) -> Void)? = nil) + { + af_setImage( + for: state, + urlRequest: urlRequest(with: url), + placeholderImage: placeholderImage, + filter: filter, + progress: progress, + progressQueue: progressQueue, + completion: completion + ) + } + + /// Asynchronously downloads an image from the specified URL request and sets it once the request is finished. + /// + /// If the image is cached locally, the image is set immediately. Otherwise the specified placeholder image will be + /// set immediately, and then the remote image will be set once the image request is finished. + /// + /// - parameter state: The control state of the button to set the image on. + /// - parameter urlRequest: The URL request. + /// - parameter placeholderImage: The image to be set initially until the image request finished. If `nil`, the + /// image will not change its image until the image request finishes. Defaults + /// to `nil`. + /// - parameter filter: The image filter applied to the image after the image request is finished. + /// Defaults to `nil`. + /// - parameter progress: The closure to be executed periodically during the lifecycle of the request. + /// Defaults to `nil`. + /// - parameter progressQueue: The dispatch queue to call the progress closure on. Defaults to the main queue. + /// - parameter completion: A closure to be executed when the image request finishes. The closure takes a + /// single response value containing either the image or the error that occurred. If + /// the image was returned from the image cache, the response will be `nil`. Defaults + /// to `nil`. + public func af_setImage( + for state: ControlState, + urlRequest: URLRequestConvertible, + placeholderImage: UIImage? = nil, + filter: ImageFilter? = nil, + progress: ImageDownloader.ProgressHandler? = nil, + progressQueue: DispatchQueue = DispatchQueue.main, + completion: ((DataResponse) -> Void)? = nil) + { + guard !isImageURLRequest(urlRequest, equalToActiveRequestURLForState: state) else { + let error = AFIError.requestCancelled + let response = DataResponse(request: nil, response: nil, data: nil, result: .failure(error)) + + completion?(response) + + return + } + + af_cancelImageRequest(for: state) + + let imageDownloader = af_imageDownloader ?? UIButton.af_sharedImageDownloader + let imageCache = imageDownloader.imageCache + + // Use the image from the image cache if it exists + if + let request = urlRequest.urlRequest, + let image = imageCache?.image(for: request, withIdentifier: filter?.identifier) + { + let response = DataResponse( + request: urlRequest.urlRequest, + response: nil, + data: nil, + result: .success(image) + ) + + setImage(image, for: state) + completion?(response) + + return + } + + // Set the placeholder since we're going to have to download + if let placeholderImage = placeholderImage { setImage(placeholderImage, for: state) } + + // Generate a unique download id to check whether the active request has changed while downloading + let downloadID = UUID().uuidString + + // Download the image, then set the image for the control state + let requestReceipt = imageDownloader.download( + urlRequest, + receiptID: downloadID, + filter: filter, + progress: progress, + progressQueue: progressQueue, + completion: { [weak self] response in + guard + let strongSelf = self, + strongSelf.isImageURLRequest(response.request, equalToActiveRequestURLForState: state) && + strongSelf.imageRequestReceipt(for: state)?.receiptID == downloadID + else { + completion?(response) + return + } + + if let image = response.result.value { + strongSelf.setImage(image, for: state) + } + + strongSelf.setImageRequestReceipt(nil, for: state) + + completion?(response) + } + ) + + setImageRequestReceipt(requestReceipt, for: state) + } + + /// Cancels the active download request for the image, if one exists. + public func af_cancelImageRequest(for state: ControlState) { + guard let receipt = imageRequestReceipt(for: state) else { return } + + let imageDownloader = af_imageDownloader ?? UIButton.af_sharedImageDownloader + imageDownloader.cancelRequest(with: receipt) + + setImageRequestReceipt(nil, for: state) + } + + // MARK: - Background Image Downloads + + /// Asynchronously downloads an image from the specified URL and sets it once the request is finished. + /// + /// If the image is cached locally, the image is set immediately. Otherwise the specified placeholder image will be + /// set immediately, and then the remote image will be set once the image request is finished. + /// + /// - parameter state: The control state of the button to set the image on. + /// - parameter url: The URL used for the image request. + /// - parameter placeholderImage: The image to be set initially until the image request finished. If `nil`, the + /// background image will not change its image until the image request finishes. + /// Defaults to `nil`. + /// - parameter filter: The image filter applied to the image after the image request is finished. + /// Defaults to `nil`. + /// - parameter progress: The closure to be executed periodically during the lifecycle of the request. + /// Defaults to `nil`. + /// - parameter progressQueue: The dispatch queue to call the progress closure on. Defaults to the main queue. + /// - parameter completion: A closure to be executed when the image request finishes. The closure takes a + /// single response value containing either the image or the error that occurred. If + /// the image was returned from the image cache, the response will be `nil`. Defaults + /// to `nil`. + public func af_setBackgroundImage( + for state: ControlState, + url: URL, + placeholderImage: UIImage? = nil, + filter: ImageFilter? = nil, + progress: ImageDownloader.ProgressHandler? = nil, + progressQueue: DispatchQueue = DispatchQueue.main, + completion: ((DataResponse) -> Void)? = nil) + { + af_setBackgroundImage( + for: state, + urlRequest: urlRequest(with: url), + placeholderImage: placeholderImage, + filter: filter, + progress: progress, + progressQueue: progressQueue, + completion: completion + ) + } + + /// Asynchronously downloads an image from the specified URL request and sets it once the request is finished. + /// + /// If the image is cached locally, the image is set immediately. Otherwise the specified placeholder image will be + /// set immediately, and then the remote image will be set once the image request is finished. + /// + /// - parameter state: The control state of the button to set the image on. + /// - parameter urlRequest: The URL request. + /// - parameter placeholderImage: The image to be set initially until the image request finished. If `nil`, the + /// background image will not change its image until the image request finishes. + /// Defaults to `nil`. + /// - parameter filter: The image filter applied to the image after the image request is finished. + /// Defaults to `nil`. + /// - parameter progress: The closure to be executed periodically during the lifecycle of the request. + /// Defaults to `nil`. + /// - parameter progressQueue: The dispatch queue to call the progress closure on. Defaults to the main queue. + /// - parameter completion: A closure to be executed when the image request finishes. The closure takes a + /// single response value containing either the image or the error that occurred. If + /// the image was returned from the image cache, the response will be `nil`. Defaults + /// to `nil`. + public func af_setBackgroundImage( + for state: ControlState, + urlRequest: URLRequestConvertible, + placeholderImage: UIImage? = nil, + filter: ImageFilter? = nil, + progress: ImageDownloader.ProgressHandler? = nil, + progressQueue: DispatchQueue = DispatchQueue.main, + completion: ((DataResponse) -> Void)? = nil) + { + guard !isImageURLRequest(urlRequest, equalToActiveRequestURLForState: state) else { + let error = AFIError.requestCancelled + let response = DataResponse(request: nil, response: nil, data: nil, result: .failure(error)) + + completion?(response) + + return + } + + af_cancelBackgroundImageRequest(for: state) + + let imageDownloader = af_imageDownloader ?? UIButton.af_sharedImageDownloader + let imageCache = imageDownloader.imageCache + + // Use the image from the image cache if it exists + if + let request = urlRequest.urlRequest, + let image = imageCache?.image(for: request, withIdentifier: filter?.identifier) + { + let response = DataResponse( + request: urlRequest.urlRequest, + response: nil, + data: nil, + result: .success(image) + ) + + setBackgroundImage(image, for: state) + completion?(response) + + return + } + + // Set the placeholder since we're going to have to download + if let placeholderImage = placeholderImage { self.setBackgroundImage(placeholderImage, for: state) } + + // Generate a unique download id to check whether the active request has changed while downloading + let downloadID = UUID().uuidString + + // Download the image, then set the image for the control state + let requestReceipt = imageDownloader.download( + urlRequest, + receiptID: downloadID, + filter: nil, + progress: progress, + progressQueue: progressQueue, + completion: { [weak self] response in + guard + let strongSelf = self, + strongSelf.isBackgroundImageURLRequest(response.request, equalToActiveRequestURLForState: state) && + strongSelf.backgroundImageRequestReceipt(for: state)?.receiptID == downloadID + else { + completion?(response) + return + } + + if let image = response.result.value { + strongSelf.setBackgroundImage(image, for: state) + } + + strongSelf.setBackgroundImageRequestReceipt(nil, for: state) + + completion?(response) + } + ) + + setBackgroundImageRequestReceipt(requestReceipt, for: state) + } + + /// Cancels the active download request for the background image, if one exists. + public func af_cancelBackgroundImageRequest(for state: ControlState) { + guard let receipt = backgroundImageRequestReceipt(for: state) else { return } + + let imageDownloader = af_imageDownloader ?? UIButton.af_sharedImageDownloader + imageDownloader.cancelRequest(with: receipt) + + setBackgroundImageRequestReceipt(nil, for: state) + } + + // MARK: - Internal - Image Request Receipts + + func imageRequestReceipt(for state: ControlState) -> RequestReceipt? { + guard let receipt = imageRequestReceipts[state.rawValue] else { return nil } + return receipt + } + + func setImageRequestReceipt(_ receipt: RequestReceipt?, for state: ControlState) { + var receipts = imageRequestReceipts + receipts[state.rawValue] = receipt + + imageRequestReceipts = receipts + } + + // MARK: - Internal - Background Image Request Receipts + + func backgroundImageRequestReceipt(for state: ControlState) -> RequestReceipt? { + guard let receipt = backgroundImageRequestReceipts[state.rawValue] else { return nil } + return receipt + } + + func setBackgroundImageRequestReceipt(_ receipt: RequestReceipt?, for state: ControlState) { + var receipts = backgroundImageRequestReceipts + receipts[state.rawValue] = receipt + + backgroundImageRequestReceipts = receipts + } + + // MARK: - Private - URL Request Helpers + + private func isImageURLRequest( + _ urlRequest: URLRequestConvertible?, + equalToActiveRequestURLForState state: ControlState) + -> Bool + { + if + let currentURL = imageRequestReceipt(for: state)?.request.task?.originalRequest?.url, + let requestURL = urlRequest?.urlRequest?.url, + currentURL == requestURL + { + return true + } + + return false + } + + private func isBackgroundImageURLRequest( + _ urlRequest: URLRequestConvertible?, + equalToActiveRequestURLForState state: ControlState) + -> Bool + { + if + let currentRequestURL = backgroundImageRequestReceipt(for: state)?.request.task?.originalRequest?.url, + let requestURL = urlRequest?.urlRequest?.url, + currentRequestURL == requestURL + { + return true + } + + return false + } + + private func urlRequest(with url: URL) -> URLRequest { + var urlRequest = URLRequest(url: url) + + for mimeType in DataRequest.acceptableImageContentTypes { + urlRequest.addValue(mimeType, forHTTPHeaderField: "Accept") + } + + return urlRequest + } +} + +#endif diff --git a/Pods/AlamofireImage/Source/UIImage+AlamofireImage.swift b/Pods/AlamofireImage/Source/UIImage+AlamofireImage.swift new file mode 100644 index 0000000..2535703 --- /dev/null +++ b/Pods/AlamofireImage/Source/UIImage+AlamofireImage.swift @@ -0,0 +1,322 @@ +// +// UIImage+AlamofireImage.swift +// +// Copyright (c) 2015-2018 Alamofire Software Foundation (http://alamofire.org/) +// +// Permission is hereby granted, free of charge, to any person obtaining a copy +// of this software and associated documentation files (the "Software"), to deal +// in the Software without restriction, including without limitation the rights +// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +// copies of the Software, and to permit persons to whom the Software is +// furnished to do so, subject to the following conditions: +// +// The above copyright notice and this permission notice shall be included in +// all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN +// THE SOFTWARE. +// + +#if os(iOS) || os(tvOS) || os(watchOS) + +import CoreGraphics +import Foundation +import UIKit + +// MARK: Initialization + +private let lock = NSLock() + +extension UIImage { + /// Initializes and returns the image object with the specified data in a thread-safe manner. + /// + /// It has been reported that there are thread-safety issues when initializing large amounts of images + /// simultaneously. In the event of these issues occurring, this method can be used in place of + /// the `init?(data:)` method. + /// + /// - parameter data: The data object containing the image data. + /// + /// - returns: An initialized `UIImage` object, or `nil` if the method failed. + public static func af_threadSafeImage(with data: Data) -> UIImage? { + lock.lock() + let image = UIImage(data: data) + lock.unlock() + + return image + } + + /// Initializes and returns the image object with the specified data and scale in a thread-safe manner. + /// + /// It has been reported that there are thread-safety issues when initializing large amounts of images + /// simultaneously. In the event of these issues occurring, this method can be used in place of + /// the `init?(data:scale:)` method. + /// + /// - parameter data: The data object containing the image data. + /// - parameter scale: The scale factor to assume when interpreting the image data. Applying a scale factor of 1.0 + /// results in an image whose size matches the pixel-based dimensions of the image. Applying a + /// different scale factor changes the size of the image as reported by the size property. + /// + /// - returns: An initialized `UIImage` object, or `nil` if the method failed. + public static func af_threadSafeImage(with data: Data, scale: CGFloat) -> UIImage? { + lock.lock() + let image = UIImage(data: data, scale: scale) + lock.unlock() + + return image + } +} + +// MARK: - Inflation + +extension UIImage { + private struct AssociatedKey { + static var inflated = "af_UIImage.Inflated" + } + + /// Returns whether the image is inflated. + public var af_inflated: Bool { + get { + if let inflated = objc_getAssociatedObject(self, &AssociatedKey.inflated) as? Bool { + return inflated + } else { + return false + } + } + set { + objc_setAssociatedObject(self, &AssociatedKey.inflated, newValue, .OBJC_ASSOCIATION_RETAIN_NONATOMIC) + } + } + + /// Inflates the underlying compressed image data to be backed by an uncompressed bitmap representation. + /// + /// Inflating compressed image formats (such as PNG or JPEG) can significantly improve drawing performance as it + /// allows a bitmap representation to be constructed in the background rather than on the main thread. + public func af_inflate() { + guard !af_inflated else { return } + + af_inflated = true + _ = cgImage?.dataProvider?.data + } +} + +// MARK: - Alpha + +extension UIImage { + /// Returns whether the image contains an alpha component. + public var af_containsAlphaComponent: Bool { + let alphaInfo = cgImage?.alphaInfo + + return ( + alphaInfo == .first || + alphaInfo == .last || + alphaInfo == .premultipliedFirst || + alphaInfo == .premultipliedLast + ) + } + + /// Returns whether the image is opaque. + public var af_isOpaque: Bool { return !af_containsAlphaComponent } +} + +// MARK: - Scaling + +extension UIImage { + /// Returns a new version of the image scaled to the specified size. + /// + /// - parameter size: The size to use when scaling the new image. + /// + /// - returns: A new image object. + public func af_imageScaled(to size: CGSize) -> UIImage { + assert(size.width > 0 && size.height > 0, "You cannot safely scale an image to a zero width or height") + + UIGraphicsBeginImageContextWithOptions(size, af_isOpaque, 0.0) + draw(in: CGRect(origin: .zero, size: size)) + + let scaledImage = UIGraphicsGetImageFromCurrentImageContext() ?? self + UIGraphicsEndImageContext() + + return scaledImage + } + + /// Returns a new version of the image scaled from the center while maintaining the aspect ratio to fit within + /// a specified size. + /// + /// The resulting image contains an alpha component used to pad the width or height with the necessary transparent + /// pixels to fit the specified size. In high performance critical situations, this may not be the optimal approach. + /// To maintain an opaque image, you could compute the `scaledSize` manually, then use the `af_imageScaledToSize` + /// method in conjunction with a `.Center` content mode to achieve the same visual result. + /// + /// - parameter size: The size to use when scaling the new image. + /// + /// - returns: A new image object. + public func af_imageAspectScaled(toFit size: CGSize) -> UIImage { + assert(size.width > 0 && size.height > 0, "You cannot safely scale an image to a zero width or height") + + let imageAspectRatio = self.size.width / self.size.height + let canvasAspectRatio = size.width / size.height + + var resizeFactor: CGFloat + + if imageAspectRatio > canvasAspectRatio { + resizeFactor = size.width / self.size.width + } else { + resizeFactor = size.height / self.size.height + } + + let scaledSize = CGSize(width: self.size.width * resizeFactor, height: self.size.height * resizeFactor) + let origin = CGPoint(x: (size.width - scaledSize.width) / 2.0, y: (size.height - scaledSize.height) / 2.0) + + UIGraphicsBeginImageContextWithOptions(size, false, 0.0) + draw(in: CGRect(origin: origin, size: scaledSize)) + + let scaledImage = UIGraphicsGetImageFromCurrentImageContext() ?? self + UIGraphicsEndImageContext() + + return scaledImage + } + + /// Returns a new version of the image scaled from the center while maintaining the aspect ratio to fill a + /// specified size. Any pixels that fall outside the specified size are clipped. + /// + /// - parameter size: The size to use when scaling the new image. + /// + /// - returns: A new image object. + public func af_imageAspectScaled(toFill size: CGSize) -> UIImage { + assert(size.width > 0 && size.height > 0, "You cannot safely scale an image to a zero width or height") + + let imageAspectRatio = self.size.width / self.size.height + let canvasAspectRatio = size.width / size.height + + var resizeFactor: CGFloat + + if imageAspectRatio > canvasAspectRatio { + resizeFactor = size.height / self.size.height + } else { + resizeFactor = size.width / self.size.width + } + + let scaledSize = CGSize(width: self.size.width * resizeFactor, height: self.size.height * resizeFactor) + let origin = CGPoint(x: (size.width - scaledSize.width) / 2.0, y: (size.height - scaledSize.height) / 2.0) + + UIGraphicsBeginImageContextWithOptions(size, af_isOpaque, 0.0) + draw(in: CGRect(origin: origin, size: scaledSize)) + + let scaledImage = UIGraphicsGetImageFromCurrentImageContext() ?? self + UIGraphicsEndImageContext() + + return scaledImage + } +} + +// MARK: - Rounded Corners + +extension UIImage { + /// Returns a new version of the image with the corners rounded to the specified radius. + /// + /// - parameter radius: The radius to use when rounding the new image. + /// - parameter divideRadiusByImageScale: Whether to divide the radius by the image scale. Set to `true` when the + /// image has the same resolution for all screen scales such as @1x, @2x and + /// @3x (i.e. single image from web server). Set to `false` for images loaded + /// from an asset catalog with varying resolutions for each screen scale. + /// `false` by default. + /// + /// - returns: A new image object. + public func af_imageRounded(withCornerRadius radius: CGFloat, divideRadiusByImageScale: Bool = false) -> UIImage { + UIGraphicsBeginImageContextWithOptions(size, false, 0.0) + + let scaledRadius = divideRadiusByImageScale ? radius / scale : radius + + let clippingPath = UIBezierPath(roundedRect: CGRect(origin: CGPoint.zero, size: size), cornerRadius: scaledRadius) + clippingPath.addClip() + + draw(in: CGRect(origin: CGPoint.zero, size: size)) + + let roundedImage = UIGraphicsGetImageFromCurrentImageContext()! + UIGraphicsEndImageContext() + + return roundedImage + } + + /// Returns a new version of the image rounded into a circle. + /// + /// - returns: A new image object. + public func af_imageRoundedIntoCircle() -> UIImage { + let radius = min(size.width, size.height) / 2.0 + var squareImage = self + + if size.width != size.height { + let squareDimension = min(size.width, size.height) + let squareSize = CGSize(width: squareDimension, height: squareDimension) + squareImage = af_imageAspectScaled(toFill: squareSize) + } + + UIGraphicsBeginImageContextWithOptions(squareImage.size, false, 0.0) + + let clippingPath = UIBezierPath( + roundedRect: CGRect(origin: CGPoint.zero, size: squareImage.size), + cornerRadius: radius + ) + + clippingPath.addClip() + + squareImage.draw(in: CGRect(origin: CGPoint.zero, size: squareImage.size)) + + let roundedImage = UIGraphicsGetImageFromCurrentImageContext()! + UIGraphicsEndImageContext() + + return roundedImage + } +} + +#endif + +#if os(iOS) || os(tvOS) + +import CoreImage + +// MARK: - Core Image Filters + +@available(iOS 9.0, *) +extension UIImage { + /// Returns a new version of the image using a CoreImage filter with the specified name and parameters. + /// + /// - parameter name: The name of the CoreImage filter to use on the new image. + /// - parameter parameters: The parameters to apply to the CoreImage filter. + /// + /// - returns: A new image object, or `nil` if the filter failed for any reason. + public func af_imageFiltered(withCoreImageFilter name: String, parameters: [String: Any]? = nil) -> UIImage? { + var image: CoreImage.CIImage? = ciImage + + if image == nil, let CGImage = self.cgImage { + image = CoreImage.CIImage(cgImage: CGImage) + } + + guard let coreImage = image else { return nil } + + #if swift(>=4.2) + let context = CIContext(options: [.priorityRequestLow: true]) + #else + let context = CIContext(options: [kCIContextPriorityRequestLow: true]) + #endif + + var parameters: [String: Any] = parameters ?? [:] + parameters[kCIInputImageKey] = coreImage + #if swift(>=4.2) + guard let filter = CIFilter(name: name, parameters: parameters) else { return nil } + #else + guard let filter = CIFilter(name: name, withInputParameters: parameters) else { return nil } + #endif + guard let outputImage = filter.outputImage else { return nil } + + let cgImageRef = context.createCGImage(outputImage, from: outputImage.extent) + + return UIImage(cgImage: cgImageRef!, scale: scale, orientation: imageOrientation) + } +} + +#endif diff --git a/Pods/AlamofireImage/Source/UIImageView+AlamofireImage.swift b/Pods/AlamofireImage/Source/UIImageView+AlamofireImage.swift new file mode 100644 index 0000000..431ba19 --- /dev/null +++ b/Pods/AlamofireImage/Source/UIImageView+AlamofireImage.swift @@ -0,0 +1,398 @@ +// +// UIImageView+AlamofireImage.swift +// +// Copyright (c) 2015-2018 Alamofire Software Foundation (http://alamofire.org/) +// +// Permission is hereby granted, free of charge, to any person obtaining a copy +// of this software and associated documentation files (the "Software"), to deal +// in the Software without restriction, including without limitation the rights +// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +// copies of the Software, and to permit persons to whom the Software is +// furnished to do so, subject to the following conditions: +// +// The above copyright notice and this permission notice shall be included in +// all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN +// THE SOFTWARE. +// + +import Alamofire +import Foundation + +#if os(iOS) || os(tvOS) + +import UIKit + +#if swift(>=4.2) +public typealias AnimationOptions = UIView.AnimationOptions +#else +public typealias AnimationOptions = UIViewAnimationOptions +#endif + +extension UIImageView { + + // MARK: - ImageTransition + + /// Used to wrap all `UIView` animation transition options alongside a duration. + public enum ImageTransition { + case noTransition + case crossDissolve(TimeInterval) + case curlDown(TimeInterval) + case curlUp(TimeInterval) + case flipFromBottom(TimeInterval) + case flipFromLeft(TimeInterval) + case flipFromRight(TimeInterval) + case flipFromTop(TimeInterval) + case custom( + duration: TimeInterval, + animationOptions: AnimationOptions, + animations: (UIImageView, Image) -> Void, + completion: ((Bool) -> Void)? + ) + + /// The duration of the image transition in seconds. + public var duration: TimeInterval { + switch self { + case .noTransition: + return 0.0 + case .crossDissolve(let duration): + return duration + case .curlDown(let duration): + return duration + case .curlUp(let duration): + return duration + case .flipFromBottom(let duration): + return duration + case .flipFromLeft(let duration): + return duration + case .flipFromRight(let duration): + return duration + case .flipFromTop(let duration): + return duration + case .custom(let duration, _, _, _): + return duration + } + } + + /// The animation options of the image transition. + public var animationOptions: AnimationOptions { + switch self { + case .noTransition: + return [] + case .crossDissolve: + return .transitionCrossDissolve + case .curlDown: + return .transitionCurlDown + case .curlUp: + return .transitionCurlUp + case .flipFromBottom: + return .transitionFlipFromBottom + case .flipFromLeft: + return .transitionFlipFromLeft + case .flipFromRight: + return .transitionFlipFromRight + case .flipFromTop: + return .transitionFlipFromTop + case .custom(_, let animationOptions, _, _): + return animationOptions + } + } + + /// The animation options of the image transition. + public var animations: ((UIImageView, Image) -> Void) { + switch self { + case .custom(_, _, let animations, _): + return animations + default: + return { $0.image = $1 } + } + } + + /// The completion closure associated with the image transition. + public var completion: ((Bool) -> Void)? { + switch self { + case .custom(_, _, _, let completion): + return completion + default: + return nil + } + } + } + + // MARK: - Private - AssociatedKeys + + private struct AssociatedKey { + static var imageDownloader = "af_UIImageView.ImageDownloader" + static var sharedImageDownloader = "af_UIImageView.SharedImageDownloader" + static var activeRequestReceipt = "af_UIImageView.ActiveRequestReceipt" + } + + // MARK: - Associated Properties + + /// The instance image downloader used to download all images. If this property is `nil`, the `UIImageView` will + /// fallback on the `af_sharedImageDownloader` for all downloads. The most common use case for needing to use a + /// custom instance image downloader is when images are behind different basic auth credentials. + public var af_imageDownloader: ImageDownloader? { + get { + return objc_getAssociatedObject(self, &AssociatedKey.imageDownloader) as? ImageDownloader + } + set(downloader) { + objc_setAssociatedObject(self, &AssociatedKey.imageDownloader, downloader, .OBJC_ASSOCIATION_RETAIN_NONATOMIC) + } + } + + /// The shared image downloader used to download all images. By default, this is the default `ImageDownloader` + /// instance backed with an `AutoPurgingImageCache` which automatically evicts images from the cache when the memory + /// capacity is reached or memory warning notifications occur. The shared image downloader is only used if the + /// `af_imageDownloader` is `nil`. + public class var af_sharedImageDownloader: ImageDownloader { + get { + if let downloader = objc_getAssociatedObject(self, &AssociatedKey.sharedImageDownloader) as? ImageDownloader { + return downloader + } else { + return ImageDownloader.default + } + } + set { + objc_setAssociatedObject(self, &AssociatedKey.sharedImageDownloader, newValue, .OBJC_ASSOCIATION_RETAIN_NONATOMIC) + } + } + + var af_activeRequestReceipt: RequestReceipt? { + get { + return objc_getAssociatedObject(self, &AssociatedKey.activeRequestReceipt) as? RequestReceipt + } + set { + objc_setAssociatedObject(self, &AssociatedKey.activeRequestReceipt, newValue, .OBJC_ASSOCIATION_RETAIN_NONATOMIC) + } + } + + // MARK: - Image Download + + /// Asynchronously downloads an image from the specified URL, applies the specified image filter to the downloaded + /// image and sets it once finished while executing the image transition. + /// + /// If the image is cached locally, the image is set immediately. Otherwise the specified placeholder image will be + /// set immediately, and then the remote image will be set once the image request is finished. + /// + /// The `completion` closure is called after the image download and filtering are complete, but before the start of + /// the image transition. Please note it is no longer the responsibility of the `completion` closure to set the + /// image. It will be set automatically. If you require a second notification after the image transition completes, + /// use a `.Custom` image transition with a `completion` closure. The `.Custom` `completion` closure is called when + /// the image transition is finished. + /// + /// - parameter url: The URL used for the image request. + /// - parameter placeholderImage: The image to be set initially until the image request finished. If + /// `nil`, the image view will not change its image until the image + /// request finishes. Defaults to `nil`. + /// - parameter filter: The image filter applied to the image after the image request is + /// finished. Defaults to `nil`. + /// - parameter progress: The closure to be executed periodically during the lifecycle of the + /// request. Defaults to `nil`. + /// - parameter progressQueue: The dispatch queue to call the progress closure on. Defaults to the + /// main queue. + /// - parameter imageTransition: The image transition animation applied to the image when set. + /// Defaults to `.None`. + /// - parameter runImageTransitionIfCached: Whether to run the image transition if the image is cached. Defaults + /// to `false`. + /// - parameter completion: A closure to be executed when the image request finishes. The closure + /// has no return value and takes three arguments: the original request, + /// the response from the server and the result containing either the + /// image or the error that occurred. If the image was returned from the + /// image cache, the response will be `nil`. Defaults to `nil`. + public func af_setImage( + withURL url: URL, + placeholderImage: UIImage? = nil, + filter: ImageFilter? = nil, + progress: ImageDownloader.ProgressHandler? = nil, + progressQueue: DispatchQueue = DispatchQueue.main, + imageTransition: ImageTransition = .noTransition, + runImageTransitionIfCached: Bool = false, + completion: ((DataResponse) -> Void)? = nil) + { + af_setImage( + withURLRequest: urlRequest(with: url), + placeholderImage: placeholderImage, + filter: filter, + progress: progress, + progressQueue: progressQueue, + imageTransition: imageTransition, + runImageTransitionIfCached: runImageTransitionIfCached, + completion: completion + ) + } + + /// Asynchronously downloads an image from the specified URL Request, applies the specified image filter to the downloaded + /// image and sets it once finished while executing the image transition. + /// + /// If the image is cached locally, the image is set immediately. Otherwise the specified placeholder image will be + /// set immediately, and then the remote image will be set once the image request is finished. + /// + /// The `completion` closure is called after the image download and filtering are complete, but before the start of + /// the image transition. Please note it is no longer the responsibility of the `completion` closure to set the + /// image. It will be set automatically. If you require a second notification after the image transition completes, + /// use a `.Custom` image transition with a `completion` closure. The `.Custom` `completion` closure is called when + /// the image transition is finished. + /// + /// - parameter urlRequest: The URL request. + /// - parameter placeholderImage: The image to be set initially until the image request finished. If + /// `nil`, the image view will not change its image until the image + /// request finishes. Defaults to `nil`. + /// - parameter filter: The image filter applied to the image after the image request is + /// finished. Defaults to `nil`. + /// - parameter progress: The closure to be executed periodically during the lifecycle of the + /// request. Defaults to `nil`. + /// - parameter progressQueue: The dispatch queue to call the progress closure on. Defaults to the + /// main queue. + /// - parameter imageTransition: The image transition animation applied to the image when set. + /// Defaults to `.None`. + /// - parameter runImageTransitionIfCached: Whether to run the image transition if the image is cached. Defaults + /// to `false`. + /// - parameter completion: A closure to be executed when the image request finishes. The closure + /// has no return value and takes three arguments: the original request, + /// the response from the server and the result containing either the + /// image or the error that occurred. If the image was returned from the + /// image cache, the response will be `nil`. Defaults to `nil`. + public func af_setImage( + withURLRequest urlRequest: URLRequestConvertible, + placeholderImage: UIImage? = nil, + filter: ImageFilter? = nil, + progress: ImageDownloader.ProgressHandler? = nil, + progressQueue: DispatchQueue = DispatchQueue.main, + imageTransition: ImageTransition = .noTransition, + runImageTransitionIfCached: Bool = false, + completion: ((DataResponse) -> Void)? = nil) + { + guard !isURLRequestURLEqualToActiveRequestURL(urlRequest) else { + let error = AFIError.requestCancelled + let response = DataResponse(request: nil, response: nil, data: nil, result: .failure(error)) + + completion?(response) + + return + } + + af_cancelImageRequest() + + let imageDownloader = af_imageDownloader ?? UIImageView.af_sharedImageDownloader + let imageCache = imageDownloader.imageCache + + // Use the image from the image cache if it exists + if + let request = urlRequest.urlRequest, + let image = imageCache?.image(for: request, withIdentifier: filter?.identifier) + { + let response = DataResponse(request: request, response: nil, data: nil, result: .success(image)) + + if runImageTransitionIfCached { + let tinyDelay = DispatchTime.now() + Double(Int64(0.001 * Float(NSEC_PER_SEC))) / Double(NSEC_PER_SEC) + + // Need to let the runloop cycle for the placeholder image to take affect + DispatchQueue.main.asyncAfter(deadline: tinyDelay) { + self.run(imageTransition, with: image) + completion?(response) + } + } else { + self.image = image + completion?(response) + } + + return + } + + // Set the placeholder since we're going to have to download + if let placeholderImage = placeholderImage { self.image = placeholderImage } + + // Generate a unique download id to check whether the active request has changed while downloading + let downloadID = UUID().uuidString + + // Download the image, then run the image transition or completion handler + let requestReceipt = imageDownloader.download( + urlRequest, + receiptID: downloadID, + filter: filter, + progress: progress, + progressQueue: progressQueue, + completion: { [weak self] response in + guard + let strongSelf = self, + strongSelf.isURLRequestURLEqualToActiveRequestURL(response.request) && + strongSelf.af_activeRequestReceipt?.receiptID == downloadID + else { + completion?(response) + return + } + + if let image = response.result.value { + strongSelf.run(imageTransition, with: image) + } + + strongSelf.af_activeRequestReceipt = nil + + completion?(response) + } + ) + + af_activeRequestReceipt = requestReceipt + } + + // MARK: - Image Download Cancellation + + /// Cancels the active download request, if one exists. + public func af_cancelImageRequest() { + guard let activeRequestReceipt = af_activeRequestReceipt else { return } + + let imageDownloader = af_imageDownloader ?? UIImageView.af_sharedImageDownloader + imageDownloader.cancelRequest(with: activeRequestReceipt) + + af_activeRequestReceipt = nil + } + + // MARK: - Image Transition + + /// Runs the image transition on the image view with the specified image. + /// + /// - parameter imageTransition: The image transition to ran on the image view. + /// - parameter image: The image to use for the image transition. + public func run(_ imageTransition: ImageTransition, with image: Image) { + UIView.transition( + with: self, + duration: imageTransition.duration, + options: imageTransition.animationOptions, + animations: { imageTransition.animations(self, image) }, + completion: imageTransition.completion + ) + } + + // MARK: - Private - URL Request Helper Methods + + private func urlRequest(with url: URL) -> URLRequest { + var urlRequest = URLRequest(url: url) + + for mimeType in DataRequest.acceptableImageContentTypes { + urlRequest.addValue(mimeType, forHTTPHeaderField: "Accept") + } + + return urlRequest + } + + private func isURLRequestURLEqualToActiveRequestURL(_ urlRequest: URLRequestConvertible?) -> Bool { + if + let currentRequestURL = af_activeRequestReceipt?.request.task?.originalRequest?.url, + let requestURL = urlRequest?.urlRequest?.url, + currentRequestURL == requestURL + { + return true + } + + return false + } +} + +#endif diff --git a/Pods/GiphyCoreSDK/LICENSE b/Pods/GiphyCoreSDK/LICENSE new file mode 100644 index 0000000..a612ad9 --- /dev/null +++ b/Pods/GiphyCoreSDK/LICENSE @@ -0,0 +1,373 @@ +Mozilla Public License Version 2.0 +================================== + +1. Definitions +-------------- + +1.1. "Contributor" + means each individual or legal entity that creates, contributes to + the creation of, or owns Covered Software. + +1.2. "Contributor Version" + means the combination of the Contributions of others (if any) used + by a Contributor and that particular Contributor's Contribution. + +1.3. "Contribution" + means Covered Software of a particular Contributor. + +1.4. "Covered Software" + means Source Code Form to which the initial Contributor has attached + the notice in Exhibit A, the Executable Form of such Source Code + Form, and Modifications of such Source Code Form, in each case + including portions thereof. + +1.5. "Incompatible With Secondary Licenses" + means + + (a) that the initial Contributor has attached the notice described + in Exhibit B to the Covered Software; or + + (b) that the Covered Software was made available under the terms of + version 1.1 or earlier of the License, but not also under the + terms of a Secondary License. + +1.6. "Executable Form" + means any form of the work other than Source Code Form. + +1.7. "Larger Work" + means a work that combines Covered Software with other material, in + a separate file or files, that is not Covered Software. + +1.8. "License" + means this document. + +1.9. "Licensable" + means having the right to grant, to the maximum extent possible, + whether at the time of the initial grant or subsequently, any and + all of the rights conveyed by this License. + +1.10. "Modifications" + means any of the following: + + (a) any file in Source Code Form that results from an addition to, + deletion from, or modification of the contents of Covered + Software; or + + (b) any new file in Source Code Form that contains any Covered + Software. + +1.11. "Patent Claims" of a Contributor + means any patent claim(s), including without limitation, method, + process, and apparatus claims, in any patent Licensable by such + Contributor that would be infringed, but for the grant of the + License, by the making, using, selling, offering for sale, having + made, import, or transfer of either its Contributions or its + Contributor Version. + +1.12. "Secondary License" + means either the GNU General Public License, Version 2.0, the GNU + Lesser General Public License, Version 2.1, the GNU Affero General + Public License, Version 3.0, or any later versions of those + licenses. + +1.13. "Source Code Form" + means the form of the work preferred for making modifications. + +1.14. "You" (or "Your") + means an individual or a legal entity exercising rights under this + License. For legal entities, "You" includes any entity that + controls, is controlled by, or is under common control with You. For + purposes of this definition, "control" means (a) the power, direct + or indirect, to cause the direction or management of such entity, + whether by contract or otherwise, or (b) ownership of more than + fifty percent (50%) of the outstanding shares or beneficial + ownership of such entity. + +2. License Grants and Conditions +-------------------------------- + +2.1. Grants + +Each Contributor hereby grants You a world-wide, royalty-free, +non-exclusive license: + +(a) under intellectual property rights (other than patent or trademark) + Licensable by such Contributor to use, reproduce, make available, + modify, display, perform, distribute, and otherwise exploit its + Contributions, either on an unmodified basis, with Modifications, or + as part of a Larger Work; and + +(b) under Patent Claims of such Contributor to make, use, sell, offer + for sale, have made, import, and otherwise transfer either its + Contributions or its Contributor Version. + +2.2. Effective Date + +The licenses granted in Section 2.1 with respect to any Contribution +become effective for each Contribution on the date the Contributor first +distributes such Contribution. + +2.3. Limitations on Grant Scope + +The licenses granted in this Section 2 are the only rights granted under +this License. No additional rights or licenses will be implied from the +distribution or licensing of Covered Software under this License. +Notwithstanding Section 2.1(b) above, no patent license is granted by a +Contributor: + +(a) for any code that a Contributor has removed from Covered Software; + or + +(b) for infringements caused by: (i) Your and any other third party's + modifications of Covered Software, or (ii) the combination of its + Contributions with other software (except as part of its Contributor + Version); or + +(c) under Patent Claims infringed by Covered Software in the absence of + its Contributions. + +This License does not grant any rights in the trademarks, service marks, +or logos of any Contributor (except as may be necessary to comply with +the notice requirements in Section 3.4). + +2.4. Subsequent Licenses + +No Contributor makes additional grants as a result of Your choice to +distribute the Covered Software under a subsequent version of this +License (see Section 10.2) or under the terms of a Secondary License (if +permitted under the terms of Section 3.3). + +2.5. Representation + +Each Contributor represents that the Contributor believes its +Contributions are its original creation(s) or it has sufficient rights +to grant the rights to its Contributions conveyed by this License. + +2.6. Fair Use + +This License is not intended to limit any rights You have under +applicable copyright doctrines of fair use, fair dealing, or other +equivalents. + +2.7. Conditions + +Sections 3.1, 3.2, 3.3, and 3.4 are conditions of the licenses granted +in Section 2.1. + +3. Responsibilities +------------------- + +3.1. Distribution of Source Form + +All distribution of Covered Software in Source Code Form, including any +Modifications that You create or to which You contribute, must be under +the terms of this License. You must inform recipients that the Source +Code Form of the Covered Software is governed by the terms of this +License, and how they can obtain a copy of this License. You may not +attempt to alter or restrict the recipients' rights in the Source Code +Form. + +3.2. Distribution of Executable Form + +If You distribute Covered Software in Executable Form then: + +(a) such Covered Software must also be made available in Source Code + Form, as described in Section 3.1, and You must inform recipients of + the Executable Form how they can obtain a copy of such Source Code + Form by reasonable means in a timely manner, at a charge no more + than the cost of distribution to the recipient; and + +(b) You may distribute such Executable Form under the terms of this + License, or sublicense it under different terms, provided that the + license for the Executable Form does not attempt to limit or alter + the recipients' rights in the Source Code Form under this License. + +3.3. Distribution of a Larger Work + +You may create and distribute a Larger Work under terms of Your choice, +provided that You also comply with the requirements of this License for +the Covered Software. If the Larger Work is a combination of Covered +Software with a work governed by one or more Secondary Licenses, and the +Covered Software is not Incompatible With Secondary Licenses, this +License permits You to additionally distribute such Covered Software +under the terms of such Secondary License(s), so that the recipient of +the Larger Work may, at their option, further distribute the Covered +Software under the terms of either this License or such Secondary +License(s). + +3.4. Notices + +You may not remove or alter the substance of any license notices +(including copyright notices, patent notices, disclaimers of warranty, +or limitations of liability) contained within the Source Code Form of +the Covered Software, except that You may alter any license notices to +the extent required to remedy known factual inaccuracies. + +3.5. Application of Additional Terms + +You may choose to offer, and to charge a fee for, warranty, support, +indemnity or liability obligations to one or more recipients of Covered +Software. However, You may do so only on Your own behalf, and not on +behalf of any Contributor. You must make it absolutely clear that any +such warranty, support, indemnity, or liability obligation is offered by +You alone, and You hereby agree to indemnify every Contributor for any +liability incurred by such Contributor as a result of warranty, support, +indemnity or liability terms You offer. You may include additional +disclaimers of warranty and limitations of liability specific to any +jurisdiction. + +4. Inability to Comply Due to Statute or Regulation +--------------------------------------------------- + +If it is impossible for You to comply with any of the terms of this +License with respect to some or all of the Covered Software due to +statute, judicial order, or regulation then You must: (a) comply with +the terms of this License to the maximum extent possible; and (b) +describe the limitations and the code they affect. Such description must +be placed in a text file included with all distributions of the Covered +Software under this License. Except to the extent prohibited by statute +or regulation, such description must be sufficiently detailed for a +recipient of ordinary skill to be able to understand it. + +5. Termination +-------------- + +5.1. The rights granted under this License will terminate automatically +if You fail to comply with any of its terms. However, if You become +compliant, then the rights granted under this License from a particular +Contributor are reinstated (a) provisionally, unless and until such +Contributor explicitly and finally terminates Your grants, and (b) on an +ongoing basis, if such Contributor fails to notify You of the +non-compliance by some reasonable means prior to 60 days after You have +come back into compliance. Moreover, Your grants from a particular +Contributor are reinstated on an ongoing basis if such Contributor +notifies You of the non-compliance by some reasonable means, this is the +first time You have received notice of non-compliance with this License +from such Contributor, and You become compliant prior to 30 days after +Your receipt of the notice. + +5.2. If You initiate litigation against any entity by asserting a patent +infringement claim (excluding declaratory judgment actions, +counter-claims, and cross-claims) alleging that a Contributor Version +directly or indirectly infringes any patent, then the rights granted to +You by any and all Contributors for the Covered Software under Section +2.1 of this License shall terminate. + +5.3. In the event of termination under Sections 5.1 or 5.2 above, all +end user license agreements (excluding distributors and resellers) which +have been validly granted by You or Your distributors under this License +prior to termination shall survive termination. + +************************************************************************ +* * +* 6. Disclaimer of Warranty * +* ------------------------- * +* * +* Covered Software is provided under this License on an "as is" * +* basis, without warranty of any kind, either expressed, implied, or * +* statutory, including, without limitation, warranties that the * +* Covered Software is free of defects, merchantable, fit for a * +* particular purpose or non-infringing. The entire risk as to the * +* quality and performance of the Covered Software is with You. * +* Should any Covered Software prove defective in any respect, You * +* (not any Contributor) assume the cost of any necessary servicing, * +* repair, or correction. This disclaimer of warranty constitutes an * +* essential part of this License. No use of any Covered Software is * +* authorized under this License except under this disclaimer. * +* * +************************************************************************ + +************************************************************************ +* * +* 7. Limitation of Liability * +* -------------------------- * +* * +* Under no circumstances and under no legal theory, whether tort * +* (including negligence), contract, or otherwise, shall any * +* Contributor, or anyone who distributes Covered Software as * +* permitted above, be liable to You for any direct, indirect, * +* special, incidental, or consequential damages of any character * +* including, without limitation, damages for lost profits, loss of * +* goodwill, work stoppage, computer failure or malfunction, or any * +* and all other commercial damages or losses, even if such party * +* shall have been informed of the possibility of such damages. This * +* limitation of liability shall not apply to liability for death or * +* personal injury resulting from such party's negligence to the * +* extent applicable law prohibits such limitation. Some * +* jurisdictions do not allow the exclusion or limitation of * +* incidental or consequential damages, so this exclusion and * +* limitation may not apply to You. * +* * +************************************************************************ + +8. Litigation +------------- + +Any litigation relating to this License may be brought only in the +courts of a jurisdiction where the defendant maintains its principal +place of business and such litigation shall be governed by laws of that +jurisdiction, without reference to its conflict-of-law provisions. +Nothing in this Section shall prevent a party's ability to bring +cross-claims or counter-claims. + +9. Miscellaneous +---------------- + +This License represents the complete agreement concerning the subject +matter hereof. If any provision of this License is held to be +unenforceable, such provision shall be reformed only to the extent +necessary to make it enforceable. Any law or regulation which provides +that the language of a contract shall be construed against the drafter +shall not be used to construe this License against a Contributor. + +10. Versions of the License +--------------------------- + +10.1. New Versions + +Mozilla Foundation is the license steward. Except as provided in Section +10.3, no one other than the license steward has the right to modify or +publish new versions of this License. Each version will be given a +distinguishing version number. + +10.2. Effect of New Versions + +You may distribute the Covered Software under the terms of the version +of the License under which You originally received the Covered Software, +or under the terms of any subsequent version published by the license +steward. + +10.3. Modified Versions + +If you create software not governed by this License, and you want to +create a new license for such software, you may create and use a +modified version of this License if you rename the license and remove +any references to the name of the license steward (except to note that +such modified license differs from this License). + +10.4. Distributing Source Code Form that is Incompatible With Secondary +Licenses + +If You choose to distribute Source Code Form that is Incompatible With +Secondary Licenses under the terms of this version of the License, the +notice described in Exhibit B of this License must be attached. + +Exhibit A - Source Code Form License Notice +------------------------------------------- + + This Source Code Form is subject to the terms of the Mozilla Public + License, v. 2.0. If a copy of the MPL was not distributed with this + file, You can obtain one at http://mozilla.org/MPL/2.0/. + +If it is not possible or desirable to put the notice in a particular +file, then You may include the notice in a location (such as a LICENSE +file in a relevant directory) where a recipient would be likely to look +for such a notice. + +You may add additional accurate notices of copyright ownership. + +Exhibit B - "Incompatible With Secondary Licenses" Notice +--------------------------------------------------------- + + This Source Code Form is "Incompatible With Secondary Licenses", as + defined by the Mozilla Public License, v. 2.0. diff --git a/Pods/GiphyCoreSDK/README.md b/Pods/GiphyCoreSDK/README.md new file mode 100644 index 0000000..79ff426 --- /dev/null +++ b/Pods/GiphyCoreSDK/README.md @@ -0,0 +1,356 @@ +# Giphy Core SDK for Swift + + +The **Giphy Core SDK** is a wrapper around [Giphy API](https://github.com/Giphy/GiphyAPI). + +[![Build Status](https://travis-ci.com/Giphy/giphy-ios-sdk-core.svg?token=ApviWy5Ne8UKNzA4xUNJ&branch=master)](https://travis-ci.com/Giphy/giphy-ios-sdk-core) +[![Carthage compatible](https://img.shields.io/badge/Carthage-compatible-4BC51D.svg?style=flat)](https://github.com/Carthage/Carthage) +[![CocoaPods](https://img.shields.io/cocoapods/v/GiphyCoreSDK.svg)]() +[![](https://img.shields.io/badge/OS%20X-10.12%2B-lightgrey.svg)]() +[![](https://img.shields.io/badge/iOS-8.0%2B-lightgrey.svg)]() +[![Swift Version](https://img.shields.io/badge/Swift-4.2-orange.svg)]() + + + + +[Giphy](https://www.giphy.com) is the best way to search, share, and discover GIFs on the Internet. Similar to the way other search engines work, the majority of our content comes from indexing based on the best and most popular GIFs and search terms across the web. We organize all those GIFs so you can find the good content easier and share it out through your social channels. We also feature some of our favorite GIF artists and work with brands to create and promote their original GIF content. + +[![](https://media.giphy.com/media/5xaOcLOqNmWHaLeB14I/giphy.gif)]() + +# Getting Started + +### Supported Platforms + +* iOS +* macOS +* tvOS +* watchOS + +### Supported End-points + +* [Search GIFs/Stickers](#search-endpoint) +* [Trending GIFs/Stickers](#trending-endpoint) +* [Translate GIFs/Stickers](#translate-endpoint) +* [Random GIFs/Stickers](#random-endpoint) +* [GIF by ID](#get-gif-by-id-endpoint) +* [GIFs by IDs](#get-gifs-by-ids-endpoint) +* [Categories for GIFs](#categories-endpoint) +* [Subcategories for GIFs](#sub-categories-endpoint) +* [GIFs for a Subcategory](#sub-category-content-endpoint) +* [Term Suggestions](#term-suggestions-endpoint) + +### Advanced Usage + +* [Filtering](#filtering-models) +* [User Dictionaries](#user-dictionaries) + +# Setup + +### CocoaPods Setup + +Add the GiphyCoreSDK entry to your Podfile + +``` +pod 'GiphyCoreSDK' +``` + +Run pods to grab the GiphyCoreSDK framework + +```bash +pod install +``` + +### Carthage Setup + +Add the GiphyCoreSDK entry to your Cartfile + +``` +git "git@github.com:Giphy/giphy-ios-sdk-core.git" "master" +``` + +Run carthage update to grab the GiphyCoreSDK framework + +```bash +carthage update +``` + +### Swift Package Manager Setup + +* Add .package(url:"https://github.com/Giphy/giphy-ios-sdk-core", from: "1.2.0") to your package dependencies. +* Then add GiphyCoreSDK to your target dependencies. + +### Initialize Giphy SDK + +```swift +// Configure your API Key +GiphyCore.configure(apiKey: "YOUR_API_KEY") +``` + +### Search Endpoint +Search all Giphy GIFs for a word or phrase. Punctuation will be stripped and ignored. + +```swift +/// Gif Search +let op = GiphyCore.shared.search("cats") { (response, error) in + + if let error = error as NSError? { + // Do what you want with the error + } + + if let response = response, let data = response.data, let pagination = response.pagination { + print(response.meta) + print(pagination) + for result in data { + print(result) + } + } else { + print("No Results Found") + } +} + +/// Sticker Search +let op = GiphyCore.shared.search("dogs", media: .sticker) { (response, error) in + //... +} +``` + +### Trending Endpoint +Fetch GIFs currently trending online. Hand curated by the Giphy editorial team. The data returned mirrors the GIFs showcased on the [Giphy](https://www.giphy.com) homepage. + +```swift +/// Trending GIFs +let op = GiphyCore.shared.trending() { (response, error) in + //... +} + +/// Trending Stickers +let op = GiphyCore.shared.trending(.sticker) { (response, error) in + //... +} +``` + +### Translate Endpoint +The translate API draws on search, but uses the Giphy "special sauce" to handle translating from one vocabulary to another. In this case, words and phrases to GIFs. Example implementations of translate can be found in the Giphy Slack, Hipchat, Wire, or Dasher integrations. Use a plus or url encode for phrases. + +```swift +/// Translate to a GIF +let op = GiphyCore.shared.translate("cats") { (response, error) in + //... +} + +/// Translate to a Sticker +let op = GiphyCore.shared.translate("cats", media: .sticker) { (response, error) in + //... +} +``` + +### Random Endpoint +Returns a random GIF, limited by tag. Excluding the tag parameter will return a random GIF from the Giphy catalog. + +```swift +/// Random GIF +let op = GiphyCore.shared.random("cats") { (response, error) in + + if let error = error as NSError? { + // Do what you want with the error + } + + if let response = response, let data = response.data { + print(response.meta) + print(data) + } else { + print("No Result Found") + } +} + +/// Random Sticker +let op = GiphyCore.shared.random("cats", media: .sticker) { (response, error) in + //... +} +``` + +### Get GIF by ID Endpoint +Returns meta data about a GIF, by GIF id. In the below example, the GIF ID is "feqkVgjJpYtjy" + +```swift +/// Gif by Id +let op = GiphyCore.shared.gifByID("feqkVgjJpYtjy") { (response, error) in + //... +} +``` + +### Get GIFs by IDs Endpoint +A multiget version of the get GIF by ID endpoint. In this case the IDs are feqkVgjJpYtjy and 7rzbxdu0ZEXLy. + +```swift +/// GIFs by Ids +let ids = ["feqkVgjJpYtjy", "7rzbxdu0ZEXLy"] + +let op = GiphyCore.shared.gifsByIDs(ids) { (response, error) in + + if let error = error as NSError? { + // Do what you want with the error + } + + if let response = response, let data = response.data, let pagination = response.pagination { + print(response.meta) + print(pagination) + for result in data { + print(result) + } + } else { + print("No Result Found") + } +} +``` + +### Categories Endpoint +A multiget version of the get GIF by ID endpoint. In this case the IDs are feqkVgjJpYtjy and 7rzbxdu0ZEXLy. + +```swift +/// Get top trending categories for GIFs. +let op = GiphyCore.shared.categoriesForGifs() { (response, error) in + + if let error = error as NSError? { + // Do what you want with the error + } + + if let response = response, let data = response.data, let pagination = response.pagination { + print(response.meta) + print(pagination) + for result in data { + print(result) + } + } else { + print("No Top Categories Found") + } +} +``` + +### Sub-Categories Endpoint +Get Sub-Categories for GIFs given a cateory. You will need this sub-category object to pull GIFs for this category. + +```swift +/// Sub-Categories for a given category. +let category = "actions" + +let op = GiphyCore.shared.subCategoriesForGifs(category) { (response, error) in + + if let error = error as NSError? { + // Do what you want with the error + } + + if let response = response, let data = response.data, let pagination = response.pagination { + print(response.meta) + print(pagination) + for subcategory in data { + print(subcategory) + } + } else { + print("No Result Found") + } +} +``` + +### Sub-Category Content Endpoint +Get GIFs for a given Sub-Category. + +```swift +/// Sub-Category Content +let category = "actions" +let subCategory = "cooking" + +let op = GiphyCore.shared.gifsByCategory(category, subCategory: subCategory) { (response, error) in + + if let error = error as NSError? { + // Do what you want with the error + } + + if let response = response, let data = response.data, let pagination = response.pagination { + print(response.meta) + print(pagination) + for result in data { + print(result) + } + } else { + print("No GIFs Found") + } +} +``` + + +### Term Suggestions Endpoint +Get term suggestions give a search term, or a substring. + +```swift +/// Term Suggestions +let op = GiphyCore.shared.termSuggestions("carm") { (response, error) in + + if let error = error as NSError? { + // Do what you want with the error + } + + if let response = response, let data = response.data { + print(response.meta) + for term in data { + print(term) + } + } else { + print("No Terms Suggestions Found") + } +} +``` + +# Advanced Usage + +## Filtering Models + +We added support for you to filter results of any models out during requests. Here are few use cases below in code: + +```swift +GiphyCore.setFilter(filter: { obj in + if let obj = obj as? GPHMedia { + + // Check to see if this Media object has tags + // Say we only want GIFs/Stickers with tags, otherwise filter them out + return obj.tags == nil + + } else if let obj = obj as? GPHChannel { + + // We only want channels which have featured Gifs + return obj.featuredGif != false + } + + // Otherwise this is a valid object, don't filter it out + return true + }) +``` + +## User Dictionaries + +We figured you might want to attach extra data to our models such us `GPHMedia` .. so now all our models have `userDictionary` +which you can attach any sort of object along with any of our models. + +```swift +/// Gif Search +let op = GiphyCore.shared.search("cats") { (response, error) in + + if let error = error as NSError? { + ...... + } + + if let response = response, let data = response.data, let pagination = response.pagination { + for result in data { + result.userDictionary = ["Description" : "Results from Cats Search"] + } + } else { + print("No Results Found") + } +} +``` + + + + + + diff --git a/Pods/GiphyCoreSDK/Sources/GPHAbstractClient.swift b/Pods/GiphyCoreSDK/Sources/GPHAbstractClient.swift new file mode 100644 index 0000000..bdd1193 --- /dev/null +++ b/Pods/GiphyCoreSDK/Sources/GPHAbstractClient.swift @@ -0,0 +1,166 @@ +// +// GPHAbstractClient.swift +// GiphyCoreSDK +// +// Created by Cem Kozinoglu, Gene Goykhman, Giorgia Marenda on 4/24/17. +// Copyright © 2017 Giphy. All rights reserved. +// +// This Source Code Form is subject to the terms of the Mozilla Public +// License, v. 2.0. If a copy of the MPL was not distributed with this +// file, You can obtain one at http://mozilla.org/MPL/2.0/. +// + +import Foundation + + +/// GIPHY Abstract API Client. +/// +@objc open class GPHAbstractClient : NSObject { + // MARK: Properties + + /// Giphy API key. + @objc open var _apiKey: String? + + /// Session + var session: URLSession + + /// Default timeout for network requests. Default: 10 seconds. + @objc open var timeout: TimeInterval = 10 + + /// Operation queue used to keep track of network requests. + let requestQueue: OperationQueue + + /// Maximum number of concurrent requests we allow per connection. + private let maxConcurrentRequestsPerConnection = 4 + + #if !os(watchOS) + + /// Network reachability detecter. + var reachability: GPHNetworkReachability = GPHNetworkReachability() + + /// Network reachability status. Not supported in watchOS. + @objc open var useReachability: Bool = true + + #endif + + // MARK: Initialization + + /// Initializer + /// + /// - parameter apiKey: Application api-key to access GIPHY endpoints. + /// + public init(_ apiKey: String?) { + self._apiKey = apiKey + + var clientHTTPHeaders: [String: String] = [:] + clientHTTPHeaders["User-Agent"] = GPHAbstractClient.defaultUserAgent() + let configuration = URLSessionConfiguration.default + configuration.httpAdditionalHeaders = clientHTTPHeaders + + session = Foundation.URLSession(configuration: configuration) + + requestQueue = OperationQueue() + requestQueue.name = "Giphy API Requests" + requestQueue.maxConcurrentOperationCount = configuration.httpMaximumConnectionsPerHost * maxConcurrentRequestsPerConnection + + super.init() + } + + // MARK: Request Methods and Helpers + + /// User-agent to be used per client + /// + /// - returns: Default User-Agent for the SDK + /// + private static func defaultUserAgent() -> String { + + guard + let dictionary = Bundle.main.infoDictionary, + let version = dictionary["CFBundleShortVersionString"] as? String + else { return "Giphy SDK (iOS)" } + return "Giphy SDK v\(version) (iOS)" + } + + + /// Encode Strings for appending to URLs for endpoints like Term Suggestions/Categories + /// + /// - parameter string: String to be encoded. + /// - returns: A percent encoded string. + /// + @objc + func encodedStringForUrl(_ string: String) -> String { + + guard + let encoded = string.addingPercentEncoding(withAllowedCharacters: .urlHostAllowed) + else { return string } + return encoded + } + + + /// Perform a request + /// + /// - parameter config: GPHRequestConfig + /// - parameter completionHandler: Completion handler to be notified of the request's outcome. + /// - returns: A cancellable operation. + /// + @objc + @discardableResult public func httpRequest(with config: GPHRequestConfig, completionHandler: @escaping GPHJSONCompletionHandler) -> Operation { + + let operation = GPHRequest(self, config: config, completionHandler: completionHandler) + self.requestQueue.addOperation(operation) + + return operation + } + + + /// Parses a JSON response to an HTTP request expected to return a particular GPHMappable response. + /// + /// - parameter config: GPHRequestConfig + /// - parameter completionHandler: Completion handler to be notified of the request's outcome. + /// - returns: GPHJSONCompletionHandler to be used as a completion handler for an HTTP request. + /// + public class func parseJSONResponse(_ config: GPHRequestConfig, + completionHandler: @escaping ((_ response: T?, _ error: Error?) -> Void)) -> GPHJSONCompletionHandler where T : GPHResponse, T : GPHMappable { + + return { (data, response, error) in + // Error returned + + if let error = error as? GPHHTTPError, (error.errorCode < 400 && error.errorCode >= 500) { + completionHandler(nil, error) + return + } + + // Handle the (impossible?) case where there is no data back from the server, + // but there is no error returned + guard let data = data else { + completionHandler(nil, GPHJSONMappingError(description: "No data returned from the server, but no error reported.")) + return + } + + do { + let mappableObject: T.GPHMappableObject = try T.mapData(data, options: config.options ?? [:]) + guard let obj = mappableObject as? T else { + completionHandler(nil, GPHJSONMappingError(description: "Couldn't cast " + String(describing: T.GPHMappableObject.self) + " to " + String(describing: T.self) + " during JSON response parsing.")) + return + } + completionHandler(obj, error) + } catch { + completionHandler(nil, error) + } + } + } + + + #if !os(watchOS) + + /// Figure out network connectivity + /// + /// - returns: `true` if network is reachable + /// + public func isNetworkReachable() -> Bool { + return !useReachability || reachability.isReachable() + } + + #endif + +} diff --git a/Pods/GiphyCoreSDK/Sources/GPHAsyncOperation.swift b/Pods/GiphyCoreSDK/Sources/GPHAsyncOperation.swift new file mode 100644 index 0000000..e199997 --- /dev/null +++ b/Pods/GiphyCoreSDK/Sources/GPHAsyncOperation.swift @@ -0,0 +1,111 @@ +// +// GPHAsyncOperation.swift +// GiphyCoreSDK +// +// Created by Cem Kozinoglu, Gene Goykhman, Giorgia Marenda on 4/24/17. +// Copyright © 2017 Giphy. All rights reserved. +// +// This Source Code Form is subject to the terms of the Mozilla Public +// License, v. 2.0. If a copy of the MPL was not distributed with this +// file, You can obtain one at http://mozilla.org/MPL/2.0/. +// + +import Foundation + +/// Sub-classing Operation to make sure we manage its state correctly +/// +@objcMembers public class GPHAsyncOperation: Operation { + // MARK: Properties + + /// State enum to use KVO trick. (cool trick from raywenderlich) + public enum State: String { + case ready, executing, finished + + /// Keypath for KVO + fileprivate var keyPath: String { + return "is" + rawValue.capitalized + } + } + + /// State of the operation. + open var state = State.ready { + + // Using KVO to update state + willSet { + willChangeValue(forKey: newValue.keyPath) + willChangeValue(forKey: state.keyPath) + } + didSet { + didChangeValue(forKey: oldValue.keyPath) + didChangeValue(forKey: state.keyPath) + } + } +} + +/// State management +/// +extension GPHAsyncOperation { + // MARK: Properties + + /// To handle KVO for ready state + override open var isReady: Bool { + return super.isReady && state == .ready + } + + /// To handle KVO for ready executing + override open var isExecuting: Bool { + return state == .executing + } + + /// To handle KVO for finished state + override open var isFinished: Bool { + return state == .finished + } + + /// Override so we can claim to be async. + override open var isAsynchronous: Bool { + return true + } + + /// Override to manage the state correctly for async. + override open func start() { + if isCancelled { + state = .finished + return + } + + main() + state = .executing + } + + /// Override to handle canceling so we can change the state to trigger KVO. + override open func cancel() { + super.cancel() + state = .finished + } +} + +/// A specific type of async operation with a completion handler. +/// +@objcMembers public class GPHAsyncOperationWithCompletion: GPHAsyncOperation { + // MARK: Properties + + /// User completion block to be called. + let completion: GPHJSONCompletionHandler? + + init(completionHandler: GPHJSONCompletionHandler?) { + self.completion = completionHandler + } + + /// Finish this operation. + /// This method should be called exactly once per operation. + internal func callCompletion(data: GPHJSONObject?, response: URLResponse?, error: Error?) { + if !isCancelled { + if let completion = completion { + completion(data, response, error) + } + state = .finished + } + } + +} diff --git a/Pods/GiphyCoreSDK/Sources/GPHBottleData.swift b/Pods/GiphyCoreSDK/Sources/GPHBottleData.swift new file mode 100644 index 0000000..1050a8a --- /dev/null +++ b/Pods/GiphyCoreSDK/Sources/GPHBottleData.swift @@ -0,0 +1,114 @@ +// +// GPHBottleData.swift +// GiphyCoreSDK +// +// Created by Cem Kozinoglu, Gene Goykhman, Giorgia Marenda on 3/13/18. +// Copyright © 2018 Giphy. All rights reserved. +// +// This Source Code Form is subject to the terms of the Mozilla Public +// License, v. 2.0. If a copy of the MPL was not distributed with this +// file, You can obtain one at http://mozilla.org/MPL/2.0/. +// + +import Foundation + +/// Represents a Giphy Bottle Data +/// +@objcMembers public class GPHBottleData: GPHFilterable, NSCoding { + // MARK: Properties + + /// Tid. + public private(set) var tid: String = "" + + /// Tags. + public private(set) var tags: [String]? + + /// JSON Representation. + public fileprivate(set) var jsonRepresentation: GPHJSONObject? + + /// User Dictionary to Store data in Obj by the Developer + public var userDictionary: [String: Any]? + + // MARK: Initializers + + /// Convenience Initializer + /// + /// - parameter tid: tid. + /// + convenience public init(_ tid: String) { + self.init() + self.tid = tid + } + + //MARK: NSCoding + + required convenience public init?(coder aDecoder: NSCoder) { + guard let tid = aDecoder.decodeObject(forKey: "tid") as? String + else { return nil } + + self.init(tid) + self.jsonRepresentation = aDecoder.decodeObject(forKey: "jsonRepresentation") as? GPHJSONObject + self.tags = aDecoder.decodeObject(forKey: "tags") as? [String] + self.userDictionary = aDecoder.decodeObject(forKey: "userDictionary") as? [String: Any] + } + + public func encode(with aCoder: NSCoder) { + aCoder.encode(self.tid, forKey: "tid") + aCoder.encode(self.tags, forKey: "tags") + aCoder.encode(self.jsonRepresentation, forKey: "jsonRepresentation") + aCoder.encode(self.userDictionary, forKey: "userDictionary") + } + + // MARK: NSObject + + override public func isEqual(_ object: Any?) -> Bool { + if object as? GPHBottleData === self { + return true + } + if let other = object as? GPHBottleData, self.tid == other.tid { + return true + } + return false + } + + override public var hash: Int { + return "gph_bottle_\(self.tid)".hashValue + } + +} + +// MARK: Extension -- Human readable + +/// Make objects human readable. +/// +extension GPHBottleData { + + override public var description: String { + return "GPHBottleData(\(self.tid))" + } + +} + +// MARK: Extension -- Parsing & Mapping + +/// For parsing/mapping protocol. +/// +extension GPHBottleData: GPHMappable { + + /// This is where the magic/mapping happens + error handling. + public static func mapData(_ data: GPHJSONObject, options: [String: Any?]) throws -> GPHBottleData { + + guard + let tid = data["tid"] as? String + else { + throw GPHJSONMappingError(description: "Couldn't map GPHBottleData for \(data)") + } + + let obj = GPHBottleData(tid) + + obj.tags = data["tags"] as? [String] + obj.jsonRepresentation = data + return obj + } + +} diff --git a/Pods/GiphyCoreSDK/Sources/GPHCategory.swift b/Pods/GiphyCoreSDK/Sources/GPHCategory.swift new file mode 100644 index 0000000..c181f2a --- /dev/null +++ b/Pods/GiphyCoreSDK/Sources/GPHCategory.swift @@ -0,0 +1,195 @@ +// +// GPHCategory.swift +// GiphyCoreSDK +// +// Created by Cem Kozinoglu, Gene Goykhman, Giorgia Marenda on 4/24/17. +// Copyright © 2017 Giphy. All rights reserved. +// +// This Source Code Form is subject to the terms of the Mozilla Public +// License, v. 2.0. If a copy of the MPL was not distributed with this +// file, You can obtain one at http://mozilla.org/MPL/2.0/. +// + +import Foundation + +/// Represents Giphy Categories & Subcategories +/// +@objcMembers public class GPHCategory: GPHFilterable, NSCoding { + // MARK: Properties + + /// Name of the Category. + public fileprivate(set) var name: String = "" + + /// Encoded name of the Category. + public fileprivate(set) var nameEncoded: String = "" + + /// URL Encoded path of the Category (to make sure we have the full-path for subcategories). + public fileprivate(set) var encodedPath: String = "" + + /// GIF representation of the Category. + public fileprivate(set) var gif: GPHMedia? + + /// Subcategories of the Category. + public fileprivate(set) var subCategories: [GPHCategory]? + + /// JSON Representation. + public fileprivate(set) var jsonRepresentation: GPHJSONObject? + + /// User Dictionary to Store data in Obj by the Developer + public var userDictionary: [String: Any]? + + // MARK: Initializers + + /// Convenience Initializer + /// + /// - parameter name: Name of the Category. + /// - parameter nameEncoded: URL Encoded name of the Category. + /// - parameter encodedPath: URL Encoded path of the Category (to make sure we have the full-path for subcategories). + /// + convenience public init(_ name: String, nameEncoded: String, encodedPath: String) { + self.init() + self.name = name + self.nameEncoded = nameEncoded + self.encodedPath = encodedPath + } + + //MARK: NSCoding + + required convenience public init?(coder aDecoder: NSCoder) { + guard + let name = aDecoder.decodeObject(forKey: "name") as? String, + let nameEncoded = aDecoder.decodeObject(forKey: "nameEncoded") as? String, + let encodedPath = aDecoder.decodeObject(forKey: "encodedPath") as? String + else { + return nil + } + + self.init(name, nameEncoded: nameEncoded, encodedPath: encodedPath) + + self.gif = aDecoder.decodeObject(forKey: "gif") as? GPHMedia + self.subCategories = aDecoder.decodeObject(forKey: "subCategories") as? [GPHCategory] + self.jsonRepresentation = aDecoder.decodeObject(forKey: "jsonRepresentation") as? GPHJSONObject + self.userDictionary = aDecoder.decodeObject(forKey: "userDictionary") as? [String: Any] + } + + public func encode(with aCoder: NSCoder) { + aCoder.encode(self.name, forKey: "name") + aCoder.encode(self.nameEncoded, forKey: "nameEncoded") + aCoder.encode(self.encodedPath, forKey: "encodedPath") + aCoder.encode(self.gif, forKey: "gif") + aCoder.encode(self.subCategories, forKey: "subCategories") + aCoder.encode(self.jsonRepresentation, forKey: "jsonRepresentation") + aCoder.encode(self.userDictionary, forKey: "userDictionary") + } + + // MARK: NSObject + + override public func isEqual(_ object: Any?) -> Bool { + if object as? GPHCategory === self { + return true + } + if let other = object as? GPHCategory, self.name == other.name { + return true + } + return false + } + + override public var hash: Int { + return "gph_category_\(self.name)".hashValue + } + +} + +// MARK: Extension -- Helper Methods + +/// Picking renditions and stuff. +/// +extension GPHCategory { + + @objc + public func addSubCategory(_ subCategory: GPHCategory) { + if self.subCategories != nil { + self.subCategories?.append(subCategory) + } else { + self.subCategories = [subCategory]; + } + } + +} + +// MARK: Extension -- Human readable + +/// Make objects human readable. +/// +extension GPHCategory { + + override public var description: String { + return "GPHCategory(\(self.name)) encoded: \(self.nameEncoded) and path:\(self.encodedPath)" + } + +} + +// MARK: Extension -- Parsing & Mapping + +/// For parsing/mapping protocol. +/// +extension GPHCategory: GPHMappable { + + /// This is where the magic/mapping happens + error handling. + public static func mapData(_ data: GPHJSONObject, options: [String: Any?]) throws -> GPHCategory { + + guard let requestType = options["request"] as? String else { + throw GPHJSONMappingError(description: "Need Request type to map the data") + } + + guard let name = data["name"] as? String, + let nameEncoded = data["name_encoded"] as? String + else { + throw GPHJSONMappingError(description: "Couldn't map GPHCategory for \(data)") + } + + let obj = GPHCategory(name, nameEncoded: nameEncoded, encodedPath: "") + + var gif: GPHMedia? = nil + + if let gifData = data["gif"] as? GPHJSONObject { + gif = try GPHMedia.mapData(gifData, options: options) + } + + obj.gif = gif + + switch requestType { + case "categories": + obj.encodedPath = nameEncoded + + if let subCategoriesJSON = data["subcategories"] as? [GPHJSONObject] { + if subCategoriesJSON.count > 0 { + obj.subCategories = [] + for subCategoryJSON in subCategoriesJSON { + // Create all the sub categories + var optionsCopy = options + optionsCopy["root"] = obj + optionsCopy["request"] = "subCategories" + let subObj = try GPHCategory.mapData(subCategoryJSON, options: optionsCopy) + obj.subCategories?.append(subObj) + } + } + } + + case "subCategories": + guard let root = options["root"] as? GPHCategory else { + throw GPHJSONMappingError(description: "Root object can not be nil, expected a GPHCategory") + } + obj.encodedPath = root.nameEncoded + "/" + nameEncoded + obj.subCategories = nil + + default: + throw GPHJSONMappingError(description: "Request type is not valid for Categories") + } + + obj.jsonRepresentation = data + + return obj + } + +} diff --git a/Pods/GiphyCoreSDK/Sources/GPHChannel.swift b/Pods/GiphyCoreSDK/Sources/GPHChannel.swift new file mode 100644 index 0000000..f1c5f25 --- /dev/null +++ b/Pods/GiphyCoreSDK/Sources/GPHChannel.swift @@ -0,0 +1,191 @@ +// +// GPHChannel.swift +// GiphyCoreSDK +// +// Created by Cem Kozinoglu, Gene Goykhman, Giorgia Marenda on 4/24/17. +// Copyright © 2017 Giphy. All rights reserved. +// +// This Source Code Form is subject to the terms of the Mozilla Public +// License, v. 2.0. If a copy of the MPL was not distributed with this +// file, You can obtain one at http://mozilla.org/MPL/2.0/. +// + +import Foundation + +/// Represents Giphy Channels +/// +@objcMembers public class GPHChannel: GPHFilterable, NSCoding { + // MARK: Properties + + // Stickers Packs Channel Root ID + public static let StickersRootId = 3143 + + /// ID of this Channel. + public fileprivate(set) var id: Int = 0 + + /// Slug of the Channel. + public fileprivate(set) var slug: String? + + /// Display name of the Channel. + public fileprivate(set) var displayName: String? + + /// Shortd display name of the Channel. + public fileprivate(set) var shortDisplayName: String? + + /// Type for this Channel. + public fileprivate(set) var type: String? + + /// Content Type (Gif or Sticker) of the Channel + public fileprivate(set) var contentType: String? + + /// Description of the Channel. + public fileprivate(set) var descriptionText: String? + + /// Banner Image of the Channel. + public fileprivate(set) var bannerImage: String? + + /// [optional] The featured gif for the pack itself. + public fileprivate(set) var featuredGif: GPHMedia? + + /// User who owns this Channel. + public fileprivate(set) var user: GPHUser? + + /// A list of tags for this Channel. + public fileprivate(set) var tags: Array? + + /// A list of direct ancestors of this Channel. + public fileprivate(set) var ancestors: Array = [] + + /// JSON Representation. + public fileprivate(set) var jsonRepresentation: GPHJSONObject? + + /// User Dictionary to Store data in Obj by the Developer + public var userDictionary: [String: Any]? + + /// Convenience Initializer + /// + /// - parameter id: ID of the Channel. + /// + convenience public init(_ id: Int) { + self.init() + self.id = id + } + + //MARK: NSCoding + + required convenience public init?(coder aDecoder: NSCoder) { + guard + let id = aDecoder.decodeObject(forKey: "id") as? Int + else { + return nil + } + + self.init(id) + + self.slug = aDecoder.decodeObject(forKey: "slug") as? String + self.type = aDecoder.decodeObject(forKey: "type") as? String + self.contentType = aDecoder.decodeObject(forKey: "content_type") as? String + self.bannerImage = aDecoder.decodeObject(forKey: "banner_image") as? String + self.displayName = aDecoder.decodeObject(forKey: "display_name") as? String + self.shortDisplayName = aDecoder.decodeObject(forKey: "short_display_name") as? String + self.descriptionText = aDecoder.decodeObject(forKey: "description") as? String + self.user = aDecoder.decodeObject(forKey: "user") as? GPHUser + self.featuredGif = aDecoder.decodeObject(forKey: "featured_gif") as? GPHMedia ?? nil + self.tags = aDecoder.decodeObject(forKey: "tags") as? Array ?? [] + self.ancestors = aDecoder.decodeObject(forKey: "ancestors") as? Array ?? [] + self.jsonRepresentation = aDecoder.decodeObject(forKey: "jsonRepresentation") as? GPHJSONObject + self.userDictionary = aDecoder.decodeObject(forKey: "userDictionary") as? [String: Any] + } + + public func encode(with aCoder: NSCoder) { + aCoder.encode(self.id, forKey: "id") + aCoder.encode(self.slug, forKey: "slug") + aCoder.encode(self.type, forKey: "type") + aCoder.encode(self.bannerImage, forKey: "banner_image") + aCoder.encode(self.contentType, forKey: "content_type") + aCoder.encode(self.displayName, forKey: "display_name") + aCoder.encode(self.descriptionText, forKey: "description") + aCoder.encode(self.shortDisplayName, forKey: "short_display_name") + aCoder.encode(self.user, forKey: "user") + aCoder.encode(self.tags, forKey: "tags") + aCoder.encode(self.ancestors, forKey: "ancestors") + aCoder.encode(self.featuredGif, forKey: "featured_gif") + aCoder.encode(self.jsonRepresentation, forKey: "jsonRepresentation") + aCoder.encode(self.userDictionary, forKey: "userDictionary") + } + + // MARK: NSObject + + override public func isEqual(_ object: Any?) -> Bool { + if object as? GPHChannel === self { + return true + } + if let other = object as? GPHChannel, self.id == other.id { + return true + } + return false + } + + override public var hash: Int { + return "gph_channel_\(self.id)".hashValue + } + + +} + +/// Make objects human readable. +/// +extension GPHChannel { + + override public var description: String { + return "GPHChannel(\(self.displayName ?? "unknown")) id: \(self.id)" + } + +} + +extension GPHChannel: GPHMappable { + + /// This is where the magic/mapping happens + error handling. + public static func mapData(_ data: GPHJSONObject, options: [String: Any?]) throws -> GPHChannel { + guard + let objId: Int = data["id"] as? Int + else { + throw GPHJSONMappingError(description: "Couldn't map GPHChannel due to missing 'id' field \(data)") + } + + let obj = GPHChannel() + + // These fields are OPTIONAL in the sense that we won't `throw` if they're missing + // (though we might want to reconsider some of them). + obj.id = objId + obj.slug = (data["slug"] as? String) + obj.displayName = (data["display_name"] as? String) + obj.shortDisplayName = (data["short_display_name"] as? String) + obj.type = (data["type"] as? String) + obj.contentType = (data["content_type"] as? String) + obj.descriptionText = (data["description"] as? String) + obj.bannerImage = (data["banner_image"] as? String) + obj.tags = (data["tags"] as? [GPHChannelTag]) + + obj.jsonRepresentation = data + + if let imageData = data["featured_gif"] as? GPHJSONObject { + obj.featuredGif = try GPHMedia.mapData(imageData, options: options) + } + + // Handle User Data + if let userData = data["user"] as? GPHJSONObject { + obj.user = try GPHUser.mapData(userData, options: options) + } + + if let ancestors = data["ancestors"] as? [GPHJSONObject] { + for ancestor in ancestors { + let ancestor = try GPHChannel.mapData(ancestor, options: options) + obj.ancestors.append(ancestor) + } + } + + return obj + } + +} diff --git a/Pods/GiphyCoreSDK/Sources/GPHChannelResponse.swift b/Pods/GiphyCoreSDK/Sources/GPHChannelResponse.swift new file mode 100644 index 0000000..bfdac14 --- /dev/null +++ b/Pods/GiphyCoreSDK/Sources/GPHChannelResponse.swift @@ -0,0 +1,75 @@ +// +// GPHChannelResponse.swift +// GiphyCoreSDK +// +// Created by Cem Kozinoglu, Gene Goykhman, Giorgia Marenda, David Hargat on 4/24/17. +// Copyright © 2017 Giphy. All rights reserved. +// +// This Source Code Form is subject to the terms of the Mozilla Public +// License, v. 2.0. If a copy of the MPL was not distributed with this +// file, You can obtain one at http://mozilla.org/MPL/2.0/. +// + +import Foundation + +/// Represents a Giphy List Channel Response (multiple results) +/// +@objcMembers public class GPHChannelResponse: GPHResponse { + // MARK: Properties + + /// Channel object. + public fileprivate(set) var data: GPHChannel? + + // MARK: Initializers + + /// Convenience Initializer + /// + /// - parameter meta: init with a GPHMeta object. + /// - parameter data: GPHChannel object. + /// + convenience public init(_ meta: GPHMeta, data: GPHChannel?) { + self.init() + self.data = data + self.meta = meta + } +} + +// MARK: Extension -- Human readable + +/// Make objects human readable. +/// +extension GPHChannelResponse { + + override public var description: String { + return "GPHChannelResponse(\(self.meta.responseId) status: \(self.meta.status) msg: \(self.meta.msg))" + } + +} + +// MARK: Extension -- Parsing & Mapping +extension GPHChannelResponse: GPHMappable { + + public static func mapData(_ data: GPHJSONObject, options: [String: Any?]) throws -> GPHChannelResponse { + + guard + let metaData = data["meta"] as? GPHJSONObject + else { + throw GPHJSONMappingError(description: "Couldn't map GPHChannel due to missing 'meta' field: \(data)") + } + + guard + let channelData = data["data"] as? GPHJSONObject + else { + throw GPHJSONMappingError(description: "Couldn't map GPHChannel due to missing 'data' field: \(data)") + } + + let meta = try GPHMeta.mapData(metaData, options: options) + let channel = try GPHChannel.mapData(channelData, options: options) + + if channel.isValidObject() { + return GPHChannelResponse(meta, data: channel) + } + return GPHChannelResponse(meta, data: nil) + } + +} diff --git a/Pods/GiphyCoreSDK/Sources/GPHChannelTag.swift b/Pods/GiphyCoreSDK/Sources/GPHChannelTag.swift new file mode 100644 index 0000000..ffb0c9c --- /dev/null +++ b/Pods/GiphyCoreSDK/Sources/GPHChannelTag.swift @@ -0,0 +1,106 @@ +// +// GPHChannel.swift +// GiphyCoreSDK +// +// Created by Cem Kozinoglu, Gene Goykhman, Giorgia Marenda on 4/24/17. +// Copyright © 2017 Giphy. All rights reserved. +// +// This Source Code Form is subject to the terms of the Mozilla Public +// License, v. 2.0. If a copy of the MPL was not distributed with this +// file, You can obtain one at http://mozilla.org/MPL/2.0/. +// + +import Foundation + +/// Represents Giphy A Channel Tag Object +/// +@objcMembers public class GPHChannelTag: GPHFilterable, NSCoding { + // MARK: Properties + + /// ID of this Channel. + public fileprivate(set) var id: Int? + + /// Slug of the Channel. + public fileprivate(set) var channel: Int? + + /// Display name of the Channel. + public fileprivate(set) var tag: String? + + /// Shortd display name of the Channel. + public fileprivate(set) var rank: Int? + + /// JSON Representation. + public fileprivate(set) var jsonRepresentation: GPHJSONObject? + + /// User Dictionary to Store data in Obj by the Developer + public var userDictionary: [String: Any]? + + //MARK: NSCoding + + required convenience public init?(coder aDecoder: NSCoder) { + self.init() + + self.id = aDecoder.decodeObject(forKey: "id") as? Int + self.channel = aDecoder.decodeObject(forKey: "channel") as? Int + self.tag = aDecoder.decodeObject(forKey: "tag") as? String + self.rank = aDecoder.decodeObject(forKey: "rank") as? Int + self.jsonRepresentation = aDecoder.decodeObject(forKey: "jsonRepresentation") as? GPHJSONObject + self.userDictionary = aDecoder.decodeObject(forKey: "userDictionary") as? [String: Any] + } + + public func encode(with aCoder: NSCoder) { + aCoder.encode(self.id, forKey: "id") + aCoder.encode(self.channel, forKey: "channel") + aCoder.encode(self.tag, forKey: "tag") + aCoder.encode(self.rank, forKey: "rank") + aCoder.encode(self.jsonRepresentation, forKey: "jsonRepresentation") + aCoder.encode(self.userDictionary, forKey: "userDictionary") + } + + + // MARK: NSObject + + override public func isEqual(_ object: Any?) -> Bool { + if object as? GPHChannel === self { + return true + } + if let other = object as? GPHChannel, self.id == other.id { + return true + } + return false + } + + override public var hash: Int { + return "gph_channel_tag_\(self.id ?? 0)".hashValue + } + +} + +/// Make objects human readable. +/// +extension GPHChannelTag { + + override public var description: String { + return "GPHChannelTag(\(self.tag ?? "unknown"))" + } + +} + +extension GPHChannelTag: GPHMappable { + + /// This is where the magic/mapping happens + error handling. + public static func mapData(_ data: GPHJSONObject, options: [String: Any?]) throws -> GPHChannelTag { + + let obj = GPHChannelTag() + + obj.id = (data["id"] as? Int) + obj.channel = (data["channel"] as? Int) + obj.tag = (data["tag"] as? String) + obj.rank = (data["rank"] as? Int) + + obj.jsonRepresentation = data + + return obj + } + +} diff --git a/Pods/GiphyCoreSDK/Sources/GPHClient.swift b/Pods/GiphyCoreSDK/Sources/GPHClient.swift new file mode 100644 index 0000000..f52b771 --- /dev/null +++ b/Pods/GiphyCoreSDK/Sources/GPHClient.swift @@ -0,0 +1,518 @@ +// +// GPHClient.swift +// GiphyCoreSDK +// +// Created by Cem Kozinoglu, Gene Goykhman, Giorgia Marenda on 4/24/17. +// Copyright © 2017 Giphy. All rights reserved. +// +// This Source Code Form is subject to the terms of the Mozilla Public +// License, v. 2.0. If a copy of the MPL was not distributed with this +// file, You can obtain one at http://mozilla.org/MPL/2.0/. +// + +import Foundation + +/// A JSON object. +public typealias GPHJSONObject = [String: Any] + +//MARK: Generic Request & Completion Handlers + +/// JSON/Error signature of generic request method +/// +/// - parameter data: The JSON response (in case of success) or `nil` (in case of error). +/// - parameter response: The URLResponse object +/// - parameter error: The encountered error (in case of error) or `nil` (in case of success). +/// +public typealias GPHJSONCompletionHandler = (_ data: GPHJSONObject?, _ response: URLResponse?, _ error: Error?) -> Void + +/// Generic Completion Handler which accepts a Response type +/// +/// - parameter response: Generic Response (GPHResponse, GPHMediaResponse..) +/// - parameter error: The encountered error (in case of error) or `nil` (in case of success). +/// +//public typealias GPHCompletionHandler = (_ response: T?, _ error: Error?) -> Void + + +/// Entry point into the Swift API. +/// +@objc public class GPHClient : GPHAbstractClient { + // MARK: Properties + + /// Giphy API key. + @objc public var apiKey: String { + get { return _apiKey! } + set { _apiKey = newValue } + } + + /// Initializer + /// + /// - parameter apiKey: Apps api-key to access end-points. + /// + @objc public init(apiKey: String) { + super.init(apiKey) + } + + //MARK: Search Endpoint + + /// Perform a search. + /// + /// - parameter query: Search parameters. + /// - parameter media: Media type (default: .gif) + /// - parameter offset: Offset of results (default: 0) + /// - parameter limit: Total hits you request (default: 25) + /// - parameter rating: maximum rating of returned content (default R) + /// - parameter lang: Language of the content (default English) + /// - parameter completionHandler: Completion handler to be notified of the request's outcome. + /// - returns: A cancellable operation. + /// + @objc + @discardableResult public func search(_ query: String, + media: GPHMediaType = .gif, + offset: Int = 0, + limit: Int = 25, + rating: GPHRatingType = .ratedR, + lang: GPHLanguageType = .english, + completionHandler: @escaping (_ response: GPHListMediaResponse?, _ error: Error?) -> Void) -> Operation { + + let config = GPHRequestConfig() + + // Build the request endpoint + config.queryItems = [ + URLQueryItem(name: "q", value: query), + URLQueryItem(name: "offset", value: "\(offset)"), + URLQueryItem(name: "limit", value: "\(limit)"), + URLQueryItem(name: "rating", value: rating.rawValue), + URLQueryItem(name: "lang", value: lang.rawValue), + ] + config.path = "\(media.rawValue)s/search" + config.method = .get + config.apiKey = apiKey + config.options = [ + "request": "search", + "media": media, + ] + + return self.httpRequest(with: config, + completionHandler: GPHAbstractClient.parseJSONResponse(config, completionHandler: completionHandler)) + } + + + //MARK: Trending Endpoint + + /// Trending + /// + /// - parameter media: Media type (default: .gif) + /// - parameter offset: offset of results (default: 0) + /// - parameter limit: total hits you request (default: 25) + /// - parameter rating: maximum rating of returned content (default R) + /// - parameter completionHandler: Completion handler to be notified of the request's outcome. + /// - returns: A cancellable operation. + /// + @objc + @discardableResult public func trending(_ media: GPHMediaType = .gif, + offset: Int = 0, + limit: Int = 25, + rating: GPHRatingType = .ratedR, + completionHandler: @escaping (_ response: GPHListMediaResponse?, _ error: Error?) -> Void) -> Operation { + + let config = GPHRequestConfig() + + // Build the request endpoint + config.queryItems = [ + URLQueryItem(name: "offset", value: "\(offset)"), + URLQueryItem(name: "limit", value: "\(limit)"), + URLQueryItem(name: "rating", value: rating.rawValue), + ] + config.path = "\(media.rawValue)s/trending" + config.method = .get + config.apiKey = apiKey + config.options = [ + "request": "trending", + "media": media, + ] + + return self.httpRequest(with: config, + completionHandler: GPHAbstractClient.parseJSONResponse(config, completionHandler: completionHandler)) + } + + + //MARK: Translate Endpoint + + /// Translate + /// + /// - parameter term: term or phrase to translate into a GIF|Sticker + /// - parameter media: Media type (default: .gif) + /// - parameter rating: maximum rating of returned content (default R) + /// - parameter lang: language of the content (default English) + /// - parameter completionHandler: Completion handler to be notified of the request's outcome. + /// - returns: A cancellable operation. + /// + @objc + @discardableResult public func translate(_ term: String, + media: GPHMediaType = .gif, + rating: GPHRatingType = .ratedR, + lang: GPHLanguageType = .english, + completionHandler: @escaping (_ response: GPHMediaResponse?, _ error: Error?) -> Void) -> Operation { + + + let config = GPHRequestConfig() + + // Build the request endpoint + config.queryItems = [ + URLQueryItem(name: "s", value: term), + URLQueryItem(name: "rating", value: rating.rawValue), + URLQueryItem(name: "lang", value: lang.rawValue), + ] + config.path = "\(media.rawValue)s/translate" + config.method = .get + config.apiKey = apiKey + config.options = [ + "request": "translate", + "media": media, + ] + + return self.httpRequest(with: config, + completionHandler: GPHAbstractClient.parseJSONResponse(config, completionHandler: completionHandler)) + } + + + //MARK: Random Endpoint + + /// Random + /// + /// Example: http://api.giphy.com/v1/gifs/random?api_key=dc6zaTOxFJmzC&tag=cats + /// - parameter query: Search parameters. + /// - parameter media: Media type (default: .gif) + /// - parameter rating: maximum rating of returned content (default R) + /// - parameter completionHandler: Completion handler to be notified of the request's outcome. + /// - returns: A cancellable operation. + /// + @objc + @discardableResult public func random(_ query: String, + media: GPHMediaType = .gif, + rating: GPHRatingType = .ratedR, + completionHandler: @escaping (_ response: GPHMediaResponse?, _ error: Error?) -> Void) -> Operation { + + let config = GPHRequestConfig() + + // Build the request endpoint + config.queryItems = [ + URLQueryItem(name: "tag", value: query), + URLQueryItem(name: "rating", value: rating.rawValue), + ] + config.path = "\(media.rawValue)s/random" + config.method = .get + config.apiKey = apiKey + config.options = [ + "request": "random", + "media": media, + ] + + return self.httpRequest(with: config, + completionHandler: GPHAbstractClient.parseJSONResponse(config, completionHandler: completionHandler)) + } + + + //MARK: GIFs by ID(s) + + /// GIF by ID + /// + /// - parameter id: GIF ID. + /// - parameter completionHandler: Completion handler to be notified of the request's outcome. + /// - returns: A cancellable operation. + /// + @objc + @discardableResult public func gifByID(_ id: String, + completionHandler: @escaping (_ response: GPHMediaResponse?, _ error: Error?) -> Void) -> Operation { + + let config = GPHRequestConfig() + + // Build the request endpoint + config.path = "gifs/\(id)" + config.method = .get + config.apiKey = apiKey + config.options = [ + "request": "get", + "media": GPHMediaType.gif, + ] + + return self.httpRequest(with: config, + completionHandler: GPHAbstractClient.parseJSONResponse(config, completionHandler: completionHandler)) + } + + + /// GIFs by IDs + /// + /// - parameter ids: array of GIF IDs. + /// - parameter completionHandler: Completion handler to be notified of the request's outcome. + /// - returns: A cancellable operation. + /// + @objc + @discardableResult public func gifsByIDs(_ ids: [String], + completionHandler: @escaping (_ response: GPHListMediaResponse?, _ error: Error?) -> Void) -> Operation { + + + let config = GPHRequestConfig() + + // Build the request endpoint + config.queryItems = [ + URLQueryItem(name: "ids", value: ids.joined(separator:",")) + ] + config.path = "gifs" + config.method = .get + config.apiKey = apiKey + config.options = [ + "request": "getAll", + "media": GPHMediaType.gif, + ] + + return self.httpRequest(with: config, + completionHandler: GPHAbstractClient.parseJSONResponse(config, completionHandler: completionHandler)) + } + + //MARK: Categories Endpoint + + /// Top Categories for GIFs + /// + /// - parameter offset: offset of results (default: 0) + /// - parameter limit: total hits you request (default: 25) + /// - parameter sort: API-specific sorting convention to use (default: blank) + /// - parameter completionHandler: Completion handler to be notified of the request's outcome. + /// - returns: A cancellable operation. + /// + @objc + @discardableResult public func categoriesForGifs(_ offset: Int = 0, + limit: Int = 25, + sort: String = "", + completionHandler: @escaping (_ response: GPHListCategoryResponse?, _ error: Error?) -> Void) -> Operation { + + let config = GPHRequestConfig() + + // Build the request endpoint + config.queryItems = [ + URLQueryItem(name: "sort", value: "\(sort)"), + URLQueryItem(name: "offset", value: "\(offset)"), + URLQueryItem(name: "limit", value: "\(limit)"), + ] + config.path = "gifs/categories" + config.method = .get + config.apiKey = apiKey + config.options = [ + "request": "categories", + "media": GPHMediaType.gif, + "root": nil, + ] + + return self.httpRequest(with: config, + completionHandler: GPHAbstractClient.parseJSONResponse(config, completionHandler: completionHandler)) + } + + /// Sub-Categories for GIFs + /// + /// - parameter category: top category to get sub-categories from + /// - parameter offset: offset of results (default: 0) + /// - parameter limit: total hits you request (default: 25) + /// - parameter sort: API-specific sorting convention to use (default: blank) + /// - parameter completionHandler: Completion handler to be notified of the request's outcome. + /// - returns: A cancellable operation. + /// + @objc + @discardableResult public func subCategoriesForGifs(_ category: String, + offset: Int = 0, + limit: Int = 25, + sort: String = "", + completionHandler: @escaping (_ response: GPHListCategoryResponse?, _ error: Error?) -> Void) -> Operation { + + // root + let categoryObj = GPHCategory(category, nameEncoded: encodedStringForUrl(category), encodedPath:encodedStringForUrl(category)) + + + let config = GPHRequestConfig() + + // Build the request endpoint + config.queryItems = [ + URLQueryItem(name: "sort", value: "\(sort)"), + URLQueryItem(name: "offset", value: "\(offset)"), + URLQueryItem(name: "limit", value: "\(limit)"), + ] + config.path = "gifs/categories/\(categoryObj.encodedPath)" + config.method = .get + config.apiKey = apiKey + config.options = [ + "request": "subCategories", + "media": GPHMediaType.gif, + "root": categoryObj, + ] + + return self.httpRequest(with: config, + completionHandler: GPHAbstractClient.parseJSONResponse(config, completionHandler: completionHandler)) + } + + /// Category Content (only works with Sub-categories / top categories won't return content) + /// + /// - parameter category: top category + /// - parameter subCategory: sub-category to get contents from + /// - parameter offset: offset of results (default: 0) + /// - parameter limit: total hits you request (default: 25) + /// - parameter rating: maximum rating of returned content (default R) + /// - parameter lang: language of the content (default English) + /// - parameter completionHandler: Completion handler to be notified of the request's outcome. + /// - returns: A cancellable operation. + /// + @objc + @discardableResult public func gifsByCategory(_ category: String, + subCategory: String, + offset: Int = 0, + limit: Int = 25, + rating: GPHRatingType = .ratedR, + lang: GPHLanguageType = .english, + completionHandler: @escaping (_ response: GPHListMediaResponse?, _ error: Error?) -> Void) -> Operation { + + let encodedPath = "\(encodedStringForUrl(category))/\(encodedStringForUrl(subCategory))" + let categoryObj = GPHCategory(category, nameEncoded: encodedStringForUrl(category), encodedPath:encodedPath) + + let config = GPHRequestConfig() + + // Build the request endpoint + config.queryItems = [ + URLQueryItem(name: "offset", value: "\(offset)"), + URLQueryItem(name: "limit", value: "\(limit)"), + URLQueryItem(name: "rating", value: rating.rawValue), + URLQueryItem(name: "lang", value: lang.rawValue), + ] + config.path = "gifs/categories/\(categoryObj.encodedPath)" + config.method = .get + config.apiKey = apiKey + config.options = [ + "request": "categoryContent", + "media": GPHMediaType.gif, + ] + + return self.httpRequest(with: config, + completionHandler: GPHAbstractClient.parseJSONResponse(config, completionHandler: completionHandler)) + } + + //MARK: Term Suggestion Endpoint + + /// Term Suggestions + /// + /// - parameter term: Word/Words + /// - parameter completionHandler: Completion handler to be notified of the request's outcome. + /// - returns: A cancellable operation. + /// + @objc + @discardableResult public func termSuggestions(_ term: String, + completionHandler: @escaping (_ response: GPHListTermSuggestionResponse?, _ error: Error?) -> Void) -> Operation { + + let config = GPHRequestConfig() + + // Build the request endpoint + config.path = "queries/suggest/\(term)" + config.method = .get + config.apiKey = apiKey + config.options = [ + "request": "termSuggestions", + "media": GPHMediaType.gif, + ] + + return self.httpRequest(with: config, + completionHandler: GPHAbstractClient.parseJSONResponse(config, completionHandler: completionHandler)) + } + + /// Get a channel by id + /// + /// - parameter channelId: channel id + /// - parameter media: the media type gif/stickers + /// - parameter completionHandler: Completion handler to be notified of the request's outcome. + /// - returns: A cancellable operation. + /// + @objc + @discardableResult public func channel(_ channelId: Int, + media: GPHMediaType, + completionHandler: @escaping (_ response: GPHChannelResponse?, _ error: Error?) -> Void) -> Operation { + + let config = GPHRequestConfig() + + // Build the request endpoint + config.path = "stickers/packs/\(channelId)" + config.method = .get + config.apiKey = apiKey + config.options = [ + "request": "channel", + "media": media, + ] + + return self.httpRequest(with: config, + completionHandler: GPHAbstractClient.parseJSONResponse(config, completionHandler: completionHandler)) + } + + /// Get a channel children + /// + /// - parameter channelId: channel id + /// - parameter offset: Offset of results (default: 0) + /// - parameter limit: Total hits you request (default: 25) + /// - parameter media: the media type gif/stickers + /// - parameter completionHandler: Completion handler to be notified of the request's outcome. + /// - returns: A cancellable operation. + /// + @objc + @discardableResult public func channelChildren(_ channelId: Int, + offset: Int = 0, + limit: Int = 25, + media: GPHMediaType, + completionHandler: @escaping (_ response: GPHListChannelResponse?, _ error: Error?) -> Void) -> Operation { + + let config = GPHRequestConfig() + + // Build the request endpoint + config.queryItems = [ + URLQueryItem(name: "offset", value: "\(offset)"), + URLQueryItem(name: "limit", value: "\(limit)"), + ] + config.path = "stickers/packs/\(channelId)/children" + config.method = .get + config.apiKey = apiKey + config.options = [ + "request": "channelChildren", + "media": media, + ] + + return self.httpRequest(with: config, + completionHandler: GPHAbstractClient.parseJSONResponse(config, completionHandler: completionHandler)) + } + + /// Get a channel gifs + /// + /// - parameter channelId: channel id + /// - parameter offset: Offset of results (default: 0) + /// - parameter limit: Total hits you request (default: 25) + /// - parameter completionHandler: Completion handler to be notified of the request's outcome. + /// - returns: A cancellable operation. + /// + @objc + @discardableResult public func channelContent(_ channelId: Int, + offset: Int = 0, + limit: Int = 25, + media: GPHMediaType, + completionHandler: @escaping (_ response: GPHListMediaResponse?, _ error: Error?) -> Void) -> Operation { + + let config = GPHRequestConfig() + + // Build the request endpoint + config.queryItems = [ + URLQueryItem(name: "offset", value: "\(offset)"), + URLQueryItem(name: "limit", value: "\(limit)"), + ] + config.path = "stickers/packs/\(channelId)/stickers" + config.method = .get + config.apiKey = apiKey + config.options = [ + "request": "channel", + "media": media, + ] + + return self.httpRequest(with: config, + completionHandler: GPHAbstractClient.parseJSONResponse(config, completionHandler: completionHandler)) + } + +} diff --git a/Pods/GiphyCoreSDK/Sources/GPHError.swift b/Pods/GiphyCoreSDK/Sources/GPHError.swift new file mode 100644 index 0000000..88e2ee7 --- /dev/null +++ b/Pods/GiphyCoreSDK/Sources/GPHError.swift @@ -0,0 +1,94 @@ +// +// GPHError.swift +// GiphyCoreSDK +// +// Created by Cem Kozinoglu, Gene Goykhman, Giorgia Marenda on 4/24/17. +// Copyright © 2017 Giphy. All rights reserved. +// +// This Source Code Form is subject to the terms of the Mozilla Public +// License, v. 2.0. If a copy of the MPL was not distributed with this +// file, You can obtain one at http://mozilla.org/MPL/2.0/. +// + +import Foundation + +/// Custom JSON Mapper Error +/// +public struct GPHJSONMappingError: CustomNSError { + // MARK: Properties + + /// Human readable issue. + public let description: String + + /// Custom error code. + public var errorCode: Int { return 1001 } + + + // MARK: Initializers + + /// Initializer + /// + /// - parameter description: textual description of the error. + /// + public init(description: String) { + self.description = description + } + + + // MARK: Helpers + + /// Creates a string with a detailed representation of the given value, suitable for debugging. + public static var errorDomain: String = String(reflecting: GPHJSONMappingError.self) + + /// NSError style, return the dict for the error with description in place. + public var errorUserInfo: GPHJSONObject { + return [ + NSLocalizedDescriptionKey: description + ] + } + +} + +/// Custom HTTP Error +/// +public struct GPHHTTPError: CustomNSError { + // MARK: Properties + + /// Human readable issue, returned by the server. + public let description: String? + + /// The HTTP status code returned by the server. + public let statusCode: Int + + /// Custom error code. + public var errorCode: Int { return statusCode } + + + // MARK: Initializers + + /// Initializer + /// + /// - parameter statusCode: Status code from the server. + /// - parameter description: Description returned from the server. + /// + public init(statusCode: Int, description: String? = nil) { + self.statusCode = statusCode + self.description = description + } + + + // MARK: Helpers + + /// Creates a string with a detailed representation of the given value, suitable for debugging. + public static var errorDomain: String = String(reflecting: GPHJSONMappingError.self) + + /// NSError style, return the dict for the error with description in place. + public var errorUserInfo: GPHJSONObject { + var userInfo = GPHJSONObject() + if let description = description { + userInfo[NSLocalizedDescriptionKey] = description + } + return userInfo + } + +} diff --git a/Pods/GiphyCoreSDK/Sources/GPHFilterable.swift b/Pods/GiphyCoreSDK/Sources/GPHFilterable.swift new file mode 100644 index 0000000..d8dbb62 --- /dev/null +++ b/Pods/GiphyCoreSDK/Sources/GPHFilterable.swift @@ -0,0 +1,28 @@ +// +// GPHFilterable.swift +// GiphyCoreSDK +// +// Created by Cem Kozinoglu on 2/26/18. +// Copyright © 2018 Giphy. All rights reserved. +// +// This Source Code Form is subject to the terms of the Mozilla Public +// License, v. 2.0. If a copy of the MPL was not distributed with this +// file, You can obtain one at http://mozilla.org/MPL/2.0/. +// + +import Foundation + +public typealias GPHFilterBlock = (_ obj: GPHFilterable) -> Bool + +@objc +open class GPHFilterable: NSObject { + + @objc public static var filter:GPHFilterBlock? = nil + + @objc public func isValidObject() -> Bool { + if let filter = GPHFilterable.filter { + return filter(self) + } + return true + } +} diff --git a/Pods/GiphyCoreSDK/Sources/GPHImage.swift b/Pods/GiphyCoreSDK/Sources/GPHImage.swift new file mode 100644 index 0000000..257ee98 --- /dev/null +++ b/Pods/GiphyCoreSDK/Sources/GPHImage.swift @@ -0,0 +1,183 @@ +// +// GPHImage.swift +// GiphyCoreSDK +// +// Created by Cem Kozinoglu, Gene Goykhman, Giorgia Marenda on 4/24/17. +// Copyright © 2017 Giphy. All rights reserved. +// +// This Source Code Form is subject to the terms of the Mozilla Public +// License, v. 2.0. If a copy of the MPL was not distributed with this +// file, You can obtain one at http://mozilla.org/MPL/2.0/. +// + +import Foundation + +/// Represents a Giphy Image (GIF/Sticker) +/// +@objcMembers public class GPHImage: GPHFilterable, NSCoding { + // MARK: Properties + + /// ID of the Represented GPHMedia Object. + public fileprivate(set) var mediaId: String = "" + + /// ID of the Represented Object. + public fileprivate(set) var rendition: GPHRenditionType = .original + + /// URL of the Gif file. + public fileprivate(set) var gifUrl: String? + + /// URL of the Still Gif file. + public fileprivate(set) var stillGifUrl: String? + + /// Width. + public fileprivate(set) var width: Int = 0 + + /// Height. + public fileprivate(set) var height: Int = 0 + + /// # of Frames. + public fileprivate(set) var frames: Int = 0 + + /// Gif file size in bytes. + public fileprivate(set) var gifSize: Int = 0 + + /// URL of the WebP file. + public fileprivate(set) var webPUrl: String? + + /// Gif file size in bytes. + public fileprivate(set) var webPSize: Int = 0 + + /// URL of the mp4 file. + public fileprivate(set) var mp4Url: String? + + /// Gif file size in bytes. + public fileprivate(set) var mp4Size: Int = 0 + + /// JSON Representation. + public fileprivate(set) var jsonRepresentation: GPHJSONObject? + + /// User Dictionary to Store data in Obj by the Developer + public var userDictionary: [String: Any]? + + // MARK: Initializers + + /// Convenience Initializer + /// + /// - parameter mediaId: Media Objects ID. + /// - parameter rendition: Rendition Type of the Image. + /// + convenience public init(_ mediaId: String, + rendition: GPHRenditionType) { + self.init() + self.mediaId = mediaId + self.rendition = rendition + } + + //MARK: NSCoding + + required convenience public init?(coder aDecoder: NSCoder) { + guard + let mediaId = aDecoder.decodeObject(forKey: "mediaId") as? String, + let rendition = GPHRenditionType(rawValue: aDecoder.decodeObject(forKey: "rendition") as! String) + else { + return nil + } + + self.init(mediaId, rendition: rendition) + + self.gifUrl = aDecoder.decodeObject(forKey: "gifUrl") as? String + self.stillGifUrl = aDecoder.decodeObject(forKey: "stillGifUrl") as? String + self.gifSize = aDecoder.decodeInteger(forKey: "gifSize") + self.width = aDecoder.decodeInteger(forKey: "width") + self.height = aDecoder.decodeInteger(forKey: "height") + self.frames = aDecoder.decodeInteger(forKey: "frames") + self.webPUrl = aDecoder.decodeObject(forKey: "webPUrl") as? String + self.webPSize = aDecoder.decodeInteger(forKey: "webPSize") + self.mp4Url = aDecoder.decodeObject(forKey: "mp4Url") as? String + self.mp4Size = aDecoder.decodeInteger(forKey: "mp4Size") + self.jsonRepresentation = aDecoder.decodeObject(forKey: "jsonRepresentation") as? GPHJSONObject + self.userDictionary = aDecoder.decodeObject(forKey: "userDictionary") as? [String: Any] + } + + public func encode(with aCoder: NSCoder) { + aCoder.encode(self.mediaId, forKey: "mediaId") + aCoder.encode(self.rendition.rawValue, forKey: "rendition") + aCoder.encode(self.gifUrl, forKey: "gifUrl") + aCoder.encode(self.stillGifUrl, forKey: "stillGifUrl") + aCoder.encode(self.gifSize, forKey: "gifSize") + aCoder.encode(self.width, forKey: "width") + aCoder.encode(self.height, forKey: "height") + aCoder.encode(self.frames, forKey: "frames") + aCoder.encode(self.webPUrl, forKey: "webPUrl") + aCoder.encode(self.webPSize, forKey: "webPSize") + aCoder.encode(self.mp4Url, forKey: "mp4Url") + aCoder.encode(self.mp4Size, forKey: "mp4Size") + aCoder.encode(self.jsonRepresentation, forKey: "jsonRepresentation") + aCoder.encode(self.userDictionary, forKey: "userDictionary") + } + + // MARK: NSObject + + override public func isEqual(_ object: Any?) -> Bool { + if object as? GPHImage === self { + return true + } + if let other = object as? GPHImage, self.mediaId == other.mediaId, self.rendition.rawValue == other.rendition.rawValue { + return true + } + return false + } + + override public var hash: Int { + return "gph_image_\(self.mediaId)_\(self.rendition.rawValue)".hashValue + } + +} + +// MARK: Extension -- Human readable + +/// Make objects human readable. +/// +extension GPHImage { + + override public var description: String { + return "GPHImage(for: \(self.mediaId)) rendition: \(self.rendition.rawValue)" + } + +} + +// MARK: Extension -- Parsing & Mapping + +/// For parsing/mapping protocol. +/// +extension GPHImage: GPHMappable { + + /// This is where the magic/mapping happens + error handling. + public static func mapData(_ data: GPHJSONObject, options: [String: Any?]) throws -> GPHImage { + + guard let root = options["root"] as? GPHMedia else { + throw GPHJSONMappingError(description: "Root object can not be nil, expected a GPHMedia") + } + + guard let renditionType = options["rendition"] as? GPHRenditionType else { + throw GPHJSONMappingError(description: "Need Rendition to map the object") + } + + let obj = GPHImage(root.id, rendition: renditionType) + + obj.gifUrl = data["url"] as? String + obj.stillGifUrl = data["still_url"] as? String + obj.gifSize = parseInt(data["size"] as? String) ?? 0 + obj.width = parseInt(data["width"] as? String) ?? 0 + obj.height = parseInt(data["height"] as? String) ?? 0 + obj.frames = parseInt(data["frames"] as? String) ?? 0 + obj.webPUrl = data["webp"] as? String + obj.webPSize = parseInt(data["webp_size"] as? String) ?? 0 + obj.mp4Url = data["mp4"] as? String + obj.mp4Size = parseInt(data["mp4_size"] as? String) ?? 0 + obj.jsonRepresentation = data + + return obj + } + +} diff --git a/Pods/GiphyCoreSDK/Sources/GPHImages.swift b/Pods/GiphyCoreSDK/Sources/GPHImages.swift new file mode 100644 index 0000000..b8979fd --- /dev/null +++ b/Pods/GiphyCoreSDK/Sources/GPHImages.swift @@ -0,0 +1,345 @@ +// +// GPHImages.swift +// GiphyCoreSDK +// +// Created by Cem Kozinoglu, Gene Goykhman, Giorgia Marenda on 4/24/17. +// Copyright © 2017 Giphy. All rights reserved. +// +// This Source Code Form is subject to the terms of the Mozilla Public +// License, v. 2.0. If a copy of the MPL was not distributed with this +// file, You can obtain one at http://mozilla.org/MPL/2.0/. +// + +import Foundation + +/// Represents a Giphy Images (Renditions) for a GPHMedia +/// +@objcMembers public class GPHImages: GPHFilterable, NSCoding { + // MARK: Properties + + /// ID of the Represented Object. + public fileprivate(set) var mediaId: String = "" + + /// Original file size and file dimensions. Good for desktop use. + public fileprivate(set) var original: GPHImage? + + /// Preview image for original. + public fileprivate(set) var originalStill: GPHImage? + + /// File size under 50kb. Duration may be truncated to meet file size requirements. Good for thumbnails and previews. + public fileprivate(set) var preview: GPHImage? + + /// Duration set to loop for 15 seconds. Only recommended for this exact use case. + public fileprivate(set) var looping: GPHImage? + + /// Height set to 200px. Good for mobile use. + public fileprivate(set) var fixedHeight: GPHImage? + + /// Static preview image for fixed_height. + public fileprivate(set) var fixedHeightStill: GPHImage? + + /// Height set to 200px. Reduced to 6 frames to minimize file size to the lowest. + /// Works well for unlimited scroll on mobile and as animated previews. See Giphy.com on mobile web as an example. + public fileprivate(set) var fixedHeightDownsampled: GPHImage? + + /// Height set to 100px. Good for mobile keyboards. + public fileprivate(set) var fixedHeightSmall: GPHImage? + + /// Static preview image for fixed_height_small. + public fileprivate(set) var fixedHeightSmallStill: GPHImage? + + /// Width set to 200px. Good for mobile use. + public fileprivate(set) var fixedWidth: GPHImage? + + /// Static preview image for fixed_width. + public fileprivate(set) var fixedWidthStill: GPHImage? + + /// Width set to 200px. Reduced to 6 frames. Works well for unlimited scroll on mobile and as animated previews. + public fileprivate(set) var fixedWidthDownsampled: GPHImage? + + /// Width set to 100px. Good for mobile keyboards. + public fileprivate(set) var fixedWidthSmall: GPHImage? + + /// Static preview image for fixed_width_small. + public fileprivate(set) var fixedWidthSmallStill: GPHImage? + + /// File size under 2mb. + public fileprivate(set) var downsized: GPHImage? + + /// File size under 200kb. + public fileprivate(set) var downsizedSmall: GPHImage? + + /// File size under 5mb. + public fileprivate(set) var downsizedMedium: GPHImage? + + /// File size under 8mb. + public fileprivate(set) var downsizedLarge: GPHImage? + + /// Static preview image for downsized. + public fileprivate(set) var downsizedStill: GPHImage? + + /// JSON Representation. + public fileprivate(set) var jsonRepresentation: GPHJSONObject? + + /// User Dictionary to Store data in Obj by the Developer + public var userDictionary: [String: Any]? + + // MARK: Initializers + + /// Convenience Initializer + /// + /// - parameter mediaId: Media Objects ID. + /// + convenience public init(_ mediaId: String) { + self.init() + self.mediaId = mediaId + } + + //MARK: NSCoding + + required convenience public init?(coder aDecoder: NSCoder) { + guard + let mediaId = aDecoder.decodeObject(forKey: "mediaId") as? String + else { + return nil + } + + self.init(mediaId) + + self.original = aDecoder.decodeObject(forKey: "original") as? GPHImage + self.originalStill = aDecoder.decodeObject(forKey: "originalStill") as? GPHImage + self.preview = aDecoder.decodeObject(forKey: "preview") as? GPHImage + self.looping = aDecoder.decodeObject(forKey: "looping") as? GPHImage + self.fixedHeight = aDecoder.decodeObject(forKey: "fixedHeight") as? GPHImage + self.fixedHeightStill = aDecoder.decodeObject(forKey: "fixedHeightStill") as? GPHImage + self.fixedHeightDownsampled = aDecoder.decodeObject(forKey: "fixedHeightDownsampled") as? GPHImage + self.fixedHeightSmall = aDecoder.decodeObject(forKey: "fixedHeightSmall") as? GPHImage + self.fixedHeightSmallStill = aDecoder.decodeObject(forKey: "fixedHeightSmallStill") as? GPHImage + self.fixedWidth = aDecoder.decodeObject(forKey: "fixedWidth") as? GPHImage + self.fixedWidthStill = aDecoder.decodeObject(forKey: "fixedWidthStill") as? GPHImage + self.fixedWidthDownsampled = aDecoder.decodeObject(forKey: "fixedWidthDownsampled") as? GPHImage + self.fixedWidthSmall = aDecoder.decodeObject(forKey: "fixedWidthSmall") as? GPHImage + self.fixedWidthSmallStill = aDecoder.decodeObject(forKey: "fixedWidthSmallStill") as? GPHImage + self.downsized = aDecoder.decodeObject(forKey: "downsized") as? GPHImage + self.downsizedSmall = aDecoder.decodeObject(forKey: "downsizedSmall") as? GPHImage + self.downsizedMedium = aDecoder.decodeObject(forKey: "downsizedMedium") as? GPHImage + self.downsizedLarge = aDecoder.decodeObject(forKey: "downsizedLarge") as? GPHImage + self.downsizedStill = aDecoder.decodeObject(forKey: "downsizedStill") as? GPHImage + self.jsonRepresentation = aDecoder.decodeObject(forKey: "jsonRepresentation") as? GPHJSONObject + self.userDictionary = aDecoder.decodeObject(forKey: "userDictionary") as? [String: Any] + } + + public func encode(with aCoder: NSCoder) { + aCoder.encode(self.mediaId, forKey: "mediaId") + aCoder.encode(self.original, forKey: "original") + aCoder.encode(self.originalStill, forKey: "originalStill") + aCoder.encode(self.preview, forKey: "preview") + aCoder.encode(self.looping, forKey: "looping") + aCoder.encode(self.fixedHeight, forKey: "fixedHeight") + aCoder.encode(self.fixedHeightStill, forKey: "fixedHeightStill") + aCoder.encode(self.fixedHeightDownsampled, forKey: "fixedHeightDownsampled") + aCoder.encode(self.fixedHeightSmall, forKey: "fixedHeightSmall") + aCoder.encode(self.fixedHeightSmallStill, forKey: "fixedHeightSmallStill") + aCoder.encode(self.fixedWidth, forKey: "fixedWidth") + aCoder.encode(self.fixedWidthStill, forKey: "fixedWidthStill") + aCoder.encode(self.fixedWidthDownsampled, forKey: "fixedWidthDownsampled") + aCoder.encode(self.fixedWidthSmall, forKey: "fixedWidthSmall") + aCoder.encode(self.fixedWidthSmallStill, forKey: "fixedWidthSmallStill") + aCoder.encode(self.downsized, forKey: "downsized") + aCoder.encode(self.downsizedSmall, forKey: "downsizedSmall") + aCoder.encode(self.downsizedMedium, forKey: "downsizedMedium") + aCoder.encode(self.downsizedLarge, forKey: "downsizedLarge") + aCoder.encode(self.downsizedStill, forKey: "downsizedStill") + aCoder.encode(self.jsonRepresentation, forKey: "jsonRepresentation") + aCoder.encode(self.userDictionary, forKey: "userDictionary") + } + + // MARK: NSObject + + override public func isEqual(_ object: Any?) -> Bool { + if object as? GPHImages === self { + return true + } + if let other = object as? GPHImages, self.mediaId == other.mediaId { + return true + } + return false + } + + override public var hash: Int { + return "gph_renditions_\(self.mediaId)".hashValue + } + +} + +// MARK: Extension -- Helper Methods + +/// Picking renditions and stuff. +/// +extension GPHImages { + + @objc + public func rendition(_ rendition: GPHRenditionType = .original) -> GPHImage? { + + switch rendition { + case .original: + return self.original + case .originalStill: + return self.originalStill + case .preview: + return self.preview + case .looping: + return self.looping + case .fixedHeight: + return self.fixedHeight + case .fixedHeightStill: + return self.fixedHeightStill + case .fixedHeightDownsampled: + return self.fixedHeightDownsampled + case .fixedHeightSmall: + return self.fixedHeightSmall + case .fixedHeightSmallStill: + return self.fixedHeightSmallStill + case .fixedWidth: + return self.fixedWidth + case .fixedWidthStill: + return self.fixedWidthStill + case .fixedWidthDownsampled: + return self.fixedWidthDownsampled + case .fixedWidthSmall: + return self.fixedWidthSmall + case .fixedWidthSmallStill: + return self.fixedWidthSmallStill + case .downsized: + return self.downsized + case .downsizedSmall: + return self.downsizedSmall + case .downsizedMedium: + return self.downsizedMedium + case .downsizedLarge: + return self.downsizedLarge + case .downsizedStill: + return self.downsizedStill +// default: +// return self.original + } + } + +} + + +// MARK: Extension -- Human readable + +/// Make objects human readable. +/// +extension GPHImages { + + override public var description: String { + return "GPHImages(for: \(self.mediaId))" + } + +} + +// MARK: Extension -- Parsing & Mapping + +/// For parsing/mapping protocol. +/// +extension GPHImages: GPHMappable { + + // convinience method to convert Random endpoint results to structured renditions + static func mapRandomData(_ keyPrefix: String, data: GPHJSONObject) -> GPHJSONObject? { + + var keyPrefixMap = keyPrefix + if keyPrefix == "original" { + keyPrefixMap = "image" + } + var mappedDict: GPHJSONObject = [:] + mappedDict["url"] = data["\(keyPrefixMap)_url"] as? String + mappedDict["width"] = parseInt(data["\(keyPrefixMap)_width"] as? String) + mappedDict["height"] = parseInt(data["\(keyPrefixMap)_height"] as? String) + mappedDict["frames"] = parseInt(data["\(keyPrefixMap)_frames"] as? String) + mappedDict["size"] = parseInt(data["\(keyPrefixMap)_size"] as? String) + mappedDict["mp4"] = data["\(keyPrefixMap)_mp4_url"] as? String + mappedDict["still_url"] = data["\(keyPrefixMap)_still_url"] as? String + + if mappedDict.count == 0 { + return nil + } + + return mappedDict + } + + + // convinience method to get GPHImage or nil safely + static func image(_ data: GPHJSONObject, options: [String: Any?]) -> (object: GPHImage?, error: GPHJSONMappingError?) { + + guard let renditionType = options["rendition"] as? GPHRenditionType else { + return (nil, GPHJSONMappingError(description: "Need Rendition to map the object")) + } + guard let requestType = options["request"] as? String else { + return (nil, GPHJSONMappingError(description: "Need Request type to map the object")) + } + + var jsonKeyData:GPHJSONObject? + + // handle structural changes on how data is mapped depending on the request type (search, trending, random....) + switch requestType { + case "random": + jsonKeyData = mapRandomData(renditionType.rawValue, data: data) + default: + jsonKeyData = data[renditionType.rawValue] as? GPHJSONObject + } + + if let jsonKeyData = jsonKeyData { + do { + let keyImage = try GPHImage.mapData(jsonKeyData, options: options) + return (keyImage, nil) + } catch let error as GPHJSONMappingError { + return (nil, error) + } catch { + return (nil, GPHJSONMappingError(description: "Fatal error, this should never happen")) + } + } + return (nil, GPHJSONMappingError(description: "Couldn't map GPHImage for the rendition \(renditionType.rawValue)")) + } + + static func optionsWithRendition(_ options: [String: Any?], rendition: GPHRenditionType) -> [String: Any?] { + var optionsCopy = options + optionsCopy["rendition"] = rendition + return optionsCopy + } + + /// This is where the magic/mapping happens + error handling. + public static func mapData(_ data: GPHJSONObject, options: [String: Any?]) throws -> GPHImages { + + guard let root = options["root"] as? GPHMedia else { + throw GPHJSONMappingError(description: "Root object can not be nil, expected a GPHMedia") + } + + let obj = GPHImages(root.id) + + obj.original = GPHImages.image(data, options: optionsWithRendition(options, rendition: .original)).object + obj.originalStill = GPHImages.image(data, options: optionsWithRendition(options, rendition: .originalStill)).object + obj.preview = GPHImages.image(data, options: optionsWithRendition(options, rendition: .preview)).object + obj.looping = GPHImages.image(data, options: optionsWithRendition(options, rendition: .looping)).object + obj.fixedHeight = GPHImages.image(data, options: optionsWithRendition(options, rendition: .fixedHeight)).object + obj.fixedHeightStill = GPHImages.image(data, options: optionsWithRendition(options, rendition: .fixedHeightStill)).object + obj.fixedHeightDownsampled = GPHImages.image(data, options: optionsWithRendition(options, rendition: .fixedHeightDownsampled)).object + obj.fixedHeightSmall = GPHImages.image(data, options: optionsWithRendition(options, rendition:.fixedHeightSmall)).object + obj.fixedHeightSmallStill = GPHImages.image(data, options: optionsWithRendition(options, rendition: .fixedHeightSmallStill)).object + obj.fixedWidth = GPHImages.image(data, options: optionsWithRendition(options, rendition: .fixedWidth)).object + obj.fixedWidthStill = GPHImages.image(data, options: optionsWithRendition(options, rendition: .fixedWidthStill)).object + obj.fixedWidthDownsampled = GPHImages.image(data, options: optionsWithRendition(options, rendition: .fixedWidthDownsampled)).object + obj.fixedWidthSmall = GPHImages.image(data, options: optionsWithRendition(options, rendition: .fixedWidthSmall)).object + obj.fixedWidthSmallStill = GPHImages.image(data, options: optionsWithRendition(options, rendition: .fixedWidthSmallStill)).object + obj.downsized = GPHImages.image(data, options: optionsWithRendition(options, rendition: .downsized)).object + obj.downsizedSmall = GPHImages.image(data, options: optionsWithRendition(options, rendition: .downsizedSmall)).object + obj.downsizedMedium = GPHImages.image(data, options: optionsWithRendition(options, rendition: .downsizedMedium)).object + obj.downsizedLarge = GPHImages.image(data, options: optionsWithRendition(options, rendition: .downsizedLarge)).object + obj.downsizedStill = GPHImages.image(data, options: optionsWithRendition(options, rendition: .downsizedStill)).object + obj.jsonRepresentation = data + + return obj + } + +} diff --git a/Pods/GiphyCoreSDK/Sources/GPHListCategoryResponse.swift b/Pods/GiphyCoreSDK/Sources/GPHListCategoryResponse.swift new file mode 100644 index 0000000..acbb4a2 --- /dev/null +++ b/Pods/GiphyCoreSDK/Sources/GPHListCategoryResponse.swift @@ -0,0 +1,102 @@ +// +// GPHListCategoryResponse.swift +// GiphyCoreSDK +// +// Created by Cem Kozinoglu, Gene Goykhman, Giorgia Marenda on 4/24/17. +// Copyright © 2017 Giphy. All rights reserved. +// +// This Source Code Form is subject to the terms of the Mozilla Public +// License, v. 2.0. If a copy of the MPL was not distributed with this +// file, You can obtain one at http://mozilla.org/MPL/2.0/. +// + +import Foundation + +/// Represents a Giphy List Category Response (multiple results) +/// +@objcMembers public class GPHListCategoryResponse: GPHResponse { + // MARK: Properties + + /// Category Objects. + public fileprivate(set) var data: [GPHCategory]? + + /// Pagination info. + public fileprivate(set) var pagination: GPHPagination? + + + // MARK: Initializers + + /// Convenience Initializer + /// + /// - parameter meta: init with a GPHMeta object. + /// - parameter data: GPHMedia array (optional). + /// - parameter pagination: GPHPagination object (optional). + /// + convenience public init(_ meta:GPHMeta, data: [GPHCategory]?, pagination: GPHPagination?) { + self.init() + self.data = data + self.pagination = pagination + self.meta = meta + } + +} + +// MARK: Extension -- Human readable + +/// Make objects human readable. +/// +extension GPHListCategoryResponse { + + override public var description: String { + return "GPHListCategoryResponse(\(self.meta.responseId) status: \(self.meta.status) msg: \(self.meta.msg))" + } + +} + +// MARK: Extension -- Parsing & Mapping + +/// For parsing/mapping protocol. +/// +extension GPHListCategoryResponse: GPHMappable { + + /// This is where the magic/mapping happens + error handling. + public static func mapData(_ data: GPHJSONObject, options: [String: Any?]) throws -> GPHListCategoryResponse { + + guard + let metaData = data["meta"] as? GPHJSONObject + else { + throw GPHJSONMappingError(description: "Couldn't map GPHMediaResponse due to Meta missing for \(data)") + } + + let meta = try GPHMeta.mapData(metaData, options: options) + + // Try to see if we can get the Media object + if let mediaData = data["data"] as? [GPHJSONObject], let paginationData = data["pagination"] as? GPHJSONObject { + + // Get Pagination + let pagination = try GPHPagination.mapData(paginationData, options: options) + + // Get Results + var results: [GPHCategory]? = [] + + for result in mediaData { + let result = try GPHCategory.mapData(result, options: options) + if result.isValidObject() { + results?.append(result) + } + } + if results != nil { + pagination.updateFilteredCount(results!.count) + } + + // We have images and the meta data and pagination + return GPHListCategoryResponse(meta, data: results, pagination: pagination) + } + + // No image and pagination data, return the meta data + return GPHListCategoryResponse(meta, data: nil, pagination: nil) + } + +} + + diff --git a/Pods/GiphyCoreSDK/Sources/GPHListChannelResponse.swift b/Pods/GiphyCoreSDK/Sources/GPHListChannelResponse.swift new file mode 100644 index 0000000..0544ae5 --- /dev/null +++ b/Pods/GiphyCoreSDK/Sources/GPHListChannelResponse.swift @@ -0,0 +1,99 @@ +// +// GPHListCategoryResponse.swift +// GiphyCoreSDK +// +// Created by Cem Kozinoglu, Gene Goykhman, Giorgia Marenda, David Hargat on 4/24/17. +// Copyright © 2017 Giphy. All rights reserved. +// +// This Source Code Form is subject to the terms of the Mozilla Public +// License, v. 2.0. If a copy of the MPL was not distributed with this +// file, You can obtain one at http://mozilla.org/MPL/2.0/. +// + +import Foundation + +/// Represents a Giphy List Channel Response +/// +@objcMembers public class GPHListChannelResponse: GPHResponse { + // MARK: Properties + + /// Category Objects. + public fileprivate(set) var data: [GPHChannel]? + + /// Pagination info. + public fileprivate(set) var pagination: GPHPagination? + + // MARK: Initializers + + /// Convenience Initializer + /// + /// - parameter meta: init with a GPHMeta object. + /// - parameter data: GPHChannel array (optional). + /// - parameter pagination: GPHPagination object (optional). + /// + convenience public init(_ meta: GPHMeta, data: [GPHChannel]?, pagination: GPHPagination?) { + self.init() + self.data = data + self.pagination = pagination + self.meta = meta + } + +} + +// MARK: Extension -- Human readable + +/// Make objects human readable. +/// +extension GPHListChannelResponse { + + override public var description: String { + return "GPHListChannelResponse(\(self.meta.responseId) status: \(self.meta.status) msg: \(self.meta.msg))" + } + +} + +// MARK: Extension -- Parsing & Mapping + +/// For parsing/mapping protocol. +/// +extension GPHListChannelResponse: GPHMappable { + + /// This is where the magic/mapping happens + error handling. + public static func mapData(_ data: GPHJSONObject, options: [String: Any?]) throws -> GPHListChannelResponse { + guard + let metaData = data["meta"] as? GPHJSONObject + else { + throw GPHJSONMappingError(description: "Couldn't map GPHListChannelResponse due to Meta missing for \(data)") + } +// guard +// let paginationData = jsonData["pagination"] as? GPHJSONObject +// else { +// throw GPHJSONMappingError(description: "Couldn't map GPHMediaResponse due to Pagination missing for \(jsonData)") +// } + guard + let resultsData = data["data"] as? [GPHJSONObject] + else { + throw GPHJSONMappingError(description: "Couldn't map GPHListChannelResponse due to Results missing for \(data)") + } + + let meta = try GPHMeta.mapData(metaData, options: options) + + // Get Results + var results: [GPHChannel]? = [] + + for result in resultsData { + let result = try GPHChannel.mapData(result, options: options) + if result.isValidObject() { + results?.append(result) + } + } +// if results != nil { +// pagination?.updateFilteredCount(results!.count) +// } + + // TODO: pagination + return GPHListChannelResponse(meta, data: results, pagination: nil) + } +} + + diff --git a/Pods/GiphyCoreSDK/Sources/GPHListMediaResponse.swift b/Pods/GiphyCoreSDK/Sources/GPHListMediaResponse.swift new file mode 100644 index 0000000..cd3c01c --- /dev/null +++ b/Pods/GiphyCoreSDK/Sources/GPHListMediaResponse.swift @@ -0,0 +1,94 @@ +// +// GPHListMediaResponse.swift +// GiphyCoreSDK +// +// Created by Cem Kozinoglu, Gene Goykhman, Giorgia Marenda on 4/24/17. +// Copyright © 2017 Giphy. All rights reserved. +// +// This Source Code Form is subject to the terms of the Mozilla Public +// License, v. 2.0. If a copy of the MPL was not distributed with this +// file, You can obtain one at http://mozilla.org/MPL/2.0/. +// + +import Foundation + +/// Represents a Giphy List Media Response (multiple results) +/// +@objcMembers public class GPHListMediaResponse: GPHResponse { + // MARK: Properties + + /// Gifs/Stickers. + public fileprivate(set) var data: [GPHMedia]? + + /// Pagination info. + public fileprivate(set) var pagination: GPHPagination? + + + // MARK: Initializers + + /// Convenience Initializer + /// + /// - parameter meta: init with a GPHMeta object. + /// - parameter data: GPHMedia array (optional). + /// - parameter pagination: GPHPagination object (optional). + /// + convenience public init(_ meta:GPHMeta, data: [GPHMedia]?, pagination: GPHPagination?) { + self.init() + self.data = data + self.pagination = pagination + self.meta = meta + } + +} + +// MARK: Extension -- Human readable + +/// Make objects human readable. +/// +extension GPHListMediaResponse { + + override public var description: String { + return "GPHListMediaResponse(\(self.meta.responseId) status: \(self.meta.status) msg: \(self.meta.msg))" + } + +} + +// MARK: Extension -- Parsing & Mapping + +/// For parsing/mapping protocol. +/// +extension GPHListMediaResponse: GPHMappable { + + /// This is where the magic/mapping happens + error handling. + public static func mapData(_ data: GPHJSONObject, options: [String: Any?]) throws -> GPHListMediaResponse { + guard + let metaData = data["meta"] as? GPHJSONObject + else { + throw GPHJSONMappingError(description: "Couldn't map GPHMediaResponse due to Meta missing for \(data)") + } + let meta = try GPHMeta.mapData(metaData, options: options) + + var pagination: GPHPagination? = nil + if let paginationData = data["pagination"] as? GPHJSONObject { + pagination = try GPHPagination.mapData(paginationData, options: options) + } + + var results: [GPHMedia]? = nil + if let mediaData = data["data"] as? [GPHJSONObject] { + results = [] + for result in mediaData { + let result = try GPHMedia.mapData(result, options: options) + if result.isValidObject() { + results?.append(result) + } + } + } + if results != nil { + pagination?.updateFilteredCount(results!.count) + } + + // No image and pagination data, return the meta data + return GPHListMediaResponse(meta, data: results, pagination: pagination) + } + +} diff --git a/Pods/GiphyCoreSDK/Sources/GPHListTermSuggestionRespose.swift b/Pods/GiphyCoreSDK/Sources/GPHListTermSuggestionRespose.swift new file mode 100644 index 0000000..816aef9 --- /dev/null +++ b/Pods/GiphyCoreSDK/Sources/GPHListTermSuggestionRespose.swift @@ -0,0 +1,89 @@ +// +// GPHListTermSuggestionResponse.swift +// GiphyCoreSDK +// +// Created by Cem Kozinoglu, Gene Goykhman, Giorgia Marenda on 4/24/17. +// Copyright © 2017 Giphy. All rights reserved. +// +// This Source Code Form is subject to the terms of the Mozilla Public +// License, v. 2.0. If a copy of the MPL was not distributed with this +// file, You can obtain one at http://mozilla.org/MPL/2.0/. +// + +import Foundation + +/// Represents a Giphy List Term Suggestions Response (multiple results) +/// +@objcMembers public class GPHListTermSuggestionResponse: GPHResponse { + // MARK: Properties + + /// Terms Suggested. + public fileprivate(set) var data: [GPHTermSuggestion]? + + + // MARK: Initializers + + /// Convenience Initializer + /// + /// - parameter meta: init with a GPHMeta object. + /// - parameter data: GPHTermSuggestion array (optional). + /// + convenience public init(_ meta:GPHMeta, data: [GPHTermSuggestion]?) { + self.init() + self.data = data + self.meta = meta + } + +} + +// MARK: Extension -- Human readable + +/// Make objects human readable. +/// +extension GPHListTermSuggestionResponse { + + override public var description: String { + return "GPHListTermSuggestionResponse(\(self.meta.responseId) status: \(self.meta.status) msg: \(self.meta.msg))" + } + +} + +// MARK: Extension -- Parsing & Mapping + +/// For parsing/mapping protocol. +/// +extension GPHListTermSuggestionResponse: GPHMappable { + + /// This is where the magic/mapping happens + error handling. + public static func mapData(_ data: GPHJSONObject, options: [String: Any?]) throws -> GPHListTermSuggestionResponse { + + guard + let metaData = data["meta"] as? GPHJSONObject + else { + throw GPHJSONMappingError(description: "Couldn't map GPHMediaResponse due to Meta missing for \(data)") + } + + let meta = try GPHMeta.mapData(metaData, options: options) + + // Try to see if we can get the Media object + if let termData = data["data"] as? [GPHJSONObject] { + + // Get Results + var results: [GPHTermSuggestion]? = [] + + for result in termData { + let result = try GPHTermSuggestion.mapData(result, options: options) + if result.isValidObject() { + results?.append(result) + } + } + + // We have images and the meta data and pagination + return GPHListTermSuggestionResponse(meta, data: results) + } + + // No image and pagination data, return the meta data + return GPHListTermSuggestionResponse(meta, data: nil) + } + +} diff --git a/Pods/GiphyCoreSDK/Sources/GPHMappable.swift b/Pods/GiphyCoreSDK/Sources/GPHMappable.swift new file mode 100644 index 0000000..4547f71 --- /dev/null +++ b/Pods/GiphyCoreSDK/Sources/GPHMappable.swift @@ -0,0 +1,108 @@ +// +// GPHMappable.swift +// GiphyCoreSDK +// +// Created by Cem Kozinoglu, Gene Goykhman, Giorgia Marenda on 4/24/17. +// Copyright © 2017 Giphy. All rights reserved. +// +// This Source Code Form is subject to the terms of the Mozilla Public +// License, v. 2.0. If a copy of the MPL was not distributed with this +// file, You can obtain one at http://mozilla.org/MPL/2.0/. +// + +import Foundation + +/// Protocol to Map JSON > GPH Objects. +/// Make sure Models implement this protocol to be able to map JSON>Obj +public protocol GPHMappable { + + /// Generic Mappable object to return. + associatedtype GPHMappableObject + + /// Static function for mapping JSON to objects. + /// + /// - parameter options: Dictionary of options (type, root object, media...) + /// - returns: object: Self + /// + static func mapData(_ data: GPHJSONObject, options: [String: Any?]) throws -> GPHMappableObject +} + +// MARK: Extension -- Parsing Helper Implementations + +/// Extend protocol to have default behavior +/// We will use this to map JSON to particular types of objs we want like Date, URL, ... +public extension GPHMappable { + + /// Map a String to a Date. + /// + /// - parameter date: String version of the Date to be mapped to Date type + /// - returns: a Date object or nil + /// + public static func parseDate(_ date: String?) -> Date? { + //"2013-03-21 04:03:08" "2018-06-05T21:46:37.525Z" "2018-08-02T12:00:00Z" + let dateFormats = ["yyyy-MM-dd HH:mm:ss", "yyyy-MM-dd'T'HH:mm:ss.SSS'Z'", "yyyy-MM-dd'T'HH:mm:ss'Z'"] + for format in dateFormats { + if let parsedDate = parseDate(date, format: format) { + return parsedDate + } + } + return nil + } + + public static func parseDate(_ date: String?, format: String) -> Date? { + guard let date = date else { return nil } + let dateFormatter = DateFormatter.standardDateFormatter + dateFormatter.timeZone = TimeZone(abbreviation: "UTC") ?? TimeZone.current + dateFormatter.dateFormat = format + return dateFormatter.date(from: date) + } + + /// Map a String to a URL. + /// + /// - parameter urk: String version of the URL to be mapped to URL type + /// - returns: a Date object or nil + /// + public static func parseURL(_ url: String?) -> URL? { + if let url = url { + return URL(string: url) + } + return nil + } + + + /// Map a String to a GPHRatingType. + /// + /// - parameter rating: String version of the rating to be mapped to GPHRatingType type + /// - returns: a GPHRatingType object or nil + /// + public static func parseRating(_ rating: String?) -> GPHRatingType { + if let rating = rating { + return GPHRatingType(rawValue: rating) ?? .unrated + } + return .unrated + } + + + /// Map a String to an Int. + /// + /// - parameter number: String version of the Int to be mapped to Int type + /// - returns: a Int object or nil + /// + public static func parseInt(_ number: String?) -> Int? { + if let number = number { + return Int(number) + } + return nil + } +} + +// MARK: Extension -- DateFormatter + +/// Create a more performant static instance of DateFormatter + +extension DateFormatter { + fileprivate static let standardDateFormatter: DateFormatter = { + let dateFormatter = DateFormatter() + return dateFormatter + }() +} diff --git a/Pods/GiphyCoreSDK/Sources/GPHMedia.swift b/Pods/GiphyCoreSDK/Sources/GPHMedia.swift new file mode 100644 index 0000000..f17073e --- /dev/null +++ b/Pods/GiphyCoreSDK/Sources/GPHMedia.swift @@ -0,0 +1,333 @@ +// +// GPHMedia.swift +// GiphyCoreSDK +// +// Created by Cem Kozinoglu, Gene Goykhman, Giorgia Marenda on 4/24/17. +// Copyright © 2017 Giphy. All rights reserved. +// +// This Source Code Form is subject to the terms of the Mozilla Public +// License, v. 2.0. If a copy of the MPL was not distributed with this +// file, You can obtain one at http://mozilla.org/MPL/2.0/. +// + +import Foundation + +/// Represents a Giphy Media Object +/// +@objcMembers public class GPHMedia: GPHFilterable, NSCoding { + // MARK: Properties + + /// ID of the Object. + public fileprivate(set) var id: String = "" + + /// Media Type (GIF|Sticker). + public fileprivate(set) var type: GPHMediaType = .gif + + /// URL of the GIF/Sticker. + public fileprivate(set) var url: String = "" + + /// Content Rating (Default G). + public fileprivate(set) var rating: GPHRatingType = .unrated + + /// Title. + public fileprivate(set) var title: String? + + /// Caption. + public fileprivate(set) var caption: String? + + /// URL Slug. + public fileprivate(set) var slug: String? + + /// Indexable or Not. + public fileprivate(set) var indexable: String? + + /// Content. + public fileprivate(set) var contentUrl: String? + + /// Bitly Short URL. + public fileprivate(set) var bitlyUrl: String? + + /// Bitly Short URL for GIF. + public fileprivate(set) var bitlyGifUrl: String? + + /// Embed URL. + public fileprivate(set) var embedUrl: String? + + /// Attribution Source. + public fileprivate(set) var source: String? + + /// Attribution Source Domain TLD. + public fileprivate(set) var sourceTld: String? + + /// Attribution Source Post URL. + public fileprivate(set) var sourcePostUrl: String? + + /// Atrribution / User. + public fileprivate(set) var user: GPHUser? + + /// Renditions of the Media Object. + public fileprivate(set) var images: GPHImages? + + /// Bottle Data. + public fileprivate(set) var bottleData: GPHBottleData? + + /// Tags representing the Media Object. + public fileprivate(set) var tags: [String]? + + /// Featured Tags. + public fileprivate(set) var featuredTags: [String]? + + /// Import Date/Time. + public fileprivate(set) var importDate: Date? + + /// Creation Date/Time. + public fileprivate(set) var createDate: Date? + + /// Last Update Date/Time. + public fileprivate(set) var updateDate: Date? + + /// Trending Date/Time. + public fileprivate(set) var trendingDate: Date? + + // NOTE: Categories endpoint. + // Example: http://api.giphy.com/v1/gifs/categories/actions?api_key=4OMJYpPoYwVpe + public fileprivate(set) var isHidden: Bool = false + public fileprivate(set) var isRemoved: Bool = false + public fileprivate(set) var isCommunity: Bool = false + public fileprivate(set) var isAnonymous: Bool = false + public fileprivate(set) var isFeatured: Bool = false + public fileprivate(set) var isRealtime: Bool = false + public fileprivate(set) var isIndexable: Bool = false + public fileprivate(set) var isSticker: Bool = false + + /// JSON Representation. + public fileprivate(set) var jsonRepresentation: GPHJSONObject? + + /// User Dictionary to Store data in Obj by the Developer + public var userDictionary: [String: Any]? + + /// Convenience Initializer + /// + /// - parameter id: Media Object ID. + /// - parameter type: Media Type (GIF/Sticker). + /// - parameter url: URL of the Media Object. + /// + convenience public init(_ id: String, type: GPHMediaType, url: String) { + self.init() + self.id = id + self.type = type + self.url = url + } + + //MARK: NSCoding + + required public convenience init?(coder aDecoder: NSCoder) { + guard let id = aDecoder.decodeObject(forKey: "id") as? String, + let type = GPHMediaType(rawValue: aDecoder.decodeObject(forKey: "type") as! String), + let url = aDecoder.decodeObject(forKey: "url") as? String + else { return nil } + + self.init(id, type: type, url: url) + + self.rating = GPHRatingType(rawValue: aDecoder.decodeObject(forKey: "rating") as? String ?? "") ?? .unrated + self.title = aDecoder.decodeObject(forKey: "title") as? String + self.caption = aDecoder.decodeObject(forKey: "caption") as? String + self.slug = aDecoder.decodeObject(forKey: "slug") as? String + self.importDate = aDecoder.decodeObject(forKey: "importDate") as? Date + self.trendingDate = aDecoder.decodeObject(forKey: "trendingDate") as? Date + self.indexable = aDecoder.decodeObject(forKey: "indexable") as? String + self.contentUrl = aDecoder.decodeObject(forKey: "contentUrl") as? String + self.bitlyUrl = aDecoder.decodeObject(forKey: "bitlyUrl") as? String + self.bitlyGifUrl = aDecoder.decodeObject(forKey: "bitlyGifUrl") as? String + self.embedUrl = aDecoder.decodeObject(forKey: "embedUrl") as? String + self.source = aDecoder.decodeObject(forKey: "source") as? String + self.sourceTld = aDecoder.decodeObject(forKey: "sourceTld") as? String + self.sourcePostUrl = aDecoder.decodeObject(forKey: "sourcePostUrl") as? String + self.user = aDecoder.decodeObject(forKey: "user") as? GPHUser + self.images = aDecoder.decodeObject(forKey: "images") as? GPHImages + self.bottleData = aDecoder.decodeObject(forKey: "bottleData") as? GPHBottleData + self.tags = aDecoder.decodeObject(forKey: "tags") as? [String] + self.featuredTags = aDecoder.decodeObject(forKey: "featuredTags") as? [String] + self.isHidden = aDecoder.decodeBool(forKey: "isHidden") + self.isRemoved = aDecoder.decodeBool(forKey: "isRemoved") + self.isCommunity = aDecoder.decodeBool(forKey: "isCommunity") + self.isAnonymous = aDecoder.decodeBool(forKey: "isAnonymous") + self.isFeatured = aDecoder.decodeBool(forKey: "isFeatured") + self.isRealtime = aDecoder.decodeBool(forKey: "isRealtime") + self.isIndexable = aDecoder.decodeBool(forKey: "isIndexable") + self.isSticker = aDecoder.decodeBool(forKey: "isSticker") + self.updateDate = aDecoder.decodeObject(forKey: "updateDate") as? Date + self.createDate = aDecoder.decodeObject(forKey: "createDate") as? Date + self.jsonRepresentation = aDecoder.decodeObject(forKey: "jsonRepresentation") as? GPHJSONObject + self.userDictionary = aDecoder.decodeObject(forKey: "userDictionary") as? [String: Any] + } + + public func encode(with aCoder: NSCoder) { + aCoder.encode(self.id, forKey: "id") + aCoder.encode(self.type.rawValue, forKey: "type") + aCoder.encode(self.url, forKey: "url") + aCoder.encode(self.rating.rawValue, forKey: "rating") + aCoder.encode(self.title, forKey: "title") + aCoder.encode(self.caption, forKey: "caption") + aCoder.encode(self.slug, forKey: "slug") + aCoder.encode(self.importDate, forKey: "importDate") + aCoder.encode(self.trendingDate, forKey: "trendingDate") + aCoder.encode(self.indexable, forKey: "indexable") + aCoder.encode(self.contentUrl, forKey: "contentUrl") + aCoder.encode(self.bitlyUrl, forKey: "bitlyUrl") + aCoder.encode(self.bitlyGifUrl, forKey: "bitlyGifUrl") + aCoder.encode(self.embedUrl, forKey: "embedUrl") + aCoder.encode(self.source, forKey: "source") + aCoder.encode(self.sourceTld, forKey: "sourceTld") + aCoder.encode(self.sourcePostUrl, forKey: "sourcePostUrl") + aCoder.encode(self.user, forKey: "user") + aCoder.encode(self.images, forKey: "images") + aCoder.encode(self.bottleData, forKey: "bottleData") + aCoder.encode(self.tags, forKey: "tags") + aCoder.encode(self.featuredTags, forKey: "featuredTags") + aCoder.encode(self.isHidden, forKey: "isHidden") + aCoder.encode(self.isRemoved, forKey: "isRemoved") + aCoder.encode(self.isCommunity, forKey: "isCommunity") + aCoder.encode(self.isAnonymous, forKey: "isAnonymous") + aCoder.encode(self.isFeatured, forKey: "isFeatured") + aCoder.encode(self.isRealtime, forKey: "isRealtime") + aCoder.encode(self.isIndexable, forKey: "isIndexable") + aCoder.encode(self.isSticker, forKey: "isSticker") + aCoder.encode(self.updateDate, forKey: "updateDate") + aCoder.encode(self.createDate, forKey: "createDate") + aCoder.encode(self.jsonRepresentation, forKey: "jsonRepresentation") + aCoder.encode(self.userDictionary, forKey: "userDictionary") + } + + // MARK: NSObject + + override public func isEqual(_ object: Any?) -> Bool { + if object as? GPHMedia === self { + return true + } + if let other = object as? GPHMedia, self.id == other.id { + return true + } + return false + } + + override public var hash: Int { + return "gph_object_\(self.id)".hashValue + } + +} + +// MARK: Extension -- Human readable + +/// Make objects human readable. +/// +extension GPHMedia { + + override public var description: String { + return "GPHMedia(\(self.type.rawValue)) for \(self.id) --> \(self.url)" + } + +} + +// MARK: Extension -- Allow setting JSON + +/// Make objects human readable. +/// +public extension GPHMedia { + + @objc public static func mapJSON(_ json: GPHJSONObject, request:String, media: GPHMediaType) throws -> GPHMedia { + let options: [String: Any?] = [ + "request": request, + "media": media + ] + let media = try GPHMedia.mapData(json, options: options) + return media + } + +} + +// MARK: Extension -- Parsing & Mapping + +/// For parsing/mapping protocol. +/// +extension GPHMedia: GPHMappable { + + /// This is where the magic/mapping happens + error handling. + public static func mapData(_ data: GPHJSONObject, options: [String: Any?]) throws -> GPHMedia { + guard + let objId: String = data["id"] as? String, + let url: String = data["url"] as? String + else { + throw GPHJSONMappingError(description: "Couldn't map GPHMedia for \(data)") + } + + guard let mediaType = options["media"] as? GPHMediaType else { + throw GPHJSONMappingError(description: "Need Media type to map the object") + } + + guard let requestType = options["request"] as? String else { + throw GPHJSONMappingError(description: "Need Request type to map the object") + } + + let obj = GPHMedia(objId, type: mediaType, url: url) + + obj.rating = parseRating(data["rating"] as? String) + obj.title = data["title"] as? String + obj.caption = data["caption"] as? String + obj.slug = data["slug"] as? String + obj.importDate = parseDate(data["import_datetime"] as? String) + obj.trendingDate = parseDate(data["trending_datetime"] as? String) + obj.indexable = data["indexable"] as? String + obj.contentUrl = data["content_url"] as? String + obj.bitlyUrl = data["bitly_url"] as? String + obj.bitlyGifUrl = data["bitly_gif_url"] as? String + obj.embedUrl = data["embed_url"] as? String + obj.source = data["source"] as? String + obj.sourceTld = data["source_tld"] as? String + obj.sourcePostUrl = data["source_post_url"] as? String + obj.tags = data["tags"] as? [String] + obj.featuredTags = data["featured_tags"] as? [String] + obj.isHidden = data["is_hidden"] as? Bool ?? false + obj.isRemoved = data["is_removed"] as? Bool ?? false + obj.isCommunity = data["is_community"] as? Bool ?? false + obj.isAnonymous = data["is_anonymous"] as? Bool ?? false + obj.isFeatured = data["is_featured"] as? Bool ?? false + obj.isRealtime = data["is_realtime"] as? Bool ?? false + obj.isIndexable = data["is_indexable"] as? Bool ?? false + obj.isSticker = data["is_sticker"] as? Bool ?? false + obj.updateDate = parseDate(data["update_datetime"] as? String) + obj.createDate = parseDate(data["create_datetime"] as? String) + obj.jsonRepresentation = data + + + // New options with root object + var optionsCopy = options + optionsCopy["root"] = obj + + // Handle User Data + if let userData = data["user"] as? GPHJSONObject { + obj.user = try GPHUser.mapData(userData, options: optionsCopy) + } + + // Handle Bottle Data + if let bottleData = data["bottle_data"] as? GPHJSONObject { + obj.bottleData = try GPHBottleData.mapData(bottleData, options: optionsCopy) + } + + // Handling exception of the Random endpoint structure + switch requestType { + case "random": + let renditions = try GPHImages.mapData(data, options: optionsCopy) + obj.images = renditions + + default: + if let renditionData = data["images"] as? GPHJSONObject { + let renditions = try GPHImages.mapData(renditionData, options: optionsCopy) + obj.images = renditions + } + } + + return obj + } + +} diff --git a/Pods/GiphyCoreSDK/Sources/GPHMediaResponse.swift b/Pods/GiphyCoreSDK/Sources/GPHMediaResponse.swift new file mode 100644 index 0000000..16ff896 --- /dev/null +++ b/Pods/GiphyCoreSDK/Sources/GPHMediaResponse.swift @@ -0,0 +1,83 @@ +// +// GPHMediaResponse.swift +// GiphyCoreSDK +// +// Created by Cem Kozinoglu, Gene Goykhman, Giorgia Marenda on 4/24/17. +// Copyright © 2017 Giphy. All rights reserved. +// +// This Source Code Form is subject to the terms of the Mozilla Public +// License, v. 2.0. If a copy of the MPL was not distributed with this +// file, You can obtain one at http://mozilla.org/MPL/2.0/. +// + +import Foundation + +/// Represents a Giphy Media Response (single result) +/// +@objcMembers public class GPHMediaResponse: GPHResponse { + // MARK: Properties + + /// Message description. + public fileprivate(set) var data: GPHMedia? + + + // MARK: Initializers + + /// Convenience Initializer + /// + /// - parameter meta: init with a GPHMeta object. + /// - parameter data: GPHMedia object (optional). + /// + convenience public init(_ meta:GPHMeta, data: GPHMedia?) { + self.init() + self.data = data + self.meta = meta + } + +} + +// MARK: Extension -- Human readable + +/// Make objects human readable. +/// +extension GPHMediaResponse { + + override public var description: String { + return "GPHMediaResponse(\(self.meta.responseId) status: \(self.meta.status) msg: \(self.meta.msg))" + } + +} + +// MARK: Extension -- Parsing & Mapping + +/// For parsing/mapping protocol. +/// +extension GPHMediaResponse: GPHMappable { + + /// this is where the magic will happen + error handling + public static func mapData(_ data: GPHJSONObject, options: [String: Any?]) throws -> GPHMediaResponse { + + guard + let metaData = data["meta"] as? GPHJSONObject + else { + throw GPHJSONMappingError(description: "Couldn't map GPHMediaResponse due to Meta missing for \(data)") + } + + let meta = try GPHMeta.mapData(metaData, options: options) + + // Try to see if we can get the Media object + if let mediaData = data["data"] as? GPHJSONObject { + + let data = try GPHMedia.mapData(mediaData, options: options) + if data.isValidObject() { + // We got the image and the meta data + return GPHMediaResponse(meta, data: data) + } + return GPHMediaResponse(meta, data: nil) + } + + // No image and the meta data + return GPHMediaResponse(meta, data: nil) + } + +} diff --git a/Pods/GiphyCoreSDK/Sources/GPHMeta.swift b/Pods/GiphyCoreSDK/Sources/GPHMeta.swift new file mode 100644 index 0000000..332f120 --- /dev/null +++ b/Pods/GiphyCoreSDK/Sources/GPHMeta.swift @@ -0,0 +1,93 @@ +// +// GPHMeta.swift +// GiphyCoreSDK +// +// Created by Cem Kozinoglu, Gene Goykhman, Giorgia Marenda on 4/24/17. +// Copyright © 2017 Giphy. All rights reserved. +// +// This Source Code Form is subject to the terms of the Mozilla Public +// License, v. 2.0. If a copy of the MPL was not distributed with this +// file, You can obtain one at http://mozilla.org/MPL/2.0/. +// + +import Foundation + +/// Represents a Giphy Response Meta Info +/// +@objcMembers public class GPHMeta: NSObject { + // MARK: Properties + + /// Unique response id. + public fileprivate(set) var responseId: String + + /// Status (200, 404...) + public fileprivate(set) var status: Int + + /// Message description. + public fileprivate(set) var msg: String + + /// Error Code. + public fileprivate(set) var errorCode: String + + // MARK: Initializers + + /// Initializer + /// + override public init() { + self.responseId = "" + self.status = 0 + self.msg = "" + self.errorCode = "" + super.init() + } + + /// Convenience Initializer + /// + /// - parameter responseId: Unique response id. + /// - parameter status: Status (200, 404...) + /// - parameter msg: Message description. + /// + convenience init(_ responseId: String, status: Int, msg: String, errorCode: String) { + self.init() + self.status = status + self.msg = msg + self.responseId = responseId + self.errorCode = errorCode + } + +} + +// MARK: Extension -- Human readable + +/// Make objects human readable. +/// +extension GPHMeta { + + override public var description: String { + return "GPHMeta(\(self.responseId) status: \(self.status) msg: \(self.msg) error_code: \(self.errorCode))" + } + +} + +// MARK: Extension -- Parsing & Mapping + +/// For parsing/mapping protocol. +/// +extension GPHMeta: GPHMappable { + + /// This is where the magic/mapping happens + error handling. + public static func mapData(_ data: GPHJSONObject, options: [String: Any?]) throws -> GPHMeta { + + guard + let responseId = data["response_id"] as? String, + let status = data["status"] as? Int, + let msg = data["msg"] as? String + else { + throw GPHJSONMappingError(description: "Couldn't map GPHMeta for \(data)") + } + let errorCode = data["error_code"] as? String ?? "" + + return GPHMeta(responseId, status: status, msg: msg, errorCode: errorCode) + } + +} diff --git a/Pods/GiphyCoreSDK/Sources/GPHNetworkReachability.swift b/Pods/GiphyCoreSDK/Sources/GPHNetworkReachability.swift new file mode 100644 index 0000000..80af3e2 --- /dev/null +++ b/Pods/GiphyCoreSDK/Sources/GPHNetworkReachability.swift @@ -0,0 +1,66 @@ +// +// GPHNetworkReachability.swift +// GiphyCoreSDK +// +// Created by Cem Kozinoglu, Gene Goykhman, Giorgia Marenda on 4/24/17. +// Copyright © 2017 Giphy. All rights reserved. +// +// This Source Code Form is subject to the terms of the Mozilla Public +// License, v. 2.0. If a copy of the MPL was not distributed with this +// file, You can obtain one at http://mozilla.org/MPL/2.0/. +// +// Credit goes to Algolia here: +// https://github.com/algolia/algoliasearch-client-swift/blob/master/Source/NetworkReachability.swift + +#if !os(watchOS) + + import Foundation + import SystemConfiguration + + + /// Detects network reachability using the system's built-in mechanism. + /// + @objcMembers public class GPHNetworkReachability { + + /// Reachability handle used to test connectivity. + private var reachability: SCNetworkReachability + + // MARK: Initialization + + public init() { + // Create reachability handle to an all-zeroes address. + var zeroAddress = GPHNetworkReachability.zeroAddress + reachability = withUnsafePointer(to: &zeroAddress) { + $0.withMemoryRebound(to: sockaddr.self, capacity: 1) { + SCNetworkReachabilityCreateWithAddress(nil, $0) + } + }! + } + + /// Test if network connectivity is currently available. + /// + /// - returns: true if network connectivity is available, false otherwise. + /// + public func isReachable() -> Bool { + var flags: SCNetworkReachabilityFlags = [] + if !SCNetworkReachabilityGetFlags(reachability, &flags) { + return false + } + + let reachable = flags.contains(.reachable) + let connectionRequired = flags.contains(.connectionRequired) + return reachable && !connectionRequired + } + + // MARK: Constants + + /// An all zeroes IP address. + static let zeroAddress: sockaddr_in = { + var address = sockaddr_in() + address.sin_len = UInt8(MemoryLayout.size) + address.sin_family = sa_family_t(AF_INET) + return address + }() + } + +#endif // !os(watchOS) diff --git a/Pods/GiphyCoreSDK/Sources/GPHPagination.swift b/Pods/GiphyCoreSDK/Sources/GPHPagination.swift new file mode 100644 index 0000000..aa90455 --- /dev/null +++ b/Pods/GiphyCoreSDK/Sources/GPHPagination.swift @@ -0,0 +1,102 @@ +// +// GPHPagination.swift +// GiphyCoreSDK +// +// Created by Cem Kozinoglu, Gene Goykhman, Giorgia Marenda on 4/24/17. +// Copyright © 2017 Giphy. All rights reserved. +// +// This Source Code Form is subject to the terms of the Mozilla Public +// License, v. 2.0. If a copy of the MPL was not distributed with this +// file, You can obtain one at http://mozilla.org/MPL/2.0/. +// + +import Foundation + +/// Represents a Giphy Response Pagination Info +/// +@objcMembers public class GPHPagination: NSObject { + // MARK: Properties + + /// Total Result Count. + public private(set) var totalCount: Int + + /// Actual Result Count (not always == limit) + public private(set) var count: Int + + /// Returned (if Filters applied) Result Count (not always == limit) + public private(set) var filteredCount: Int + + /// Offset to start next set of results. + public private(set) var offset: Int + + /// Next Page token + public private(set) var nextCursor: String? + + // MARK: Initializers + + /// Initializer + /// + override public init() { + self.totalCount = 0 + self.count = 0 + self.filteredCount = 0 + self.offset = 0 + super.init() + } + + /// Convenience Initializer + /// + /// - parameter totalCount: Total number of results available. + /// - parameter count: Number of results returned. + /// - parameter offset: Current offset of the result set. + /// + convenience init(_ totalCount: Int, count: Int, offset: Int, nextCursor: String? = nil) { + self.init() + self.totalCount = totalCount + self.count = count + self.filteredCount = count + self.offset = offset + self.nextCursor = nextCursor + } + + public func updateFilteredCount(_ count: Int) { + self.filteredCount = count + } + +} + +// MARK: Extension -- Human readable + +/// Make objects human readable. +/// +extension GPHPagination { + + override public var description: String { + return "GPHPagination(totalCount: \(self.totalCount) count: \(self.count) offset: \(self.offset))" + } + +} + +// MARK: Extension -- Parsing & Mapping + +/// For parsing/mapping protocol. +/// +extension GPHPagination: GPHMappable { + + /// This is where the magic/mapping happens + error handling. + public static func mapData(_ data: GPHJSONObject, options: [String: Any?]) throws -> GPHPagination { + + guard + let count = data["count"] as? Int + else { + throw GPHJSONMappingError(description: "Couldn't map GPHPagination for \(data)") + } + + let totalCount = data["total_count"] as? Int ?? count + let offset = data["offset"] as? Int ?? 0 + let nextCursor = data["next_cursor"] as? String ?? data["next_page"] as? String + + return GPHPagination(totalCount, count: count, offset: offset, nextCursor: nextCursor) + } + +} diff --git a/Pods/GiphyCoreSDK/Sources/GPHRequest.swift b/Pods/GiphyCoreSDK/Sources/GPHRequest.swift new file mode 100644 index 0000000..f124a88 --- /dev/null +++ b/Pods/GiphyCoreSDK/Sources/GPHRequest.swift @@ -0,0 +1,352 @@ +// +// GPHRequest.swift +// GiphyCoreSDK +// +// Created by Cem Kozinoglu, Gene Goykhman, Giorgia Marenda on 4/24/17. +// Copyright © 2017 Giphy. All rights reserved. +// +// This Source Code Form is subject to the terms of the Mozilla Public +// License, v. 2.0. If a copy of the MPL was not distributed with this +// file, You can obtain one at http://mozilla.org/MPL/2.0/. +// + +import Foundation + +/// Async Request Operations with Completion Handler Support +/// +@objcMembers public class GPHRequest: GPHAsyncOperationWithCompletion { + // MARK: Properties + + /// Config to form requests. + var config: GPHRequestConfig + + /// The client to which this request is related. + let client: GPHAbstractClient + + var lastRequestStartedAt: Date? = nil + + private var retryLimit = 3 + private var retryCount = 0 + private var retryDelay = 1.0 + private var retryDelayPower = 2.0 + + var hasRequestInFlight: Bool = false + + // This flag isn't set until we've receive at least a first response - + // even if it was empty. + var hasReceivedAResponse: Bool = false + + // This flag is set IFF we have received a failure more recently + // than a response. + var hasReceivedAFailure: Bool = false + + // This flag is set IFF we have received an empty response, which + // should indicate that we have "bottomed out" in the paging. + var hasReceivedEmptyResponse: Bool = false + + // MARK: Initializers + + /// Convenience Initializer + /// + /// - parameter client: GPHClient object to handle the request. + /// - parameter config: GPHRequestConfig to formulate request(s). + /// - parameter completionHandler: GPHJSONCompletionHandler to return JSON or Error. + /// + init(_ client: GPHAbstractClient, config: GPHRequestConfig, completionHandler: @escaping GPHJSONCompletionHandler) { + self.client = client + self.config = config + self.retryLimit = config.retry + super.init(completionHandler: completionHandler) + } + + func resetRequest(fireEventImmediately: Bool) { + + hasReceivedAResponse = false + hasReceivedEmptyResponse = false + hasReceivedAFailure = false + hasRequestInFlight = false + + lastRequestStartedAt = nil + + newRequest(force: true) + + if fireEventImmediately { + self.callCompletion(data: nil, response: nil, error: GPHHTTPError(statusCode:101, description: "Reset Request")) + } + + } + + func scheduleRetry() { + + if self.hasRequestInFlight && state != .finished { + // A retry is already scheduled, so ignore. + return + } + + retryCount += 1 + + // Our retry adopts a simple "exponential backoff" algorithm. + // Essentially we wait for the square of the retry count, in seconds, + // although we could tune this if we wanted to. + // e.g. After the first failure, we wait 1 second, + // after the second we wait 4 seconds, + // after the third we wait 9 seconds, etc. + let retryDelaySeconds = retryDelay * pow(Double(retryCount), retryDelayPower) + DispatchQueue.main.asyncAfter(deadline: .now() + retryDelaySeconds) { + self.newRequestFired() + } + } + + func cancelRetry() { + self.state = .finished + } + + func newRequestFired() { + newRequest(force: true) + } + + + // Initiate a new request if necessary. + // + // 1) If force is YES, always create a new request. + // 2) If force is NO, do not create a new request if there is already a pending retry. + @discardableResult func newRequest(force: Bool) -> Bool { + +// print("New Request retryCount:\(retryCount)") + if force { + cancelRetry() + hasRequestInFlight = false + } + + if hasRequestInFlight { + // There already is a request in flight. + return false + } + + hasRequestInFlight = true + lastRequestStartedAt = Date() + + self.start() + return true + } + + func succesfulRequest(data: GPHJSONObject?, response: URLResponse?, error: Error?) { + + self.cancelRetry() + self.retryCount = 0 + + self.hasRequestInFlight = false + self.hasReceivedAFailure = false + self.hasReceivedAResponse = true + + self.state = .finished + self.callCompletion(data: data, response: response, error: error) + } + + func failedRequest(retry: Bool = false, data: GPHJSONObject?, response: URLResponse?, error: Error?) { + + self.hasRequestInFlight = false + self.hasReceivedAFailure = true + + if retry { + if retryCount < retryLimit { + self.state = .finished + self.scheduleRetry() + return + } + } + + self.retryCount = 0 + self.state = .finished + self.callCompletion(data: data, response: response, error: error) + } + + + // MARK: Operation function + + /// Override the Operation function main to handle the request + /// + override public func main() { + client.session.dataTask(with: config.getRequest()) { data, response, error in + + if self.isCancelled { + return + } + + #if !os(watchOS) + if !self.client.isNetworkReachable() { + self.failedRequest(retry: true, data: nil, response: response, error: GPHHTTPError(statusCode:100, description: "Network is not reachable")) + return + } + #endif + + do { + guard let data = data else { + self.failedRequest(retry: true, data: nil, response: response, error:GPHJSONMappingError(description: "Can not map API response to JSON, there is no data")) + return + } + + let result = try JSONSerialization.jsonObject(with: data, options: .allowFragments) + + if let result = result as? GPHJSONObject { + // Got the JSON + let httpResponse = response! as! HTTPURLResponse + // Get the status code from the JSON if available and prefer it over the response code from HTTPURLRespons + // If not found return the actual response code from http + let statusCode = ((result["meta"] as? GPHJSONObject)?["status"] as? Int) ?? httpResponse.statusCode + + if httpResponse.statusCode != 200 || statusCode != 200 { + // Get the error message from JSON if available. + let errorMessage = (result["meta"] as? GPHJSONObject)?["msg"] as? String + // Prep the error + let errorAPIorHTTP = GPHHTTPError(statusCode: statusCode, description: errorMessage) + self.failedRequest(retry: false, data: result, response: response, error: errorAPIorHTTP) + return + } + self.succesfulRequest(data: result, response: response, error: error) + + } else { + self.failedRequest(retry: false, data: nil, response: response, error: GPHJSONMappingError(description: "Can not map API response to JSON")) + } + } catch { + self.failedRequest(retry: false, data: nil, response: response, error: error) + } + + }.resume() + } +} + + +/// Request Type for URLRequest objects. +/// +public enum GPHRequestType: String { + + /// POST request + case post = "POST" + + /// GET Request + case get = "GET" + + /// PUT Request + case put = "PUT" + + /// DELETE Request + case delete = "DELETE" + + /// UPLOAD Request + case upload = "UPLOAD" +} + +/// Router to generate URLRequest objects. +/// +public enum GPHRequestRouter { + /// MARK: Properties + + /// Setup the Request: Path, Method, Parameters, Headers) + case request(String, String, GPHRequestType, [URLQueryItem]?, [String: String]?) + + /// HTTP Method type. + var method: GPHRequestType { + switch self { + case .request(_, _, let method, _, _): + return method + } + } + + /// Full URL + var url: URL { + switch self { + case .request(let base, let path, _, _, _): + let baseUrl = URL(string: base)! + return baseUrl.appendingPathComponent(path) + } + } + + /// Query Parameters + var query: [URLQueryItem] { + switch self { + case .request(_, _, _, let queryItems, _): + return queryItems ?? [] + } + } + + /// Custom Headers + var headers: [String: String] { + switch self { + case .request(_, _, _, _, let customHeaders): + return customHeaders ?? [:] + } + } + + // MARK: Helper functions + + /// Encode a URLQueryItem for including in HTTP requests + /// (encodes + signs correctly to %2B) + /// + /// - parameter queryItem: URLQueryItem to be encoded. + /// - returns: a URLQueryItem whose value is correctly percent-escaped. + /// + public func encodedURLQueryItem(_ queryItem: URLQueryItem) -> URLQueryItem { + var allowedCharacters: CharacterSet = CharacterSet.urlQueryAllowed + + // Removing the characters that AlamoFire removes to match behaviour: + // https://github.com/Alamofire/Alamofire/blob/master/Source/ParameterEncoding.swift#L236 + + allowedCharacters.remove(charactersIn: ":#[]@!$&'()*+,;=") + let encodedValue = queryItem.value?.addingPercentEncoding(withAllowedCharacters: allowedCharacters) + return URLQueryItem(name: queryItem.name, value: encodedValue) + } + + + /// Construct the request from url, method and parameters. + /// + /// - parameter apiKey: Api-key for the request. + /// - returns: A URLRequest object constructed from the current type of the request. + /// + public func asURLRequest(_ apiKey: String) -> URLRequest { + + var queryItems = query + queryItems.append(URLQueryItem(name: "api_key", value: apiKey)) + + // Get the final url + let finalUrl: URL = { + switch method { + case .get: + var urlComponents = URLComponents(string: url.absoluteString) + urlComponents?.queryItems = queryItems + guard let fullUrl = urlComponents?.url else { return url } + return fullUrl + default: + return url + } + }() + + // Create the request. + var request = URLRequest(url: finalUrl) + request.httpMethod = (method == .upload ? "POST" : method.rawValue) + + // Add the custom headers. + for (header, value) in headers { + request.addValue(value, forHTTPHeaderField: header) + } + + switch method { + case .post, .delete, .put: + // Set up request parameters. + request.addValue("application/x-www-form-urlencoded", forHTTPHeaderField: "content-type") + + var urlComponents = URLComponents(string: url.absoluteString) + let encodedQueryItems: [URLQueryItem] = queryItems.map { queryItem in + return encodedURLQueryItem(queryItem) + } + urlComponents?.queryItems = encodedQueryItems + request.httpBody = (urlComponents?.query ?? "").data(using: String.Encoding.utf8) + case .get: + request.addValue("application/json", forHTTPHeaderField: "content-type") + default: + break + } + + return request + } +} diff --git a/Pods/GiphyCoreSDK/Sources/GPHRequestConfig.swift b/Pods/GiphyCoreSDK/Sources/GPHRequestConfig.swift new file mode 100644 index 0000000..2427b08 --- /dev/null +++ b/Pods/GiphyCoreSDK/Sources/GPHRequestConfig.swift @@ -0,0 +1,27 @@ +// +// GPHRequestConfig.swift +// GiphyCoreSDK +// +// Created by Cem Kozinoglu on 3/15/18. +// Copyright © 2018 Giphy. All rights reserved. +// + +import Foundation + + +@objcMembers public class GPHRequestConfig:NSObject { + + public var base = "https://api.giphy.com/v1/" + public var method: GPHRequestType = .get + public var queryItems: [URLQueryItem]? = nil + public var headers: [String: String]? = nil + public var path: String = "" + public var requestType: String = "" + public var options: [String: Any?]? = nil + public var apiKey: String = "" + public var retry: Int = 3 + + public func getRequest() -> URLRequest { + return GPHRequestRouter.request(base, path, method, queryItems, headers).asURLRequest(apiKey) + } +} diff --git a/Pods/GiphyCoreSDK/Sources/GPHResponse.swift b/Pods/GiphyCoreSDK/Sources/GPHResponse.swift new file mode 100644 index 0000000..3eb27be --- /dev/null +++ b/Pods/GiphyCoreSDK/Sources/GPHResponse.swift @@ -0,0 +1,53 @@ +// +// GPHResponse.swift +// GiphyCoreSDK +// +// Created by Cem Kozinoglu, Gene Goykhman, Giorgia Marenda on 4/24/17. +// Copyright © 2017 Giphy. All rights reserved. +// +// This Source Code Form is subject to the terms of the Mozilla Public +// License, v. 2.0. If a copy of the MPL was not distributed with this +// file, You can obtain one at http://mozilla.org/MPL/2.0/. +// + +import Foundation + +/// Represents a Giphy Response Meta Info +/// +@objcMembers open class GPHResponse: NSObject { + // MARK: Properties + + /// Message description. + open var meta: GPHMeta + + + // MARK: Initializers + + /// Initializer + /// + override public init() { + self.meta = GPHMeta() + super.init() + } + + /// Convenience Initializer + /// + /// - parameter meta: init with a GPHMeta object. + /// + convenience public init(_ meta: GPHMeta) { + self.init() + self.meta = meta + } +} + +// MARK: Extension -- Human readable + +/// Make objects human readable. +/// +extension GPHResponse { + + override open var description: String { + return "GPHResponse(\(self.meta.responseId) status: \(self.meta.status) msg: \(self.meta.msg))" + } + +} diff --git a/Pods/GiphyCoreSDK/Sources/GPHTermSuggestion.swift b/Pods/GiphyCoreSDK/Sources/GPHTermSuggestion.swift new file mode 100644 index 0000000..96ea609 --- /dev/null +++ b/Pods/GiphyCoreSDK/Sources/GPHTermSuggestion.swift @@ -0,0 +1,107 @@ +// +// GPHTermSuggestion.swift +// GiphyCoreSDK +// +// Created by Cem Kozinoglu, Gene Goykhman, Giorgia Marenda on 4/24/17. +// Copyright © 2017 Giphy. All rights reserved. +// +// This Source Code Form is subject to the terms of the Mozilla Public +// License, v. 2.0. If a copy of the MPL was not distributed with this +// file, You can obtain one at http://mozilla.org/MPL/2.0/. +// + +import Foundation + +/// Represents a Giphy Term Suggestion +/// +@objcMembers public class GPHTermSuggestion: GPHFilterable, NSCoding { + // MARK: Properties + + /// Term suggestion. + public private(set) var term: String = "" + + /// JSON Representation. + public fileprivate(set) var jsonRepresentation: GPHJSONObject? + + /// User Dictionary to Store data in Obj by the Developer + public var userDictionary: [String: Any]? + + // MARK: Initializers + + /// Convenience Initializer + /// + /// - parameter term: Term suggestion. + /// + convenience public init(_ term: String) { + self.init() + self.term = term + } + + //MARK: NSCoding + + required convenience public init?(coder aDecoder: NSCoder) { + guard let term = aDecoder.decodeObject(forKey: "term") as? String + else { return nil } + + self.init(term) + self.jsonRepresentation = aDecoder.decodeObject(forKey: "jsonRepresentation") as? GPHJSONObject + self.userDictionary = aDecoder.decodeObject(forKey: "userDictionary") as? [String: Any] + } + + public func encode(with aCoder: NSCoder) { + aCoder.encode(self.term, forKey: "term") + aCoder.encode(self.jsonRepresentation, forKey: "jsonRepresentation") + aCoder.encode(self.userDictionary, forKey: "userDictionary") + } + + // MARK: NSObject + + override public func isEqual(_ object: Any?) -> Bool { + if object as? GPHTermSuggestion === self { + return true + } + if let other = object as? GPHTermSuggestion, self.term == other.term { + return true + } + return false + } + + override public var hash: Int { + return "gph_term_suggestion_\(self.term)".hashValue + } + +} + +// MARK: Extension -- Human readable + +/// Make objects human readable. +/// +extension GPHTermSuggestion { + + override public var description: String { + return "GPHTermSuggestion(\(self.term))" + } + +} + +// MARK: Extension -- Parsing & Mapping + +/// For parsing/mapping protocol. +/// +extension GPHTermSuggestion: GPHMappable { + + /// This is where the magic/mapping happens + error handling. + public static func mapData(_ data: GPHJSONObject, options: [String: Any?]) throws -> GPHTermSuggestion { + + guard + let term = data["name"] as? String + else { + throw GPHJSONMappingError(description: "Couldn't map GPHTermSuggestion for \(data)") + } + + let obj = GPHTermSuggestion(term) + obj.jsonRepresentation = data + return obj + } + +} diff --git a/Pods/GiphyCoreSDK/Sources/GPHTypes.swift b/Pods/GiphyCoreSDK/Sources/GPHTypes.swift new file mode 100644 index 0000000..313f9c3 --- /dev/null +++ b/Pods/GiphyCoreSDK/Sources/GPHTypes.swift @@ -0,0 +1,523 @@ +// +// GPHTypes.swift +// GiphyCoreSDK +// +// Created by Cem Kozinoglu, Gene Goykhman, Giorgia Marenda on 4/24/17. +// Copyright © 2017 Giphy. All rights reserved. +// +// This Source Code Form is subject to the terms of the Mozilla Public +// License, v. 2.0. If a copy of the MPL was not distributed with this +// file, You can obtain one at http://mozilla.org/MPL/2.0/. +// + +import Foundation + + +/// Represents a Giphy Object Type (GIF/Sticker/...) +/// +@objc public enum GPHMediaType: Int, RawRepresentable { + /// We use Int, RawRepresentable to be able to bridge btw ObjC<>Swift without losing String values. + + /// Gif Media Type + case gif + + /// Sticker Media Type + case sticker + + public typealias RawValue = String + + public var rawValue: RawValue { + switch self { + case .gif: + return "gif" + case .sticker: + return "sticker" + } + } + + public init?(rawValue: RawValue) { + switch rawValue.lowercased() { + case "gif": + self = .gif + case "sticker": + self = .sticker + default: + self = .gif + } + } + +} + +/// Represents a Giphy Rendition Type (Original/Preview/...) +/// +@objc public enum GPHRenditionType: Int, RawRepresentable { + /// We use Int, RawRepresentable to be able to bridge btw ObjC<>Swift without losing String values. + + /// Original file size and file dimensions. Good for desktop use. + case original + + /// Preview image for original. + case originalStill + + /// File size under 50kb. Duration may be truncated to meet file size requirements. Good for thumbnails and previews. + case preview + + /// Duration set to loop for 15 seconds. Only recommended for this exact use case. + case looping + + /// Height set to 200px. Good for mobile use. + case fixedHeight + + /// Static preview image for fixed_height + case fixedHeightStill + + /// Height set to 200px. Reduced to 6 frames to minimize file size to the lowest. + /// Works well for unlimited scroll on mobile and as animated previews. See Giphy.com on mobile web as an example. + case fixedHeightDownsampled + + /// Height set to 100px. Good for mobile keyboards. + case fixedHeightSmall + + /// Static preview image for fixed_height_small + case fixedHeightSmallStill + + /// Width set to 200px. Good for mobile use. + case fixedWidth + + /// Static preview image for fixed_width + case fixedWidthStill + + /// Width set to 200px. Reduced to 6 frames. Works well for unlimited scroll on mobile and as animated previews. + case fixedWidthDownsampled + + /// Width set to 100px. Good for mobile keyboards. + case fixedWidthSmall + + /// Static preview image for fixed_width_small + case fixedWidthSmallStill + + /// File size under 2mb. + case downsized + + /// File size under 200kb. + case downsizedSmall + + /// File size under 5mb. + case downsizedMedium + + /// File size under 8mb. + case downsizedLarge + + /// Static preview image for downsized. + case downsizedStill + + + public typealias RawValue = String + + public var rawValue: RawValue { + switch self { + case .original: + return "original" + case .originalStill: + return "original_still" + case .preview: + return "preview" + case .looping: + return "looping" + case .fixedHeight: + return "fixed_height" + case .fixedHeightStill: + return "fixed_height_still" + case .fixedHeightDownsampled: + return "fixed_height_downsampled" + case .fixedHeightSmall: + return "fixed_height_small" + case .fixedHeightSmallStill: + return "fixed_height_small_still" + case .fixedWidth: + return "fixed_width" + case .fixedWidthStill: + return "fixed_width_still" + case .fixedWidthDownsampled: + return "fixed_width_downsampled" + case .fixedWidthSmall: + return "fixed_width_small" + case .fixedWidthSmallStill: + return "fixed_width_small_still" + case .downsized: + return "downsized" + case .downsizedSmall: + return "downsized_small" + case .downsizedMedium: + return "downsized_medium" + case .downsizedLarge: + return "downsized_large" + case .downsizedStill: + return "downsized_still" + } + } + + public init?(rawValue: RawValue) { + switch rawValue.lowercased() { + + case "original": + self = .original + case "original_still": + self = .originalStill + case "preview": + self = .preview + case "looping": + self = .looping + case "fixed_height": + self = .fixedHeight + case "fixed_height_still": + self = .fixedHeightStill + case "fixed_height_downsampled": + self = .fixedHeightDownsampled + case "fixed_height_small": + self = .fixedHeightSmall + case "fixed_height_small_still": + self = .fixedHeightSmallStill + case "fixed_width": + self = .fixedWidth + case "fixed_width_still": + self = .fixedWidthStill + case "fixed_width_downsampled": + self = .fixedWidthDownsampled + case "fixed_width_small": + self = .fixedWidthSmall + case "fixed_width_small_still": + self = .fixedWidthSmallStill + case "downsized": + self = .downsized + case "downsized_small": + self = .downsizedSmall + case "downsized_medium": + self = .downsizedMedium + case "downsized_large": + self = .downsizedLarge + case "downsized_still": + self = .downsizedStill + + default: + self = .original + } + } +} + + +/// Represents Giphy APIs Supported Languages +/// +@objc public enum GPHLanguageType: Int, RawRepresentable { + /// We use Int, RawRepresentable to be able to bridge btw ObjC<>Swift without loosing String values. + + /// English (en) + case english + + /// Spanish (es) + case spanish + + /// Portuguese (pt) + case portuguese + + /// Indonesian (id) + case indonesian + + /// French (fr) + case french + + /// Arabic (ar) + case arabic + + /// Turkish (tr) + case turkish + + /// Thai (th) + case thai + + /// Vietnamese (vi) + case vietnamese + + /// German (de) + case german + + /// Italian (it) + case italian + + /// Japanese (ja) + case japanese + + /// Chinese Simplified (zh-cn) + case chineseSimplified + + /// Chinese Traditional (zh-tw) + case chineseTraditional + + /// Russian (ru) + case russian + + /// Korean (ko) + case korean + + /// Polish (pl) + case polish + + /// Dutch (nl) + case dutch + + /// Romanian (ro) + case romanian + + /// Hungarian (hu) + case hungarian + + /// Swedish (sv) + case swedish + + /// Czech (cs) + case czech + + /// Hindi (hi) + case hindi + + /// Bengali (bn) + case bengali + + /// Danish (da) + case danish + + /// Farsi (fa) + case farsi + + /// Filipino (tl) + case filipino + + /// Finnish (fi) + case finnish + + /// Hebrew (iw) + case hebrew + + /// Malay (ms) + case malay + + /// Norwegian (no) + case norwegian + + /// Ukrainian (uk) + case ukrainian + + public typealias RawValue = String + + public var rawValue: RawValue { + switch self { + case .english: + return "en" + case .spanish: + return "es" + case .portuguese: + return "pt" + case .indonesian: + return "id" + case .french: + return "fr" + case .arabic: + return "ar" + case .turkish: + return "tr" + case .thai: + return "th" + case .vietnamese: + return "vi" + case .german: + return "de" + case .italian: + return "it" + case .japanese: + return "ja" + case .chineseSimplified: + return "zh-cn" + case .chineseTraditional: + return "zh-tw" + case .russian: + return "ru" + case .korean: + return "ko" + case .polish: + return "pl" + case .dutch: + return "nl" + case .romanian: + return "ro" + case .hungarian: + return "hu" + case .swedish: + return "sv" + case .czech: + return "cs" + case .hindi: + return "hi" + case .bengali: + return "bn" + case .danish: + return "da" + case .farsi: + return "fa" + case .filipino: + return "tl" + case .finnish: + return "fi" + case .hebrew: + return "iw" + case .malay: + return "ms" + case .norwegian: + return "no" + case .ukrainian: + return "uk" + } + } + + public init?(rawValue: RawValue) { + switch rawValue.lowercased() { + + case "en": + self = .english + case "es": + self = .spanish + case "pt": + self = .portuguese + case "id": + self = .indonesian + case "fr": + self = .french + case "ar": + self = .arabic + case "tr": + self = .turkish + case "th": + self = .thai + case "vi": + self = .vietnamese + case "de": + self = .german + case "it": + self = .italian + case "ja": + self = .japanese + case "zh-cn": + self = .chineseSimplified + case "zh-tw": + self = .chineseTraditional + case "ru": + self = .russian + case "ko": + self = .korean + case "pl": + self = .polish + case "nl": + self = .dutch + case "ro": + self = .romanian + case "hu": + self = .hungarian + case "sv": + self = .swedish + case "cs": + self = .czech + case "hi": + self = .hindi + case "bn": + self = .bengali + case "da": + self = .danish + case "fa": + self = .farsi + case "tl": + self = .filipino + case "fi": + self = .finnish + case "iw": + self = .hebrew + case "ms": + self = .malay + case "no": + self = .norwegian + case "uk": + self = .ukrainian + default: + self = .english + } + } +} + + +/// Represents content rating (y,g, pg, pg-13 or r) +/// +@objc public enum GPHRatingType: Int, RawRepresentable { + /// We use Int, RawRepresentable to be able to bridge btw ObjC<>Swift without loosing String values. + + /// Rated Y + case ratedY + + /// Rated G + case ratedG + + /// Rated PG + case ratedPG + + /// Rated PG-13 + case ratedPG13 + + /// Rated R + case ratedR + + /// Not Safe for Work + case nsfw + + /// Unrated + case unrated + + public typealias RawValue = String + + public var rawValue: RawValue { + switch self { + case .ratedY: + return "y" + case .ratedG: + return "g" + case .ratedPG: + return "pg" + case .ratedPG13: + return "pg-13" + case .ratedR: + return "r" + case .nsfw: + return "nsfw" + case .unrated: + return "unrated" + } + } + + public init?(rawValue: RawValue) { + switch rawValue.lowercased() { + case "y": + self = .ratedY + case "g": + self = .ratedG + case "pg": + self = .ratedPG + case "pg-13": + self = .ratedPG13 + case "r": + self = .ratedR + case "nsfw": + self = .nsfw + case "unrated": + self = .unrated + default: + self = .ratedR + } + } + +} diff --git a/Pods/GiphyCoreSDK/Sources/GPHUser.swift b/Pods/GiphyCoreSDK/Sources/GPHUser.swift new file mode 100644 index 0000000..276431f --- /dev/null +++ b/Pods/GiphyCoreSDK/Sources/GPHUser.swift @@ -0,0 +1,241 @@ +// +// GPHUser.swift +// GiphyCoreSDK +// +// Created by Cem Kozinoglu, Gene Goykhman, Giorgia Marenda on 4/24/17. +// Copyright © 2017 Giphy. All rights reserved. +// +// This Source Code Form is subject to the terms of the Mozilla Public +// License, v. 2.0. If a copy of the MPL was not distributed with this +// file, You can obtain one at http://mozilla.org/MPL/2.0/. +// + +import Foundation + +/// Represents a Giphy User Object +/// +/// http://api.giphy.com/v1/gifs/categories/animals/cats?api_key=4OMJYpPoYwVpe + +@objcMembers public class GPHUser: GPHFilterable, NSCoding { + // MARK: Properties + + /// Username. + public fileprivate(set) var username: String = "" + + /// User ID. + public fileprivate(set) var userId: String? + + /// Name of the User. + public fileprivate(set) var name: String? + + /// Description of the User. + public fileprivate(set) var userDescription: String? + + /// Attribution Display Name. + public fileprivate(set) var attributionDisplayName: String? + + /// Display Name for the User. + public fileprivate(set) var displayName: String? + + /// Twitter Handler. + public fileprivate(set) var twitter: String? + + /// URL of the Twitter Handler. + public fileprivate(set) var twitterUrl: String? + + /// URL of the Facebook Handler. + public fileprivate(set) var facebookUrl: String? + + /// URL of the Instagram Handler. + public fileprivate(set) var instagramUrl: String? + + /// URL of the Website + public fileprivate(set) var websiteUrl: String? + + /// Displayable URL of the Website. + public fileprivate(set) var websiteDisplayUrl: String? + + /// URL of the Tumblr Handler. + public fileprivate(set) var tumblrUrl: String? + + /// URL of the Avatar. + public fileprivate(set) var avatarUrl: String? + + /// URL of the Banner. + public fileprivate(set) var bannerUrl: String? + + /// URL of the Profile. + public fileprivate(set) var profileUrl: String? + + /// User Public/Private. + public fileprivate(set) var isPublic: Bool = false + + /// User is Staff. + public fileprivate(set) var isStaff: Bool = false + + /// User is Verified + public fileprivate(set) var isVerified: Bool = false + + /// Suppress Chrome. + public fileprivate(set) var suppressChrome: Bool = false + + /// Last Login Date/Time. + public fileprivate(set) var loginDate: Date? + + /// Join Date/Time. + public fileprivate(set) var joinDate: Date? + + /// JSON Representation. + public fileprivate(set) var jsonRepresentation: GPHJSONObject? + + /// User Dictionary to Store data in Obj by the Developer + public var userDictionary: [String: Any]? + + // MARK: Initializers + + /// Convenience Initializer + /// + /// - parameter username: Username of the User. + /// + convenience public init(_ username: String) { + self.init() + self.username = username + } + + //MARK: NSCoding + + required convenience public init?(coder aDecoder: NSCoder) { + guard + let username = aDecoder.decodeObject(forKey: "username") as? String + else { + return nil + } + + self.init(username) + + self.userId = aDecoder.decodeObject(forKey: "userId") as? String + self.isPublic = aDecoder.decodeBool(forKey: "isPublic") + self.isStaff = aDecoder.decodeBool(forKey: "isStaff") + self.isVerified = aDecoder.decodeBool(forKey: "isVerified") + self.suppressChrome = aDecoder.decodeBool(forKey: "suppressChrome") + self.name = aDecoder.decodeObject(forKey: "name") as? String + self.displayName = aDecoder.decodeObject(forKey: "displayName") as? String + self.userDescription = aDecoder.decodeObject(forKey: "userDescription") as? String + self.attributionDisplayName = aDecoder.decodeObject(forKey: "attributionDisplayName") as? String + self.twitter = aDecoder.decodeObject(forKey: "twitter") as? String + self.twitterUrl = aDecoder.decodeObject(forKey: "twitterUrl") as? String + self.facebookUrl = aDecoder.decodeObject(forKey: "facebookUrl") as? String + self.instagramUrl = aDecoder.decodeObject(forKey: "instagramUrl") as? String + self.websiteUrl = aDecoder.decodeObject(forKey: "websiteUrl") as? String + self.websiteDisplayUrl = aDecoder.decodeObject(forKey: "websiteDisplayUrl") as? String + self.tumblrUrl = aDecoder.decodeObject(forKey: "tumblrUrl") as? String + self.avatarUrl = aDecoder.decodeObject(forKey: "avatarUrl") as? String + self.bannerUrl = aDecoder.decodeObject(forKey: "bannerUrl") as? String + self.profileUrl = aDecoder.decodeObject(forKey: "profileUrl") as? String + self.loginDate = aDecoder.decodeObject(forKey: "loginDate") as? Date + self.joinDate = aDecoder.decodeObject(forKey: "joinDate") as? Date + self.jsonRepresentation = aDecoder.decodeObject(forKey: "jsonRepresentation") as? GPHJSONObject + self.userDictionary = aDecoder.decodeObject(forKey: "userDictionary") as? [String: Any] + } + + public func encode(with aCoder: NSCoder) { + aCoder.encode(self.username, forKey: "username") + aCoder.encode(self.userId, forKey: "userId") + aCoder.encode(self.isPublic, forKey: "isPublic") + aCoder.encode(self.isStaff, forKey: "isStaff") + aCoder.encode(self.isVerified, forKey: "isVerified") + aCoder.encode(self.suppressChrome, forKey: "suppressChrome") + aCoder.encode(self.name, forKey: "name") + aCoder.encode(self.displayName, forKey: "displayName") + aCoder.encode(self.userDescription, forKey: "userDescription") + aCoder.encode(self.attributionDisplayName, forKey: "attributionDisplayName") + aCoder.encode(self.twitter, forKey: "twitter") + aCoder.encode(self.twitterUrl, forKey: "twitterUrl") + aCoder.encode(self.facebookUrl, forKey: "facebookUrl") + aCoder.encode(self.instagramUrl, forKey: "instagramUrl") + aCoder.encode(self.websiteUrl, forKey: "websiteUrl") + aCoder.encode(self.websiteDisplayUrl, forKey: "websiteDisplayUrl") + aCoder.encode(self.tumblrUrl, forKey: "tumblrUrl") + aCoder.encode(self.avatarUrl, forKey: "avatarUrl") + aCoder.encode(self.bannerUrl, forKey: "bannerUrl") + aCoder.encode(self.profileUrl, forKey: "profileUrl") + aCoder.encode(self.loginDate, forKey: "loginDate") + aCoder.encode(self.joinDate, forKey: "joinDate") + aCoder.encode(self.jsonRepresentation, forKey: "jsonRepresentation") + aCoder.encode(self.userDictionary, forKey: "userDictionary") + } + + // MARK: NSObject + + override public func isEqual(_ object: Any?) -> Bool { + if object as? GPHUser === self { + return true + } + if let other = object as? GPHUser, self.username == other.username { + return true + } + return false + } + + override public var hash: Int { + return "gph_user_\(self.username)".hashValue + } + +} + +// MARK: Extension -- Human readable + +/// Make objects human readable. +/// +extension GPHUser { + + override public var description: String { + return "GPHUser(\(self.username))" + } + +} + +// MARK: Extension -- Parsing & Mapping + +/// For parsing/mapping protocol. +/// +extension GPHUser: GPHMappable { + + /// This is where the magic/mapping happens + error handling. + public static func mapData(_ data: GPHJSONObject, options: [String: Any?]) throws -> GPHUser { + + guard + let username = data["username"] as? String + else { + throw GPHJSONMappingError(description: "Couldn't map GPHUser for \(data)") + } + + let obj = GPHUser(username) + + obj.userId = data["id"] as? String + obj.isPublic = data["is_public"] as? Bool ?? false + obj.isStaff = data["is_staff"] as? Bool ?? false + obj.isVerified = data["is_verified"] as? Bool ?? false + obj.suppressChrome = data["suppress_chrome"] as? Bool ?? false + obj.name = data["name"] as? String + obj.displayName = data["display_name"] as? String + obj.userDescription = data["description"] as? String + obj.attributionDisplayName = data["attribution_display_name"] as? String + obj.twitter = data["twitter"] as? String + obj.twitterUrl = data["twitter_url"] as? String + obj.facebookUrl = data["facebook_url"] as? String + obj.instagramUrl = data["instagram_url"] as? String + obj.websiteUrl = data["website_url"] as? String + obj.websiteDisplayUrl = data["website_display_url"] as? String + obj.tumblrUrl = data["tumblr_url"] as? String + obj.avatarUrl = data["avatar_url"] as? String + obj.bannerUrl = data["banner_url"] as? String + obj.profileUrl = data["profile_url"] as? String + obj.loginDate = parseDate(data["last_login"] as? String) + obj.joinDate = parseDate(data["date_joined"] as? String) + obj.jsonRepresentation = data + + return obj + } + +} diff --git a/Pods/GiphyCoreSDK/Sources/GiphyCore.swift b/Pods/GiphyCoreSDK/Sources/GiphyCore.swift new file mode 100644 index 0000000..072c8a1 --- /dev/null +++ b/Pods/GiphyCoreSDK/Sources/GiphyCore.swift @@ -0,0 +1,32 @@ +// +// GiphyCore.swift +// GiphyCoreSDK +// +// Created by Cem Kozinoglu on 2/17/18. +// Copyright © 2018 Giphy. All rights reserved. +// + +import Foundation + +@objc public class GiphyCore: NSObject { + + // Singleton to interface with + @objc public static let shared = GPHClient(apiKey: "") + + /// Configure the Client + /// + /// - parameter apiKey: Giphy Api Key to use. + /// + @objc public class func configure(apiKey: String) { + shared.apiKey = apiKey + } + + /// Configure Filtering for all the Models + /// + /// - parameter filter: GPHFilterBlock to use and figure out if an object is valid or not. + /// + @objc public class func setFilter(filter: @escaping GPHFilterBlock) { + GPHFilterable.filter = filter + } + +} diff --git a/Pods/Manifest.lock b/Pods/Manifest.lock new file mode 100644 index 0000000..f3d4d20 --- /dev/null +++ b/Pods/Manifest.lock @@ -0,0 +1,25 @@ +PODS: + - Alamofire (4.7.3) + - AlamofireImage (3.4.1): + - Alamofire (~> 4.7) + - GiphyCoreSDK (1.4.0) + +DEPENDENCIES: + - Alamofire + - AlamofireImage + - GiphyCoreSDK + +SPEC REPOS: + https://github.com/cocoapods/specs.git: + - Alamofire + - AlamofireImage + - GiphyCoreSDK + +SPEC CHECKSUMS: + Alamofire: c7287b6e5d7da964a70935e5db17046b7fde6568 + AlamofireImage: 78d67ccbb763d87ba44b21583d2153500a195630 + GiphyCoreSDK: 1fe401c5fc65f182e7aa8b7fb2c9005f2a523374 + +PODFILE CHECKSUM: de154add1f98ee8de3a656157ac9b567dfb60cea + +COCOAPODS: 1.5.3 diff --git a/Pods/Pods.xcodeproj/project.pbxproj b/Pods/Pods.xcodeproj/project.pbxproj new file mode 100644 index 0000000..83003f1 --- /dev/null +++ b/Pods/Pods.xcodeproj/project.pbxproj @@ -0,0 +1,1209 @@ +// !$*UTF8*$! +{ + archiveVersion = 1; + classes = { + }; + objectVersion = 50; + objects = { + +/* Begin PBXBuildFile section */ + 0BF96C90FD9427084AEEE5A80777D315 /* ParameterEncoding.swift in Sources */ = {isa = PBXBuildFile; fileRef = CF32C4B7557300ECD2B69C7D2DBD0B81 /* ParameterEncoding.swift */; settings = {COMPILER_FLAGS = "-w -Xanalyzer -analyzer-disable-all-checks"; }; }; + 0C0999336CB60FB05382C22234F3BD12 /* GPHCategory.swift in Sources */ = {isa = PBXBuildFile; fileRef = 93D7F1C61D175EC407AAF2C6D3C69B55 /* GPHCategory.swift */; settings = {COMPILER_FLAGS = "-w -Xanalyzer -analyzer-disable-all-checks"; }; }; + 15FB65BCB4965C6535D6A0BF45729318 /* GPHMediaResponse.swift in Sources */ = {isa = PBXBuildFile; fileRef = E71089437F91AA345B407F58E771BCF7 /* GPHMediaResponse.swift */; settings = {COMPILER_FLAGS = "-w -Xanalyzer -analyzer-disable-all-checks"; }; }; + 1B9BB6FA8B1063E806B2B85848565729 /* GPHChannel.swift in Sources */ = {isa = PBXBuildFile; fileRef = C995EE8354CA18A106E2CB9A3580A880 /* GPHChannel.swift */; settings = {COMPILER_FLAGS = "-w -Xanalyzer -analyzer-disable-all-checks"; }; }; + 1CA14C18BD2534E7C4BF1F143A7B3992 /* GPHResponse.swift in Sources */ = {isa = PBXBuildFile; fileRef = 92A0DB9E48B5358B3ADDDE05F7BB9CAA /* GPHResponse.swift */; settings = {COMPILER_FLAGS = "-w -Xanalyzer -analyzer-disable-all-checks"; }; }; + 1CD2199964B9A046AAD5D5334AC2D598 /* GPHImage.swift in Sources */ = {isa = PBXBuildFile; fileRef = 1C6F8FC7F8087C8CA1FE23763A0FB4DF /* GPHImage.swift */; settings = {COMPILER_FLAGS = "-w -Xanalyzer -analyzer-disable-all-checks"; }; }; + 208BC377B47C3CB40659D990D98180E6 /* GPHChannelTag.swift in Sources */ = {isa = PBXBuildFile; fileRef = 10820F9243CB05D1856DD0F8CEACA3DC /* GPHChannelTag.swift */; settings = {COMPILER_FLAGS = "-w -Xanalyzer -analyzer-disable-all-checks"; }; }; + 2305F3556264131853F108275C3F8398 /* GPHImages.swift in Sources */ = {isa = PBXBuildFile; fileRef = 15FEB397021DF9DA1D44F5ED25F7AA54 /* GPHImages.swift */; settings = {COMPILER_FLAGS = "-w -Xanalyzer -analyzer-disable-all-checks"; }; }; + 241A895884308A756FA317AB3C366DF2 /* Image.swift in Sources */ = {isa = PBXBuildFile; fileRef = 3406631BC27E485CA0CAB919D633E449 /* Image.swift */; settings = {COMPILER_FLAGS = "-w -Xanalyzer -analyzer-disable-all-checks"; }; }; + 2932B9857FE28906E32BB7B10ADE632F /* GiphyCore.swift in Sources */ = {isa = PBXBuildFile; fileRef = A82A66DE86B86B0CC39DEAFDC351D492 /* GiphyCore.swift */; settings = {COMPILER_FLAGS = "-w -Xanalyzer -analyzer-disable-all-checks"; }; }; + 3097C68621D9261149AFFD3DA1E9FCC9 /* GPHMappable.swift in Sources */ = {isa = PBXBuildFile; fileRef = EAF60DDA76FDCE8B9EE0E12C7AD394EA /* GPHMappable.swift */; settings = {COMPILER_FLAGS = "-w -Xanalyzer -analyzer-disable-all-checks"; }; }; + 31E097613F217BBF4E774D235917E165 /* TaskDelegate.swift in Sources */ = {isa = PBXBuildFile; fileRef = FFD2B0C81D077DF81DEA91A2404DB105 /* TaskDelegate.swift */; settings = {COMPILER_FLAGS = "-w -Xanalyzer -analyzer-disable-all-checks"; }; }; + 38578837A6DBD53EC97EA6C08B79D579 /* GiphyCoreSDK-dummy.m in Sources */ = {isa = PBXBuildFile; fileRef = 4F0145D2E49B8E026829CFC26CF572E5 /* GiphyCoreSDK-dummy.m */; }; + 39E46DB3A3EA5EB4427CC89A9FBE6127 /* DispatchQueue+Alamofire.swift in Sources */ = {isa = PBXBuildFile; fileRef = 6F4CBBC165C36FB5BAE525289D87E50D /* DispatchQueue+Alamofire.swift */; settings = {COMPILER_FLAGS = "-w -Xanalyzer -analyzer-disable-all-checks"; }; }; + 3E87E7CB5B4A10C78BB5AA0FEBFB94C8 /* AlamofireImage-umbrella.h in Headers */ = {isa = PBXBuildFile; fileRef = 2F9648232D9B2C593CCABCC284BE06F1 /* AlamofireImage-umbrella.h */; settings = {ATTRIBUTES = (Public, ); }; }; + 40E83A2C4472A974BA66E787E66ACB40 /* MultipartFormData.swift in Sources */ = {isa = PBXBuildFile; fileRef = 4B33519DFFB4D1AF8D5E4E584F738E18 /* MultipartFormData.swift */; settings = {COMPILER_FLAGS = "-w -Xanalyzer -analyzer-disable-all-checks"; }; }; + 41147D250A2E4D7B4B07F7494FB1B725 /* GPHUser.swift in Sources */ = {isa = PBXBuildFile; fileRef = 70CFC3B326918907B8B4C6A1FDB22422 /* GPHUser.swift */; settings = {COMPILER_FLAGS = "-w -Xanalyzer -analyzer-disable-all-checks"; }; }; + 43A7850130BCC891F79E2D0517991151 /* UIImage+AlamofireImage.swift in Sources */ = {isa = PBXBuildFile; fileRef = 100C2755C38AE9D0A80B0C9C08C961B4 /* UIImage+AlamofireImage.swift */; settings = {COMPILER_FLAGS = "-w -Xanalyzer -analyzer-disable-all-checks"; }; }; + 44221FD16515B202679641D0AB8E5138 /* GPHAsyncOperation.swift in Sources */ = {isa = PBXBuildFile; fileRef = 92AFA0121E2C67F2B3092C2FABF50251 /* GPHAsyncOperation.swift */; settings = {COMPILER_FLAGS = "-w -Xanalyzer -analyzer-disable-all-checks"; }; }; + 46CBF4D9DC9F49B0D2BEAD741A048109 /* ImageDownloader.swift in Sources */ = {isa = PBXBuildFile; fileRef = 901284EA4566119A1190C451B15D0114 /* ImageDownloader.swift */; settings = {COMPILER_FLAGS = "-w -Xanalyzer -analyzer-disable-all-checks"; }; }; + 497906EDDC273362B916A169A0995E8F /* GiphyCoreSDK-umbrella.h in Headers */ = {isa = PBXBuildFile; fileRef = 57E868A1DA1563CD85F0DB28549ADBF0 /* GiphyCoreSDK-umbrella.h */; settings = {ATTRIBUTES = (Public, ); }; }; + 4AD483A62D3A97A08D5D0A69055AF85B /* Foundation.framework in Frameworks */ = {isa = PBXBuildFile; fileRef = C23B3260E70D1B3A7B5E759A4A683949 /* Foundation.framework */; }; + 4BD4C27516C74875DEECF61FCBBAC52F /* GPHChannelResponse.swift in Sources */ = {isa = PBXBuildFile; fileRef = DBFFCBA3C5BA38D2AC2AEF3F70280C3D /* GPHChannelResponse.swift */; settings = {COMPILER_FLAGS = "-w -Xanalyzer -analyzer-disable-all-checks"; }; }; + 4D4A61EC172DB39FCF11C0829DF6913C /* ServerTrustPolicy.swift in Sources */ = {isa = PBXBuildFile; fileRef = E2F5C88C39CD282C00C9768B7C31A9B1 /* ServerTrustPolicy.swift */; settings = {COMPILER_FLAGS = "-w -Xanalyzer -analyzer-disable-all-checks"; }; }; + 4EC6096B54148453641B27E58ACF9BE6 /* GPHListChannelResponse.swift in Sources */ = {isa = PBXBuildFile; fileRef = CD0EBBA60A5BA3B262E23D028F46A269 /* GPHListChannelResponse.swift */; settings = {COMPILER_FLAGS = "-w -Xanalyzer -analyzer-disable-all-checks"; }; }; + 51E39EEE8A287772E96315B5E4848EB5 /* GPHAbstractClient.swift in Sources */ = {isa = PBXBuildFile; fileRef = 6152647EF58151FCDD07BB861E925824 /* GPHAbstractClient.swift */; settings = {COMPILER_FLAGS = "-w -Xanalyzer -analyzer-disable-all-checks"; }; }; + 52D24C0AECF15D853C9E0E940B945E8E /* GPHRequest.swift in Sources */ = {isa = PBXBuildFile; fileRef = C38CF643AEDD709EB251F8D376001C71 /* GPHRequest.swift */; settings = {COMPILER_FLAGS = "-w -Xanalyzer -analyzer-disable-all-checks"; }; }; + 53A3D10EF5AC98CB6421D5B94E0360EE /* UIButton+AlamofireImage.swift in Sources */ = {isa = PBXBuildFile; fileRef = 0753B7CAB3F6F9D3CA97DF0D893D170A /* UIButton+AlamofireImage.swift */; settings = {COMPILER_FLAGS = "-w -Xanalyzer -analyzer-disable-all-checks"; }; }; + 5FAE6243000CCAF381D57109484B1396 /* SessionDelegate.swift in Sources */ = {isa = PBXBuildFile; fileRef = 06FF53004FEBB70294AF674186ABBF19 /* SessionDelegate.swift */; settings = {COMPILER_FLAGS = "-w -Xanalyzer -analyzer-disable-all-checks"; }; }; + 6154423EBB7596B73FA383A41D20DF96 /* GPHMedia.swift in Sources */ = {isa = PBXBuildFile; fileRef = 24AFEC9BC6EBC59962CB6C066898B819 /* GPHMedia.swift */; settings = {COMPILER_FLAGS = "-w -Xanalyzer -analyzer-disable-all-checks"; }; }; + 66777B3D392D4AF8CBAE17A9C5D13C2F /* Timeline.swift in Sources */ = {isa = PBXBuildFile; fileRef = 0331384DA4F3BC61C45B567442294E78 /* Timeline.swift */; settings = {COMPILER_FLAGS = "-w -Xanalyzer -analyzer-disable-all-checks"; }; }; + 6E234A862ED158238D3CB582143270EF /* Alamofire.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5009A677968894603B01AF80304EE2F4 /* Alamofire.swift */; settings = {COMPILER_FLAGS = "-w -Xanalyzer -analyzer-disable-all-checks"; }; }; + 71C8993DD60E299326A97D5329C3CD71 /* Alamofire-dummy.m in Sources */ = {isa = PBXBuildFile; fileRef = DF85F30B1B42C6B67B8585CA6D9840A6 /* Alamofire-dummy.m */; }; + 72EDF21BFA7D0C52E40EAB4354F8AF44 /* Response.swift in Sources */ = {isa = PBXBuildFile; fileRef = E59E74ADE8E9CF7C995FC34CD482D297 /* Response.swift */; settings = {COMPILER_FLAGS = "-w -Xanalyzer -analyzer-disable-all-checks"; }; }; + 72F3A8CAF8EDC96305B12AD552A46DCF /* GPHListCategoryResponse.swift in Sources */ = {isa = PBXBuildFile; fileRef = A6442144200EAB263D260E228F99FC14 /* GPHListCategoryResponse.swift */; settings = {COMPILER_FLAGS = "-w -Xanalyzer -analyzer-disable-all-checks"; }; }; + 7A4334D14CDAF9ECD065EAF8F0A54431 /* ImageFilter.swift in Sources */ = {isa = PBXBuildFile; fileRef = 65C84F249DA25455F994ACA59E3EB9C6 /* ImageFilter.swift */; settings = {COMPILER_FLAGS = "-w -Xanalyzer -analyzer-disable-all-checks"; }; }; + 7BB64E803F9C456C16F4508ADC1ECD4B /* AlamofireImage-dummy.m in Sources */ = {isa = PBXBuildFile; fileRef = A99501F3526C5350C9D4C586898B1787 /* AlamofireImage-dummy.m */; }; + 7DDEEA91D0D552EA97C246C730D78824 /* AFError.swift in Sources */ = {isa = PBXBuildFile; fileRef = 791295320EA9D290EFE2E224DC31DA95 /* AFError.swift */; settings = {COMPILER_FLAGS = "-w -Xanalyzer -analyzer-disable-all-checks"; }; }; + 7E7B3F64A04D8D89CC15B0F527B006D0 /* GPHPagination.swift in Sources */ = {isa = PBXBuildFile; fileRef = C654196D2872FE700755069C2952F316 /* GPHPagination.swift */; settings = {COMPILER_FLAGS = "-w -Xanalyzer -analyzer-disable-all-checks"; }; }; + 7EC61770466C1FF57B5A2C82046284B7 /* Request.swift in Sources */ = {isa = PBXBuildFile; fileRef = 16243B7112792D10E80A24F584D40952 /* Request.swift */; settings = {COMPILER_FLAGS = "-w -Xanalyzer -analyzer-disable-all-checks"; }; }; + 86A8F0C9FEF4F13201D747D948493BA5 /* GPHBottleData.swift in Sources */ = {isa = PBXBuildFile; fileRef = 221466E73882FD9C0B7C0C7FC38BFC39 /* GPHBottleData.swift */; settings = {COMPILER_FLAGS = "-w -Xanalyzer -analyzer-disable-all-checks"; }; }; + 8C7F8BED5B207B5BD45457C6154AF2DB /* AFIError.swift in Sources */ = {isa = PBXBuildFile; fileRef = 7B6063FA1E9233A43EED066FF653D2B5 /* AFIError.swift */; settings = {COMPILER_FLAGS = "-w -Xanalyzer -analyzer-disable-all-checks"; }; }; + 8D82EFD461A2579EB956249A6B314ED7 /* Alamofire.framework in Frameworks */ = {isa = PBXBuildFile; fileRef = 706C7AFFE37BA158C3553250F4B5FAED /* Alamofire.framework */; }; + 918D55F16814247D5D0D74FC75B48FBE /* Validation.swift in Sources */ = {isa = PBXBuildFile; fileRef = 478D5B24BA1118704FBF99D099A1A4D8 /* Validation.swift */; settings = {COMPILER_FLAGS = "-w -Xanalyzer -analyzer-disable-all-checks"; }; }; + 9645F89261BA745E21BC1685D3F07BE7 /* Foundation.framework in Frameworks */ = {isa = PBXBuildFile; fileRef = C23B3260E70D1B3A7B5E759A4A683949 /* Foundation.framework */; }; + 9678682EA18EA975424ADE69DFCC6FDF /* GPHClient.swift in Sources */ = {isa = PBXBuildFile; fileRef = B9A6C0978BDF4573DB2CEFFF118BDDD1 /* GPHClient.swift */; settings = {COMPILER_FLAGS = "-w -Xanalyzer -analyzer-disable-all-checks"; }; }; + 98911DB23E65DBB0061B5B4E8B9C8163 /* GPHListMediaResponse.swift in Sources */ = {isa = PBXBuildFile; fileRef = FA00AA1DB8C2F7D109E1E92B60DA9AD1 /* GPHListMediaResponse.swift */; settings = {COMPILER_FLAGS = "-w -Xanalyzer -analyzer-disable-all-checks"; }; }; + A8941F45F19AFB646934F36B44C7EAE9 /* GPHError.swift in Sources */ = {isa = PBXBuildFile; fileRef = A9DF4A6D300C3BEF9913FBB6ECD4F69E /* GPHError.swift */; settings = {COMPILER_FLAGS = "-w -Xanalyzer -analyzer-disable-all-checks"; }; }; + ADB5CA583C364148A856FF7DDD5814DC /* UIImageView+AlamofireImage.swift in Sources */ = {isa = PBXBuildFile; fileRef = 7190265F5B67903AB3860D80CAE8C56E /* UIImageView+AlamofireImage.swift */; settings = {COMPILER_FLAGS = "-w -Xanalyzer -analyzer-disable-all-checks"; }; }; + B1E3FC26FEADE86BF9164BF5C387F32C /* ImageCache.swift in Sources */ = {isa = PBXBuildFile; fileRef = 4FC277600EB9FC8707C4E5BF61E61110 /* ImageCache.swift */; settings = {COMPILER_FLAGS = "-w -Xanalyzer -analyzer-disable-all-checks"; }; }; + B52C9F47F81C4E04299C652EEA2A02BB /* Pods-Giphy Search-umbrella.h in Headers */ = {isa = PBXBuildFile; fileRef = 456FBB9E70BECB6A3C8CECECCC21987B /* Pods-Giphy Search-umbrella.h */; settings = {ATTRIBUTES = (Public, ); }; }; + BFD8087821CC1D34D365791776FD3971 /* GPHTermSuggestion.swift in Sources */ = {isa = PBXBuildFile; fileRef = 6708018CA505C9A03A69D4D477D11CDD /* GPHTermSuggestion.swift */; settings = {COMPILER_FLAGS = "-w -Xanalyzer -analyzer-disable-all-checks"; }; }; + CAFDEC2BE2BD6C00E8E71FED4BBFF080 /* Result.swift in Sources */ = {isa = PBXBuildFile; fileRef = EA889D1A300A2C0144FD803BA4B1E081 /* Result.swift */; settings = {COMPILER_FLAGS = "-w -Xanalyzer -analyzer-disable-all-checks"; }; }; + D04270C0C61007A8BB065F92A680D6DE /* ResponseSerialization.swift in Sources */ = {isa = PBXBuildFile; fileRef = 2B93F497A4213A40D8DA5237FF4F388F /* ResponseSerialization.swift */; settings = {COMPILER_FLAGS = "-w -Xanalyzer -analyzer-disable-all-checks"; }; }; + D8EC5B74B9B5DC842F4179D19E6DE6D4 /* Foundation.framework in Frameworks */ = {isa = PBXBuildFile; fileRef = C23B3260E70D1B3A7B5E759A4A683949 /* Foundation.framework */; }; + DA3B50AF86C7F0AB8AA95BC126F0D070 /* SessionManager.swift in Sources */ = {isa = PBXBuildFile; fileRef = 12DDD051EA43B45D90D08F043DCE0F51 /* SessionManager.swift */; settings = {COMPILER_FLAGS = "-w -Xanalyzer -analyzer-disable-all-checks"; }; }; + DC8B1477A63E87749CEA0BB74B70150C /* GPHMeta.swift in Sources */ = {isa = PBXBuildFile; fileRef = 348E1CCFC78AE519181C0D1B69D037F8 /* GPHMeta.swift */; settings = {COMPILER_FLAGS = "-w -Xanalyzer -analyzer-disable-all-checks"; }; }; + DDDFD26405A572B0F50D29094E2E9BBA /* Request+AlamofireImage.swift in Sources */ = {isa = PBXBuildFile; fileRef = 57DCFF12DF7539AF6E2E36E97A87ECC6 /* Request+AlamofireImage.swift */; settings = {COMPILER_FLAGS = "-w -Xanalyzer -analyzer-disable-all-checks"; }; }; + E168E51972842469FAAD625F11D9D781 /* Notifications.swift in Sources */ = {isa = PBXBuildFile; fileRef = E7F2545F91340951789EAF9D6CEF8BBA /* Notifications.swift */; settings = {COMPILER_FLAGS = "-w -Xanalyzer -analyzer-disable-all-checks"; }; }; + EA338DB6E8FA1A61BDC85E7DD77CFA87 /* GPHTypes.swift in Sources */ = {isa = PBXBuildFile; fileRef = A9066EECF1F755E84DD5DB420AD4960E /* GPHTypes.swift */; settings = {COMPILER_FLAGS = "-w -Xanalyzer -analyzer-disable-all-checks"; }; }; + EF1461221681BCA12A4147900A704727 /* Alamofire-umbrella.h in Headers */ = {isa = PBXBuildFile; fileRef = B23CBAD42DE705027DC75341F4623CFD /* Alamofire-umbrella.h */; settings = {ATTRIBUTES = (Public, ); }; }; + F2BE6E75383179D394ED5EC55C660136 /* Pods-Giphy Search-dummy.m in Sources */ = {isa = PBXBuildFile; fileRef = 834E548745E7A8B10F719C6F12895855 /* Pods-Giphy Search-dummy.m */; }; + F45A1FBFDACD59E9A503A834ACBE0DC5 /* GPHFilterable.swift in Sources */ = {isa = PBXBuildFile; fileRef = E402AFD3FA125FB89D2C47530A17A309 /* GPHFilterable.swift */; settings = {COMPILER_FLAGS = "-w -Xanalyzer -analyzer-disable-all-checks"; }; }; + F6C27C4EBA7BBCB559013086C90D2D09 /* GPHNetworkReachability.swift in Sources */ = {isa = PBXBuildFile; fileRef = 27B15B7AE9D0678D079671D276BF9DD4 /* GPHNetworkReachability.swift */; settings = {COMPILER_FLAGS = "-w -Xanalyzer -analyzer-disable-all-checks"; }; }; + F8FF1D3214A72E73919D4B4EC6A3F5C2 /* GPHListTermSuggestionRespose.swift in Sources */ = {isa = PBXBuildFile; fileRef = 3137EA7CCC722FD8BE39A48797D511EF /* GPHListTermSuggestionRespose.swift */; settings = {COMPILER_FLAGS = "-w -Xanalyzer -analyzer-disable-all-checks"; }; }; + FA84EF6E647BA385B9C163DA1D5C255B /* GPHRequestConfig.swift in Sources */ = {isa = PBXBuildFile; fileRef = 00010D5C9EFDD00EA981CBC6CCCC5A0A /* GPHRequestConfig.swift */; settings = {COMPILER_FLAGS = "-w -Xanalyzer -analyzer-disable-all-checks"; }; }; + FD9ACD2FBE5243A91558B907BC425CF1 /* NetworkReachabilityManager.swift in Sources */ = {isa = PBXBuildFile; fileRef = 438E10EF8EA2CF3262BDAD8FE9996483 /* NetworkReachabilityManager.swift */; settings = {COMPILER_FLAGS = "-w -Xanalyzer -analyzer-disable-all-checks"; }; }; + FF2832D705F42B3D41189D922875987A /* Foundation.framework in Frameworks */ = {isa = PBXBuildFile; fileRef = C23B3260E70D1B3A7B5E759A4A683949 /* Foundation.framework */; }; +/* End PBXBuildFile section */ + +/* Begin PBXContainerItemProxy section */ + 2554943E4381B6131E33D4F9A9D344EF /* PBXContainerItemProxy */ = { + isa = PBXContainerItemProxy; + containerPortal = D41D8CD98F00B204E9800998ECF8427E /* Project object */; + proxyType = 1; + remoteGlobalIDString = E76458C58C9140B6A16D60547E68E80C; + remoteInfo = Alamofire; + }; + 412DD3039F2133834AFE21755F5FF409 /* PBXContainerItemProxy */ = { + isa = PBXContainerItemProxy; + containerPortal = D41D8CD98F00B204E9800998ECF8427E /* Project object */; + proxyType = 1; + remoteGlobalIDString = 5F4BA8B4D605B684ABBD2FB009E45151; + remoteInfo = AlamofireImage; + }; + 70BCB262EF988D1824EE4BC307664C62 /* PBXContainerItemProxy */ = { + isa = PBXContainerItemProxy; + containerPortal = D41D8CD98F00B204E9800998ECF8427E /* Project object */; + proxyType = 1; + remoteGlobalIDString = 19828C73A3124A7244CF9306F7A32C69; + remoteInfo = GiphyCoreSDK; + }; + 84DE9D25FE685AFA1B87C7FACEEDB4B4 /* PBXContainerItemProxy */ = { + isa = PBXContainerItemProxy; + containerPortal = D41D8CD98F00B204E9800998ECF8427E /* Project object */; + proxyType = 1; + remoteGlobalIDString = E76458C58C9140B6A16D60547E68E80C; + remoteInfo = Alamofire; + }; +/* End PBXContainerItemProxy section */ + +/* Begin PBXFileReference section */ + 00010D5C9EFDD00EA981CBC6CCCC5A0A /* GPHRequestConfig.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = GPHRequestConfig.swift; path = Sources/GPHRequestConfig.swift; sourceTree = ""; }; + 0331384DA4F3BC61C45B567442294E78 /* Timeline.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = Timeline.swift; path = Source/Timeline.swift; sourceTree = ""; }; + 06FF53004FEBB70294AF674186ABBF19 /* SessionDelegate.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = SessionDelegate.swift; path = Source/SessionDelegate.swift; sourceTree = ""; }; + 0753B7CAB3F6F9D3CA97DF0D893D170A /* UIButton+AlamofireImage.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = "UIButton+AlamofireImage.swift"; path = "Source/UIButton+AlamofireImage.swift"; sourceTree = ""; }; + 0858C9D0F89FAA89856A25A21E9E4375 /* Alamofire.framework */ = {isa = PBXFileReference; explicitFileType = wrapper.framework; includeInIndex = 0; name = Alamofire.framework; path = Alamofire.framework; sourceTree = BUILT_PRODUCTS_DIR; }; + 100C2755C38AE9D0A80B0C9C08C961B4 /* UIImage+AlamofireImage.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = "UIImage+AlamofireImage.swift"; path = "Source/UIImage+AlamofireImage.swift"; sourceTree = ""; }; + 10820F9243CB05D1856DD0F8CEACA3DC /* GPHChannelTag.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = GPHChannelTag.swift; path = Sources/GPHChannelTag.swift; sourceTree = ""; }; + 10B7B70F44D9E46F276EAD3CBFBDDA1B /* GiphyCoreSDK.framework */ = {isa = PBXFileReference; explicitFileType = wrapper.framework; includeInIndex = 0; name = GiphyCoreSDK.framework; path = GiphyCoreSDK.framework; sourceTree = BUILT_PRODUCTS_DIR; }; + 12DDD051EA43B45D90D08F043DCE0F51 /* SessionManager.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = SessionManager.swift; path = Source/SessionManager.swift; sourceTree = ""; }; + 15FEB397021DF9DA1D44F5ED25F7AA54 /* GPHImages.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = GPHImages.swift; path = Sources/GPHImages.swift; sourceTree = ""; }; + 16243B7112792D10E80A24F584D40952 /* Request.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = Request.swift; path = Source/Request.swift; sourceTree = ""; }; + 1C6F8FC7F8087C8CA1FE23763A0FB4DF /* GPHImage.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = GPHImage.swift; path = Sources/GPHImage.swift; sourceTree = ""; }; + 1F12B7C2DE164D2FB737B8D44D02B79D /* Pods-Giphy Search-frameworks.sh */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = text.script.sh; path = "Pods-Giphy Search-frameworks.sh"; sourceTree = ""; }; + 221466E73882FD9C0B7C0C7FC38BFC39 /* GPHBottleData.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = GPHBottleData.swift; path = Sources/GPHBottleData.swift; sourceTree = ""; }; + 24AFEC9BC6EBC59962CB6C066898B819 /* GPHMedia.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = GPHMedia.swift; path = Sources/GPHMedia.swift; sourceTree = ""; }; + 27B15B7AE9D0678D079671D276BF9DD4 /* GPHNetworkReachability.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = GPHNetworkReachability.swift; path = Sources/GPHNetworkReachability.swift; sourceTree = ""; }; + 2B93F497A4213A40D8DA5237FF4F388F /* ResponseSerialization.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = ResponseSerialization.swift; path = Source/ResponseSerialization.swift; sourceTree = ""; }; + 2F9648232D9B2C593CCABCC284BE06F1 /* AlamofireImage-umbrella.h */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.h; path = "AlamofireImage-umbrella.h"; sourceTree = ""; }; + 30035D38303ECE4DC18471A8E5E3CF0E /* AlamofireImage-prefix.pch */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.h; path = "AlamofireImage-prefix.pch"; sourceTree = ""; }; + 3018485A1063717DEA8D74B7780B2C80 /* GiphyCoreSDK.modulemap */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.module; path = GiphyCoreSDK.modulemap; sourceTree = ""; }; + 3137EA7CCC722FD8BE39A48797D511EF /* GPHListTermSuggestionRespose.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = GPHListTermSuggestionRespose.swift; path = Sources/GPHListTermSuggestionRespose.swift; sourceTree = ""; }; + 31E8026AE06999DD1A0697859A6DD2AE /* AlamofireImage.framework */ = {isa = PBXFileReference; explicitFileType = wrapper.framework; includeInIndex = 0; name = AlamofireImage.framework; path = AlamofireImage.framework; sourceTree = BUILT_PRODUCTS_DIR; }; + 3406631BC27E485CA0CAB919D633E449 /* Image.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = Image.swift; path = Source/Image.swift; sourceTree = ""; }; + 348E1CCFC78AE519181C0D1B69D037F8 /* GPHMeta.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = GPHMeta.swift; path = Sources/GPHMeta.swift; sourceTree = ""; }; + 3774AA2DBA6D44FA0201CABB6B6C2058 /* Pods_Giphy_Search.framework */ = {isa = PBXFileReference; explicitFileType = wrapper.framework; includeInIndex = 0; name = Pods_Giphy_Search.framework; path = "Pods-Giphy Search.framework"; sourceTree = BUILT_PRODUCTS_DIR; }; + 3A189F0858B646F948EF6E7DF7EC8281 /* Pods-Giphy Search-acknowledgements.plist */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = text.plist.xml; path = "Pods-Giphy Search-acknowledgements.plist"; sourceTree = ""; }; + 3B8057DE472B446B51AB9D280B4B3AE2 /* Pods-Giphy Search.release.xcconfig */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = text.xcconfig; path = "Pods-Giphy Search.release.xcconfig"; sourceTree = ""; }; + 438E10EF8EA2CF3262BDAD8FE9996483 /* NetworkReachabilityManager.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = NetworkReachabilityManager.swift; path = Source/NetworkReachabilityManager.swift; sourceTree = ""; }; + 456FBB9E70BECB6A3C8CECECCC21987B /* Pods-Giphy Search-umbrella.h */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.h; path = "Pods-Giphy Search-umbrella.h"; sourceTree = ""; }; + 478D5B24BA1118704FBF99D099A1A4D8 /* Validation.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = Validation.swift; path = Source/Validation.swift; sourceTree = ""; }; + 48FBA1BB6777A216F06F1BFDA7F5664A /* Alamofire.xcconfig */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = text.xcconfig; path = Alamofire.xcconfig; sourceTree = ""; }; + 4B33519DFFB4D1AF8D5E4E584F738E18 /* MultipartFormData.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = MultipartFormData.swift; path = Source/MultipartFormData.swift; sourceTree = ""; }; + 4B73C18659566CE05CFD1FC0A887D201 /* Pods-Giphy Search-resources.sh */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = text.script.sh; path = "Pods-Giphy Search-resources.sh"; sourceTree = ""; }; + 4F0145D2E49B8E026829CFC26CF572E5 /* GiphyCoreSDK-dummy.m */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.objc; path = "GiphyCoreSDK-dummy.m"; sourceTree = ""; }; + 4FC277600EB9FC8707C4E5BF61E61110 /* ImageCache.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = ImageCache.swift; path = Source/ImageCache.swift; sourceTree = ""; }; + 5009A677968894603B01AF80304EE2F4 /* Alamofire.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = Alamofire.swift; path = Source/Alamofire.swift; sourceTree = ""; }; + 524B80A293C2CF7413D7B16B99E41F51 /* GiphyCoreSDK-prefix.pch */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.h; path = "GiphyCoreSDK-prefix.pch"; sourceTree = ""; }; + 57DCFF12DF7539AF6E2E36E97A87ECC6 /* Request+AlamofireImage.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = "Request+AlamofireImage.swift"; path = "Source/Request+AlamofireImage.swift"; sourceTree = ""; }; + 57E868A1DA1563CD85F0DB28549ADBF0 /* GiphyCoreSDK-umbrella.h */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.h; path = "GiphyCoreSDK-umbrella.h"; sourceTree = ""; }; + 5EADAC7D02CC67FC8A243B4116F467E1 /* Pods-Giphy Search.modulemap */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.module; path = "Pods-Giphy Search.modulemap"; sourceTree = ""; }; + 6152647EF58151FCDD07BB861E925824 /* GPHAbstractClient.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = GPHAbstractClient.swift; path = Sources/GPHAbstractClient.swift; sourceTree = ""; }; + 65C84F249DA25455F994ACA59E3EB9C6 /* ImageFilter.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = ImageFilter.swift; path = Source/ImageFilter.swift; sourceTree = ""; }; + 6708018CA505C9A03A69D4D477D11CDD /* GPHTermSuggestion.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = GPHTermSuggestion.swift; path = Sources/GPHTermSuggestion.swift; sourceTree = ""; }; + 6F4CBBC165C36FB5BAE525289D87E50D /* DispatchQueue+Alamofire.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = "DispatchQueue+Alamofire.swift"; path = "Source/DispatchQueue+Alamofire.swift"; sourceTree = ""; }; + 706C7AFFE37BA158C3553250F4B5FAED /* Alamofire.framework */ = {isa = PBXFileReference; explicitFileType = wrapper.framework; includeInIndex = 0; path = Alamofire.framework; sourceTree = BUILT_PRODUCTS_DIR; }; + 70CFC3B326918907B8B4C6A1FDB22422 /* GPHUser.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = GPHUser.swift; path = Sources/GPHUser.swift; sourceTree = ""; }; + 7190265F5B67903AB3860D80CAE8C56E /* UIImageView+AlamofireImage.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = "UIImageView+AlamofireImage.swift"; path = "Source/UIImageView+AlamofireImage.swift"; sourceTree = ""; }; + 791295320EA9D290EFE2E224DC31DA95 /* AFError.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = AFError.swift; path = Source/AFError.swift; sourceTree = ""; }; + 7B6063FA1E9233A43EED066FF653D2B5 /* AFIError.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = AFIError.swift; path = Source/AFIError.swift; sourceTree = ""; }; + 834E548745E7A8B10F719C6F12895855 /* Pods-Giphy Search-dummy.m */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.objc; path = "Pods-Giphy Search-dummy.m"; sourceTree = ""; }; + 864852583A21997FED7E8A1A5CE75410 /* Info.plist */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = text.plist.xml; path = Info.plist; sourceTree = ""; }; + 8DB0ED45006BFAA11E4097BABB265BD0 /* Alamofire-prefix.pch */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.h; path = "Alamofire-prefix.pch"; sourceTree = ""; }; + 901284EA4566119A1190C451B15D0114 /* ImageDownloader.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = ImageDownloader.swift; path = Source/ImageDownloader.swift; sourceTree = ""; }; + 92A0DB9E48B5358B3ADDDE05F7BB9CAA /* GPHResponse.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = GPHResponse.swift; path = Sources/GPHResponse.swift; sourceTree = ""; }; + 92AFA0121E2C67F2B3092C2FABF50251 /* GPHAsyncOperation.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = GPHAsyncOperation.swift; path = Sources/GPHAsyncOperation.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; }; + 93D7F1C61D175EC407AAF2C6D3C69B55 /* GPHCategory.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = GPHCategory.swift; path = Sources/GPHCategory.swift; sourceTree = ""; }; + 9B980313ECD2579BD6DD295EF5A7B852 /* Alamofire.modulemap */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.module; path = Alamofire.modulemap; sourceTree = ""; }; + 9EB58D075E5B45F2A60CA2D9D6EA185A /* Pods-Giphy Search-acknowledgements.markdown */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = text; path = "Pods-Giphy Search-acknowledgements.markdown"; sourceTree = ""; }; + A60C6915BE355DB410E9B2B3309752A0 /* Info.plist */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = text.plist.xml; path = Info.plist; sourceTree = ""; }; + A6442144200EAB263D260E228F99FC14 /* GPHListCategoryResponse.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = GPHListCategoryResponse.swift; path = Sources/GPHListCategoryResponse.swift; sourceTree = ""; }; + A82A66DE86B86B0CC39DEAFDC351D492 /* GiphyCore.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = GiphyCore.swift; path = Sources/GiphyCore.swift; sourceTree = ""; }; + A9066EECF1F755E84DD5DB420AD4960E /* GPHTypes.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = GPHTypes.swift; path = Sources/GPHTypes.swift; sourceTree = ""; }; + A99501F3526C5350C9D4C586898B1787 /* AlamofireImage-dummy.m */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.objc; path = "AlamofireImage-dummy.m"; sourceTree = ""; }; + A9DF4A6D300C3BEF9913FBB6ECD4F69E /* GPHError.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = GPHError.swift; path = Sources/GPHError.swift; sourceTree = ""; }; + B23CBAD42DE705027DC75341F4623CFD /* Alamofire-umbrella.h */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.h; path = "Alamofire-umbrella.h"; sourceTree = ""; }; + B9A6C0978BDF4573DB2CEFFF118BDDD1 /* GPHClient.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = GPHClient.swift; path = Sources/GPHClient.swift; sourceTree = ""; }; + C23B3260E70D1B3A7B5E759A4A683949 /* Foundation.framework */ = {isa = PBXFileReference; lastKnownFileType = wrapper.framework; name = Foundation.framework; path = Platforms/iPhoneOS.platform/Developer/SDKs/iPhoneOS11.3.sdk/System/Library/Frameworks/Foundation.framework; sourceTree = DEVELOPER_DIR; }; + C38CF643AEDD709EB251F8D376001C71 /* GPHRequest.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = GPHRequest.swift; path = Sources/GPHRequest.swift; sourceTree = ""; }; + C654196D2872FE700755069C2952F316 /* GPHPagination.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = GPHPagination.swift; path = Sources/GPHPagination.swift; sourceTree = ""; }; + C995EE8354CA18A106E2CB9A3580A880 /* GPHChannel.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = GPHChannel.swift; path = Sources/GPHChannel.swift; sourceTree = ""; }; + CADC1CD570310F38D608A9D5603A0E84 /* Pods-Giphy Search.debug.xcconfig */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = text.xcconfig; path = "Pods-Giphy Search.debug.xcconfig"; sourceTree = ""; }; + CD0EBBA60A5BA3B262E23D028F46A269 /* GPHListChannelResponse.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = GPHListChannelResponse.swift; path = Sources/GPHListChannelResponse.swift; sourceTree = ""; }; + CF32C4B7557300ECD2B69C7D2DBD0B81 /* ParameterEncoding.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = ParameterEncoding.swift; path = Source/ParameterEncoding.swift; sourceTree = ""; }; + D0EA22EEC4BB3E25403C9D2956D242C8 /* AlamofireImage.modulemap */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.module; path = AlamofireImage.modulemap; sourceTree = ""; }; + DBFFCBA3C5BA38D2AC2AEF3F70280C3D /* GPHChannelResponse.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = GPHChannelResponse.swift; path = Sources/GPHChannelResponse.swift; sourceTree = ""; }; + DF85F30B1B42C6B67B8585CA6D9840A6 /* Alamofire-dummy.m */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.objc; path = "Alamofire-dummy.m"; sourceTree = ""; }; + E2F5C88C39CD282C00C9768B7C31A9B1 /* ServerTrustPolicy.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = ServerTrustPolicy.swift; path = Source/ServerTrustPolicy.swift; sourceTree = ""; }; + E402AFD3FA125FB89D2C47530A17A309 /* GPHFilterable.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = GPHFilterable.swift; path = Sources/GPHFilterable.swift; sourceTree = ""; }; + E59E74ADE8E9CF7C995FC34CD482D297 /* Response.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = Response.swift; path = Source/Response.swift; sourceTree = ""; }; + E71089437F91AA345B407F58E771BCF7 /* GPHMediaResponse.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = GPHMediaResponse.swift; path = Sources/GPHMediaResponse.swift; sourceTree = ""; }; + E7F2545F91340951789EAF9D6CEF8BBA /* Notifications.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = Notifications.swift; path = Source/Notifications.swift; sourceTree = ""; }; + EA889D1A300A2C0144FD803BA4B1E081 /* Result.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = Result.swift; path = Source/Result.swift; sourceTree = ""; }; + EAF60DDA76FDCE8B9EE0E12C7AD394EA /* GPHMappable.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = GPHMappable.swift; path = Sources/GPHMappable.swift; sourceTree = ""; }; + EC7FE4000F844EFBED4C4E96E8AD82E3 /* GiphyCoreSDK.xcconfig */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = text.xcconfig; path = GiphyCoreSDK.xcconfig; sourceTree = ""; }; + F4DB4B6F552190A7AD38F3A894D72AB8 /* Info.plist */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = text.plist.xml; path = Info.plist; sourceTree = ""; }; + FA00AA1DB8C2F7D109E1E92B60DA9AD1 /* GPHListMediaResponse.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = GPHListMediaResponse.swift; path = Sources/GPHListMediaResponse.swift; sourceTree = ""; }; + FD403887FA1D4993B227F2102540CA5C /* Info.plist */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = text.plist.xml; path = Info.plist; sourceTree = ""; }; + FDE4A021CB10C1C74833AE7D71CD301E /* AlamofireImage.xcconfig */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = text.xcconfig; path = AlamofireImage.xcconfig; sourceTree = ""; }; + FFD2B0C81D077DF81DEA91A2404DB105 /* TaskDelegate.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = TaskDelegate.swift; path = Source/TaskDelegate.swift; sourceTree = ""; }; +/* End PBXFileReference section */ + +/* Begin PBXFrameworksBuildPhase section */ + 2C1047F6C4EE52C8AA60B562CA27EF88 /* Frameworks */ = { + isa = PBXFrameworksBuildPhase; + buildActionMask = 2147483647; + files = ( + 8D82EFD461A2579EB956249A6B314ED7 /* Alamofire.framework in Frameworks */, + 9645F89261BA745E21BC1685D3F07BE7 /* Foundation.framework in Frameworks */, + ); + runOnlyForDeploymentPostprocessing = 0; + }; + 612DB893128CAE04AFD8A0AF6B4313AB /* Frameworks */ = { + isa = PBXFrameworksBuildPhase; + buildActionMask = 2147483647; + files = ( + 4AD483A62D3A97A08D5D0A69055AF85B /* Foundation.framework in Frameworks */, + ); + runOnlyForDeploymentPostprocessing = 0; + }; + 6E8AF668A2161F7D6F680F721DB65D2D /* Frameworks */ = { + isa = PBXFrameworksBuildPhase; + buildActionMask = 2147483647; + files = ( + D8EC5B74B9B5DC842F4179D19E6DE6D4 /* Foundation.framework in Frameworks */, + ); + runOnlyForDeploymentPostprocessing = 0; + }; + A23E88328DD7B1FF41BEF56BC58DC331 /* Frameworks */ = { + isa = PBXFrameworksBuildPhase; + buildActionMask = 2147483647; + files = ( + FF2832D705F42B3D41189D922875987A /* Foundation.framework in Frameworks */, + ); + runOnlyForDeploymentPostprocessing = 0; + }; +/* End PBXFrameworksBuildPhase section */ + +/* Begin PBXGroup section */ + 06802D9C8F3B929214120E513AB239B1 /* Support Files */ = { + isa = PBXGroup; + children = ( + 9B980313ECD2579BD6DD295EF5A7B852 /* Alamofire.modulemap */, + 48FBA1BB6777A216F06F1BFDA7F5664A /* Alamofire.xcconfig */, + DF85F30B1B42C6B67B8585CA6D9840A6 /* Alamofire-dummy.m */, + 8DB0ED45006BFAA11E4097BABB265BD0 /* Alamofire-prefix.pch */, + B23CBAD42DE705027DC75341F4623CFD /* Alamofire-umbrella.h */, + 864852583A21997FED7E8A1A5CE75410 /* Info.plist */, + ); + name = "Support Files"; + path = "../Target Support Files/Alamofire"; + sourceTree = ""; + }; + 110D4099F9AC925206FA105D06CD459A /* AlamofireImage */ = { + isa = PBXGroup; + children = ( + 7B6063FA1E9233A43EED066FF653D2B5 /* AFIError.swift */, + 3406631BC27E485CA0CAB919D633E449 /* Image.swift */, + 4FC277600EB9FC8707C4E5BF61E61110 /* ImageCache.swift */, + 901284EA4566119A1190C451B15D0114 /* ImageDownloader.swift */, + 65C84F249DA25455F994ACA59E3EB9C6 /* ImageFilter.swift */, + 57DCFF12DF7539AF6E2E36E97A87ECC6 /* Request+AlamofireImage.swift */, + 0753B7CAB3F6F9D3CA97DF0D893D170A /* UIButton+AlamofireImage.swift */, + 100C2755C38AE9D0A80B0C9C08C961B4 /* UIImage+AlamofireImage.swift */, + 7190265F5B67903AB3860D80CAE8C56E /* UIImageView+AlamofireImage.swift */, + 669F1D5359A8DA417E6D5503221718D8 /* Support Files */, + ); + name = AlamofireImage; + path = AlamofireImage; + sourceTree = ""; + }; + 1D854E931A9FCAE5B5BC836BC122B940 /* Targets Support Files */ = { + isa = PBXGroup; + children = ( + D8CC61E1C114BA612BF5B2A4A793912D /* Pods-Giphy Search */, + ); + name = "Targets Support Files"; + sourceTree = ""; + }; + 26D621E1E8E6F8C5E7E358FD052BE7A5 /* Pods */ = { + isa = PBXGroup; + children = ( + BA3831C1C70C3101B2E09FD3550C4666 /* Alamofire */, + 110D4099F9AC925206FA105D06CD459A /* AlamofireImage */, + 955C32B4394C3FACE27DA8DA29B8F219 /* GiphyCoreSDK */, + ); + name = Pods; + sourceTree = ""; + }; + 2E183E668396F3AEC638B45B7883E58B /* Support Files */ = { + isa = PBXGroup; + children = ( + 3018485A1063717DEA8D74B7780B2C80 /* GiphyCoreSDK.modulemap */, + EC7FE4000F844EFBED4C4E96E8AD82E3 /* GiphyCoreSDK.xcconfig */, + 4F0145D2E49B8E026829CFC26CF572E5 /* GiphyCoreSDK-dummy.m */, + 524B80A293C2CF7413D7B16B99E41F51 /* GiphyCoreSDK-prefix.pch */, + 57E868A1DA1563CD85F0DB28549ADBF0 /* GiphyCoreSDK-umbrella.h */, + F4DB4B6F552190A7AD38F3A894D72AB8 /* Info.plist */, + ); + name = "Support Files"; + path = "../Target Support Files/GiphyCoreSDK"; + sourceTree = ""; + }; + 4A0D5893AF81DC8BB5022505D9454E21 /* iOS */ = { + isa = PBXGroup; + children = ( + C23B3260E70D1B3A7B5E759A4A683949 /* Foundation.framework */, + ); + name = iOS; + sourceTree = ""; + }; + 59B91F212518421F271EBA85D5530651 /* Frameworks */ = { + isa = PBXGroup; + children = ( + 706C7AFFE37BA158C3553250F4B5FAED /* Alamofire.framework */, + 4A0D5893AF81DC8BB5022505D9454E21 /* iOS */, + ); + name = Frameworks; + sourceTree = ""; + }; + 669F1D5359A8DA417E6D5503221718D8 /* Support Files */ = { + isa = PBXGroup; + children = ( + D0EA22EEC4BB3E25403C9D2956D242C8 /* AlamofireImage.modulemap */, + FDE4A021CB10C1C74833AE7D71CD301E /* AlamofireImage.xcconfig */, + A99501F3526C5350C9D4C586898B1787 /* AlamofireImage-dummy.m */, + 30035D38303ECE4DC18471A8E5E3CF0E /* AlamofireImage-prefix.pch */, + 2F9648232D9B2C593CCABCC284BE06F1 /* AlamofireImage-umbrella.h */, + A60C6915BE355DB410E9B2B3309752A0 /* Info.plist */, + ); + name = "Support Files"; + path = "../Target Support Files/AlamofireImage"; + sourceTree = ""; + }; + 7DB346D0F39D3F0E887471402A8071AB = { + isa = PBXGroup; + children = ( + 93A4A3777CF96A4AAC1D13BA6DCCEA73 /* Podfile */, + 59B91F212518421F271EBA85D5530651 /* Frameworks */, + 26D621E1E8E6F8C5E7E358FD052BE7A5 /* Pods */, + F45D28A5EF732FF63827CA48E7D74931 /* Products */, + 1D854E931A9FCAE5B5BC836BC122B940 /* Targets Support Files */, + ); + sourceTree = ""; + }; + 955C32B4394C3FACE27DA8DA29B8F219 /* GiphyCoreSDK */ = { + isa = PBXGroup; + children = ( + A82A66DE86B86B0CC39DEAFDC351D492 /* GiphyCore.swift */, + 6152647EF58151FCDD07BB861E925824 /* GPHAbstractClient.swift */, + 92AFA0121E2C67F2B3092C2FABF50251 /* GPHAsyncOperation.swift */, + 221466E73882FD9C0B7C0C7FC38BFC39 /* GPHBottleData.swift */, + 93D7F1C61D175EC407AAF2C6D3C69B55 /* GPHCategory.swift */, + C995EE8354CA18A106E2CB9A3580A880 /* GPHChannel.swift */, + DBFFCBA3C5BA38D2AC2AEF3F70280C3D /* GPHChannelResponse.swift */, + 10820F9243CB05D1856DD0F8CEACA3DC /* GPHChannelTag.swift */, + B9A6C0978BDF4573DB2CEFFF118BDDD1 /* GPHClient.swift */, + A9DF4A6D300C3BEF9913FBB6ECD4F69E /* GPHError.swift */, + E402AFD3FA125FB89D2C47530A17A309 /* GPHFilterable.swift */, + 1C6F8FC7F8087C8CA1FE23763A0FB4DF /* GPHImage.swift */, + 15FEB397021DF9DA1D44F5ED25F7AA54 /* GPHImages.swift */, + A6442144200EAB263D260E228F99FC14 /* GPHListCategoryResponse.swift */, + CD0EBBA60A5BA3B262E23D028F46A269 /* GPHListChannelResponse.swift */, + FA00AA1DB8C2F7D109E1E92B60DA9AD1 /* GPHListMediaResponse.swift */, + 3137EA7CCC722FD8BE39A48797D511EF /* GPHListTermSuggestionRespose.swift */, + EAF60DDA76FDCE8B9EE0E12C7AD394EA /* GPHMappable.swift */, + 24AFEC9BC6EBC59962CB6C066898B819 /* GPHMedia.swift */, + E71089437F91AA345B407F58E771BCF7 /* GPHMediaResponse.swift */, + 348E1CCFC78AE519181C0D1B69D037F8 /* GPHMeta.swift */, + 27B15B7AE9D0678D079671D276BF9DD4 /* GPHNetworkReachability.swift */, + C654196D2872FE700755069C2952F316 /* GPHPagination.swift */, + C38CF643AEDD709EB251F8D376001C71 /* GPHRequest.swift */, + 00010D5C9EFDD00EA981CBC6CCCC5A0A /* GPHRequestConfig.swift */, + 92A0DB9E48B5358B3ADDDE05F7BB9CAA /* GPHResponse.swift */, + 6708018CA505C9A03A69D4D477D11CDD /* GPHTermSuggestion.swift */, + A9066EECF1F755E84DD5DB420AD4960E /* GPHTypes.swift */, + 70CFC3B326918907B8B4C6A1FDB22422 /* GPHUser.swift */, + 2E183E668396F3AEC638B45B7883E58B /* Support Files */, + ); + name = GiphyCoreSDK; + path = GiphyCoreSDK; + sourceTree = ""; + }; + BA3831C1C70C3101B2E09FD3550C4666 /* Alamofire */ = { + isa = PBXGroup; + children = ( + 791295320EA9D290EFE2E224DC31DA95 /* AFError.swift */, + 5009A677968894603B01AF80304EE2F4 /* Alamofire.swift */, + 6F4CBBC165C36FB5BAE525289D87E50D /* DispatchQueue+Alamofire.swift */, + 4B33519DFFB4D1AF8D5E4E584F738E18 /* MultipartFormData.swift */, + 438E10EF8EA2CF3262BDAD8FE9996483 /* NetworkReachabilityManager.swift */, + E7F2545F91340951789EAF9D6CEF8BBA /* Notifications.swift */, + CF32C4B7557300ECD2B69C7D2DBD0B81 /* ParameterEncoding.swift */, + 16243B7112792D10E80A24F584D40952 /* Request.swift */, + E59E74ADE8E9CF7C995FC34CD482D297 /* Response.swift */, + 2B93F497A4213A40D8DA5237FF4F388F /* ResponseSerialization.swift */, + EA889D1A300A2C0144FD803BA4B1E081 /* Result.swift */, + E2F5C88C39CD282C00C9768B7C31A9B1 /* ServerTrustPolicy.swift */, + 06FF53004FEBB70294AF674186ABBF19 /* SessionDelegate.swift */, + 12DDD051EA43B45D90D08F043DCE0F51 /* SessionManager.swift */, + FFD2B0C81D077DF81DEA91A2404DB105 /* TaskDelegate.swift */, + 0331384DA4F3BC61C45B567442294E78 /* Timeline.swift */, + 478D5B24BA1118704FBF99D099A1A4D8 /* Validation.swift */, + 06802D9C8F3B929214120E513AB239B1 /* Support Files */, + ); + name = Alamofire; + path = Alamofire; + sourceTree = ""; + }; + D8CC61E1C114BA612BF5B2A4A793912D /* Pods-Giphy Search */ = { + isa = PBXGroup; + children = ( + FD403887FA1D4993B227F2102540CA5C /* Info.plist */, + 5EADAC7D02CC67FC8A243B4116F467E1 /* Pods-Giphy Search.modulemap */, + 9EB58D075E5B45F2A60CA2D9D6EA185A /* Pods-Giphy Search-acknowledgements.markdown */, + 3A189F0858B646F948EF6E7DF7EC8281 /* Pods-Giphy Search-acknowledgements.plist */, + 834E548745E7A8B10F719C6F12895855 /* Pods-Giphy Search-dummy.m */, + 1F12B7C2DE164D2FB737B8D44D02B79D /* Pods-Giphy Search-frameworks.sh */, + 4B73C18659566CE05CFD1FC0A887D201 /* Pods-Giphy Search-resources.sh */, + 456FBB9E70BECB6A3C8CECECCC21987B /* Pods-Giphy Search-umbrella.h */, + CADC1CD570310F38D608A9D5603A0E84 /* Pods-Giphy Search.debug.xcconfig */, + 3B8057DE472B446B51AB9D280B4B3AE2 /* Pods-Giphy Search.release.xcconfig */, + ); + name = "Pods-Giphy Search"; + path = "Target Support Files/Pods-Giphy Search"; + sourceTree = ""; + }; + F45D28A5EF732FF63827CA48E7D74931 /* Products */ = { + isa = PBXGroup; + children = ( + 0858C9D0F89FAA89856A25A21E9E4375 /* Alamofire.framework */, + 31E8026AE06999DD1A0697859A6DD2AE /* AlamofireImage.framework */, + 10B7B70F44D9E46F276EAD3CBFBDDA1B /* GiphyCoreSDK.framework */, + 3774AA2DBA6D44FA0201CABB6B6C2058 /* Pods_Giphy_Search.framework */, + ); + name = Products; + sourceTree = ""; + }; +/* End PBXGroup section */ + +/* Begin PBXHeadersBuildPhase section */ + 85017B56D813746CFDC156B9E9D4A837 /* Headers */ = { + isa = PBXHeadersBuildPhase; + buildActionMask = 2147483647; + files = ( + B52C9F47F81C4E04299C652EEA2A02BB /* Pods-Giphy Search-umbrella.h in Headers */, + ); + runOnlyForDeploymentPostprocessing = 0; + }; + A6A607506FEAAC7C41268D3E5CF4E5FE /* Headers */ = { + isa = PBXHeadersBuildPhase; + buildActionMask = 2147483647; + files = ( + EF1461221681BCA12A4147900A704727 /* Alamofire-umbrella.h in Headers */, + ); + runOnlyForDeploymentPostprocessing = 0; + }; + CC4BD7DC3B6C66E0D660E5AE137D5EFA /* Headers */ = { + isa = PBXHeadersBuildPhase; + buildActionMask = 2147483647; + files = ( + 3E87E7CB5B4A10C78BB5AA0FEBFB94C8 /* AlamofireImage-umbrella.h in Headers */, + ); + runOnlyForDeploymentPostprocessing = 0; + }; + F819C302414FC7243BAD6314135271BC /* Headers */ = { + isa = PBXHeadersBuildPhase; + buildActionMask = 2147483647; + files = ( + 497906EDDC273362B916A169A0995E8F /* GiphyCoreSDK-umbrella.h in Headers */, + ); + runOnlyForDeploymentPostprocessing = 0; + }; +/* End PBXHeadersBuildPhase section */ + +/* Begin PBXNativeTarget section */ + 19828C73A3124A7244CF9306F7A32C69 /* GiphyCoreSDK */ = { + isa = PBXNativeTarget; + buildConfigurationList = 345CDDB6E42B3ED1847D232C452F4F1C /* Build configuration list for PBXNativeTarget "GiphyCoreSDK" */; + buildPhases = ( + F819C302414FC7243BAD6314135271BC /* Headers */, + 0851AEF3EB76A525C75FC0310FD806E3 /* Sources */, + A23E88328DD7B1FF41BEF56BC58DC331 /* Frameworks */, + BACAB294727FE33F34CEF9C3366C0EB7 /* Resources */, + ); + buildRules = ( + ); + dependencies = ( + ); + name = GiphyCoreSDK; + productName = GiphyCoreSDK; + productReference = 10B7B70F44D9E46F276EAD3CBFBDDA1B /* GiphyCoreSDK.framework */; + productType = "com.apple.product-type.framework"; + }; + 5D2BD95E6D2F1FF6B446A1D392FD5588 /* Pods-Giphy Search */ = { + isa = PBXNativeTarget; + buildConfigurationList = 166D00443DEEE6DD3F026CFBF8A8E523 /* Build configuration list for PBXNativeTarget "Pods-Giphy Search" */; + buildPhases = ( + 85017B56D813746CFDC156B9E9D4A837 /* Headers */, + 5BFCE4E8068FDEEA7C47E5A2E88E7433 /* Sources */, + 612DB893128CAE04AFD8A0AF6B4313AB /* Frameworks */, + E1BF336D20DC75C2DDD2A9AB1433984F /* Resources */, + ); + buildRules = ( + ); + dependencies = ( + D2B2450D4038F5A660FF97642BA6FD3E /* PBXTargetDependency */, + 5DA60125C0888E2A42C0F87875AF44CA /* PBXTargetDependency */, + 11EA5A72559EAC6BAF8675972A831CE6 /* PBXTargetDependency */, + ); + name = "Pods-Giphy Search"; + productName = "Pods-Giphy Search"; + productReference = 3774AA2DBA6D44FA0201CABB6B6C2058 /* Pods_Giphy_Search.framework */; + productType = "com.apple.product-type.framework"; + }; + 5F4BA8B4D605B684ABBD2FB009E45151 /* AlamofireImage */ = { + isa = PBXNativeTarget; + buildConfigurationList = FECA52B188EB8A276F28B478D92AF353 /* Build configuration list for PBXNativeTarget "AlamofireImage" */; + buildPhases = ( + CC4BD7DC3B6C66E0D660E5AE137D5EFA /* Headers */, + EC82E73BD7A6D07E59AA6C4E703ACF53 /* Sources */, + 2C1047F6C4EE52C8AA60B562CA27EF88 /* Frameworks */, + 02D2C3712053831212DD40D64DCC1E27 /* Resources */, + ); + buildRules = ( + ); + dependencies = ( + 6C1BEAD2D55745FC5FC741F8C60CBEEA /* PBXTargetDependency */, + ); + name = AlamofireImage; + productName = AlamofireImage; + productReference = 31E8026AE06999DD1A0697859A6DD2AE /* AlamofireImage.framework */; + productType = "com.apple.product-type.framework"; + }; + E76458C58C9140B6A16D60547E68E80C /* Alamofire */ = { + isa = PBXNativeTarget; + buildConfigurationList = 427F0F003A1AD80AE00155AFCDEFAC20 /* Build configuration list for PBXNativeTarget "Alamofire" */; + buildPhases = ( + A6A607506FEAAC7C41268D3E5CF4E5FE /* Headers */, + 86CCC4A4A8864DB1BD696381A2D523B0 /* Sources */, + 6E8AF668A2161F7D6F680F721DB65D2D /* Frameworks */, + 3DDB7E21141D7764AE4658D5B6AFF8C6 /* Resources */, + ); + buildRules = ( + ); + dependencies = ( + ); + name = Alamofire; + productName = Alamofire; + productReference = 0858C9D0F89FAA89856A25A21E9E4375 /* Alamofire.framework */; + productType = "com.apple.product-type.framework"; + }; +/* End PBXNativeTarget section */ + +/* Begin PBXProject section */ + D41D8CD98F00B204E9800998ECF8427E /* Project object */ = { + isa = PBXProject; + attributes = { + LastSwiftUpdateCheck = 0930; + LastUpgradeCheck = 0930; + }; + buildConfigurationList = 2D8E8EC45A3A1A1D94AE762CB5028504 /* Build configuration list for PBXProject "Pods" */; + compatibilityVersion = "Xcode 3.2"; + developmentRegion = English; + hasScannedForEncodings = 0; + knownRegions = ( + en, + ); + mainGroup = 7DB346D0F39D3F0E887471402A8071AB; + productRefGroup = F45D28A5EF732FF63827CA48E7D74931 /* Products */; + projectDirPath = ""; + projectRoot = ""; + targets = ( + E76458C58C9140B6A16D60547E68E80C /* Alamofire */, + 5F4BA8B4D605B684ABBD2FB009E45151 /* AlamofireImage */, + 19828C73A3124A7244CF9306F7A32C69 /* GiphyCoreSDK */, + 5D2BD95E6D2F1FF6B446A1D392FD5588 /* Pods-Giphy Search */, + ); + }; +/* End PBXProject section */ + +/* Begin PBXResourcesBuildPhase section */ + 02D2C3712053831212DD40D64DCC1E27 /* Resources */ = { + isa = PBXResourcesBuildPhase; + buildActionMask = 2147483647; + files = ( + ); + runOnlyForDeploymentPostprocessing = 0; + }; + 3DDB7E21141D7764AE4658D5B6AFF8C6 /* Resources */ = { + isa = PBXResourcesBuildPhase; + buildActionMask = 2147483647; + files = ( + ); + runOnlyForDeploymentPostprocessing = 0; + }; + BACAB294727FE33F34CEF9C3366C0EB7 /* Resources */ = { + isa = PBXResourcesBuildPhase; + buildActionMask = 2147483647; + files = ( + ); + runOnlyForDeploymentPostprocessing = 0; + }; + E1BF336D20DC75C2DDD2A9AB1433984F /* Resources */ = { + isa = PBXResourcesBuildPhase; + buildActionMask = 2147483647; + files = ( + ); + runOnlyForDeploymentPostprocessing = 0; + }; +/* End PBXResourcesBuildPhase section */ + +/* Begin PBXSourcesBuildPhase section */ + 0851AEF3EB76A525C75FC0310FD806E3 /* Sources */ = { + isa = PBXSourcesBuildPhase; + buildActionMask = 2147483647; + files = ( + 2932B9857FE28906E32BB7B10ADE632F /* GiphyCore.swift in Sources */, + 38578837A6DBD53EC97EA6C08B79D579 /* GiphyCoreSDK-dummy.m in Sources */, + 51E39EEE8A287772E96315B5E4848EB5 /* GPHAbstractClient.swift in Sources */, + 44221FD16515B202679641D0AB8E5138 /* GPHAsyncOperation.swift in Sources */, + 86A8F0C9FEF4F13201D747D948493BA5 /* GPHBottleData.swift in Sources */, + 0C0999336CB60FB05382C22234F3BD12 /* GPHCategory.swift in Sources */, + 1B9BB6FA8B1063E806B2B85848565729 /* GPHChannel.swift in Sources */, + 4BD4C27516C74875DEECF61FCBBAC52F /* GPHChannelResponse.swift in Sources */, + 208BC377B47C3CB40659D990D98180E6 /* GPHChannelTag.swift in Sources */, + 9678682EA18EA975424ADE69DFCC6FDF /* GPHClient.swift in Sources */, + A8941F45F19AFB646934F36B44C7EAE9 /* GPHError.swift in Sources */, + F45A1FBFDACD59E9A503A834ACBE0DC5 /* GPHFilterable.swift in Sources */, + 1CD2199964B9A046AAD5D5334AC2D598 /* GPHImage.swift in Sources */, + 2305F3556264131853F108275C3F8398 /* GPHImages.swift in Sources */, + 72F3A8CAF8EDC96305B12AD552A46DCF /* GPHListCategoryResponse.swift in Sources */, + 4EC6096B54148453641B27E58ACF9BE6 /* GPHListChannelResponse.swift in Sources */, + 98911DB23E65DBB0061B5B4E8B9C8163 /* GPHListMediaResponse.swift in Sources */, + F8FF1D3214A72E73919D4B4EC6A3F5C2 /* GPHListTermSuggestionRespose.swift in Sources */, + 3097C68621D9261149AFFD3DA1E9FCC9 /* GPHMappable.swift in Sources */, + 6154423EBB7596B73FA383A41D20DF96 /* GPHMedia.swift in Sources */, + 15FB65BCB4965C6535D6A0BF45729318 /* GPHMediaResponse.swift in Sources */, + DC8B1477A63E87749CEA0BB74B70150C /* GPHMeta.swift in Sources */, + F6C27C4EBA7BBCB559013086C90D2D09 /* GPHNetworkReachability.swift in Sources */, + 7E7B3F64A04D8D89CC15B0F527B006D0 /* GPHPagination.swift in Sources */, + 52D24C0AECF15D853C9E0E940B945E8E /* GPHRequest.swift in Sources */, + FA84EF6E647BA385B9C163DA1D5C255B /* GPHRequestConfig.swift in Sources */, + 1CA14C18BD2534E7C4BF1F143A7B3992 /* GPHResponse.swift in Sources */, + BFD8087821CC1D34D365791776FD3971 /* GPHTermSuggestion.swift in Sources */, + EA338DB6E8FA1A61BDC85E7DD77CFA87 /* GPHTypes.swift in Sources */, + 41147D250A2E4D7B4B07F7494FB1B725 /* GPHUser.swift in Sources */, + ); + runOnlyForDeploymentPostprocessing = 0; + }; + 5BFCE4E8068FDEEA7C47E5A2E88E7433 /* Sources */ = { + isa = PBXSourcesBuildPhase; + buildActionMask = 2147483647; + files = ( + F2BE6E75383179D394ED5EC55C660136 /* Pods-Giphy Search-dummy.m in Sources */, + ); + runOnlyForDeploymentPostprocessing = 0; + }; + 86CCC4A4A8864DB1BD696381A2D523B0 /* Sources */ = { + isa = PBXSourcesBuildPhase; + buildActionMask = 2147483647; + files = ( + 7DDEEA91D0D552EA97C246C730D78824 /* AFError.swift in Sources */, + 71C8993DD60E299326A97D5329C3CD71 /* Alamofire-dummy.m in Sources */, + 6E234A862ED158238D3CB582143270EF /* Alamofire.swift in Sources */, + 39E46DB3A3EA5EB4427CC89A9FBE6127 /* DispatchQueue+Alamofire.swift in Sources */, + 40E83A2C4472A974BA66E787E66ACB40 /* MultipartFormData.swift in Sources */, + FD9ACD2FBE5243A91558B907BC425CF1 /* NetworkReachabilityManager.swift in Sources */, + E168E51972842469FAAD625F11D9D781 /* Notifications.swift in Sources */, + 0BF96C90FD9427084AEEE5A80777D315 /* ParameterEncoding.swift in Sources */, + 7EC61770466C1FF57B5A2C82046284B7 /* Request.swift in Sources */, + 72EDF21BFA7D0C52E40EAB4354F8AF44 /* Response.swift in Sources */, + D04270C0C61007A8BB065F92A680D6DE /* ResponseSerialization.swift in Sources */, + CAFDEC2BE2BD6C00E8E71FED4BBFF080 /* Result.swift in Sources */, + 4D4A61EC172DB39FCF11C0829DF6913C /* ServerTrustPolicy.swift in Sources */, + 5FAE6243000CCAF381D57109484B1396 /* SessionDelegate.swift in Sources */, + DA3B50AF86C7F0AB8AA95BC126F0D070 /* SessionManager.swift in Sources */, + 31E097613F217BBF4E774D235917E165 /* TaskDelegate.swift in Sources */, + 66777B3D392D4AF8CBAE17A9C5D13C2F /* Timeline.swift in Sources */, + 918D55F16814247D5D0D74FC75B48FBE /* Validation.swift in Sources */, + ); + runOnlyForDeploymentPostprocessing = 0; + }; + EC82E73BD7A6D07E59AA6C4E703ACF53 /* Sources */ = { + isa = PBXSourcesBuildPhase; + buildActionMask = 2147483647; + files = ( + 8C7F8BED5B207B5BD45457C6154AF2DB /* AFIError.swift in Sources */, + 7BB64E803F9C456C16F4508ADC1ECD4B /* AlamofireImage-dummy.m in Sources */, + 241A895884308A756FA317AB3C366DF2 /* Image.swift in Sources */, + B1E3FC26FEADE86BF9164BF5C387F32C /* ImageCache.swift in Sources */, + 46CBF4D9DC9F49B0D2BEAD741A048109 /* ImageDownloader.swift in Sources */, + 7A4334D14CDAF9ECD065EAF8F0A54431 /* ImageFilter.swift in Sources */, + DDDFD26405A572B0F50D29094E2E9BBA /* Request+AlamofireImage.swift in Sources */, + 53A3D10EF5AC98CB6421D5B94E0360EE /* UIButton+AlamofireImage.swift in Sources */, + 43A7850130BCC891F79E2D0517991151 /* UIImage+AlamofireImage.swift in Sources */, + ADB5CA583C364148A856FF7DDD5814DC /* UIImageView+AlamofireImage.swift in Sources */, + ); + runOnlyForDeploymentPostprocessing = 0; + }; +/* End PBXSourcesBuildPhase section */ + +/* Begin PBXTargetDependency section */ + 11EA5A72559EAC6BAF8675972A831CE6 /* PBXTargetDependency */ = { + isa = PBXTargetDependency; + name = GiphyCoreSDK; + target = 19828C73A3124A7244CF9306F7A32C69 /* GiphyCoreSDK */; + targetProxy = 70BCB262EF988D1824EE4BC307664C62 /* PBXContainerItemProxy */; + }; + 5DA60125C0888E2A42C0F87875AF44CA /* PBXTargetDependency */ = { + isa = PBXTargetDependency; + name = AlamofireImage; + target = 5F4BA8B4D605B684ABBD2FB009E45151 /* AlamofireImage */; + targetProxy = 412DD3039F2133834AFE21755F5FF409 /* PBXContainerItemProxy */; + }; + 6C1BEAD2D55745FC5FC741F8C60CBEEA /* PBXTargetDependency */ = { + isa = PBXTargetDependency; + name = Alamofire; + target = E76458C58C9140B6A16D60547E68E80C /* Alamofire */; + targetProxy = 84DE9D25FE685AFA1B87C7FACEEDB4B4 /* PBXContainerItemProxy */; + }; + D2B2450D4038F5A660FF97642BA6FD3E /* PBXTargetDependency */ = { + isa = PBXTargetDependency; + name = Alamofire; + target = E76458C58C9140B6A16D60547E68E80C /* Alamofire */; + targetProxy = 2554943E4381B6131E33D4F9A9D344EF /* PBXContainerItemProxy */; + }; +/* End PBXTargetDependency section */ + +/* Begin XCBuildConfiguration section */ + 077FA22CDC93B120D917D3D89AAFDFEA /* Release */ = { + isa = XCBuildConfiguration; + baseConfigurationReference = EC7FE4000F844EFBED4C4E96E8AD82E3 /* GiphyCoreSDK.xcconfig */; + buildSettings = { + CODE_SIGN_IDENTITY = ""; + "CODE_SIGN_IDENTITY[sdk=appletvos*]" = ""; + "CODE_SIGN_IDENTITY[sdk=iphoneos*]" = ""; + "CODE_SIGN_IDENTITY[sdk=watchos*]" = ""; + CURRENT_PROJECT_VERSION = 1; + DEFINES_MODULE = YES; + DYLIB_COMPATIBILITY_VERSION = 1; + DYLIB_CURRENT_VERSION = 1; + DYLIB_INSTALL_NAME_BASE = "@rpath"; + GCC_PREFIX_HEADER = "Target Support Files/GiphyCoreSDK/GiphyCoreSDK-prefix.pch"; + INFOPLIST_FILE = "Target Support Files/GiphyCoreSDK/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/GiphyCoreSDK/GiphyCoreSDK.modulemap"; + PRODUCT_MODULE_NAME = GiphyCoreSDK; + PRODUCT_NAME = GiphyCoreSDK; + SDKROOT = iphoneos; + SKIP_INSTALL = YES; + SWIFT_ACTIVE_COMPILATION_CONDITIONS = "$(inherited) "; + SWIFT_COMPILATION_MODE = wholemodule; + SWIFT_OPTIMIZATION_LEVEL = "-O"; + SWIFT_VERSION = 4.2; + TARGETED_DEVICE_FAMILY = "1,2"; + VALIDATE_PRODUCT = YES; + VERSIONING_SYSTEM = "apple-generic"; + VERSION_INFO_PREFIX = ""; + }; + name = Release; + }; + 0CE3AF37574381AF901BDA40A1F17C0E /* Debug */ = { + isa = XCBuildConfiguration; + baseConfigurationReference = 48FBA1BB6777A216F06F1BFDA7F5664A /* Alamofire.xcconfig */; + buildSettings = { + CODE_SIGN_IDENTITY = ""; + "CODE_SIGN_IDENTITY[sdk=appletvos*]" = ""; + "CODE_SIGN_IDENTITY[sdk=iphoneos*]" = ""; + "CODE_SIGN_IDENTITY[sdk=watchos*]" = ""; + CURRENT_PROJECT_VERSION = 1; + DEFINES_MODULE = YES; + DYLIB_COMPATIBILITY_VERSION = 1; + DYLIB_CURRENT_VERSION = 1; + DYLIB_INSTALL_NAME_BASE = "@rpath"; + GCC_PREFIX_HEADER = "Target Support Files/Alamofire/Alamofire-prefix.pch"; + INFOPLIST_FILE = "Target Support Files/Alamofire/Info.plist"; + INSTALL_PATH = "$(LOCAL_LIBRARY_DIR)/Frameworks"; + IPHONEOS_DEPLOYMENT_TARGET = 8.0; + LD_RUNPATH_SEARCH_PATHS = ( + "$(inherited)", + "@executable_path/Frameworks", + "@loader_path/Frameworks", + ); + MODULEMAP_FILE = "Target Support Files/Alamofire/Alamofire.modulemap"; + PRODUCT_MODULE_NAME = Alamofire; + PRODUCT_NAME = Alamofire; + SDKROOT = iphoneos; + SKIP_INSTALL = YES; + SWIFT_ACTIVE_COMPILATION_CONDITIONS = "$(inherited) "; + SWIFT_OPTIMIZATION_LEVEL = "-Onone"; + SWIFT_VERSION = 4.2; + TARGETED_DEVICE_FAMILY = "1,2"; + VERSIONING_SYSTEM = "apple-generic"; + VERSION_INFO_PREFIX = ""; + }; + name = Debug; + }; + 1FAC42999DB6B764662174F6D556AB8E /* Release */ = { + isa = XCBuildConfiguration; + baseConfigurationReference = 3B8057DE472B446B51AB9D280B4B3AE2 /* Pods-Giphy Search.release.xcconfig */; + buildSettings = { + ALWAYS_EMBED_SWIFT_STANDARD_LIBRARIES = NO; + CLANG_ENABLE_OBJC_WEAK = NO; + CODE_SIGN_IDENTITY = ""; + "CODE_SIGN_IDENTITY[sdk=appletvos*]" = ""; + "CODE_SIGN_IDENTITY[sdk=iphoneos*]" = ""; + "CODE_SIGN_IDENTITY[sdk=watchos*]" = ""; + CURRENT_PROJECT_VERSION = 1; + DEFINES_MODULE = YES; + DYLIB_COMPATIBILITY_VERSION = 1; + DYLIB_CURRENT_VERSION = 1; + DYLIB_INSTALL_NAME_BASE = "@rpath"; + INFOPLIST_FILE = "Target Support Files/Pods-Giphy Search/Info.plist"; + INSTALL_PATH = "$(LOCAL_LIBRARY_DIR)/Frameworks"; + IPHONEOS_DEPLOYMENT_TARGET = 11.0; + LD_RUNPATH_SEARCH_PATHS = ( + "$(inherited)", + "@executable_path/Frameworks", + "@loader_path/Frameworks", + ); + MACH_O_TYPE = staticlib; + MODULEMAP_FILE = "Target Support Files/Pods-Giphy Search/Pods-Giphy Search.modulemap"; + OTHER_LDFLAGS = ""; + OTHER_LIBTOOLFLAGS = ""; + PODS_ROOT = "$(SRCROOT)"; + PRODUCT_BUNDLE_IDENTIFIER = "org.cocoapods.${PRODUCT_NAME:rfc1034identifier}"; + PRODUCT_NAME = "$(TARGET_NAME:c99extidentifier)"; + SDKROOT = iphoneos; + SKIP_INSTALL = YES; + SWIFT_COMPILATION_MODE = wholemodule; + SWIFT_OPTIMIZATION_LEVEL = "-O"; + TARGETED_DEVICE_FAMILY = "1,2"; + VALIDATE_PRODUCT = YES; + VERSIONING_SYSTEM = "apple-generic"; + VERSION_INFO_PREFIX = ""; + }; + name = Release; + }; + 29461B23402771DC36BB84FE023D99B9 /* Release */ = { + isa = XCBuildConfiguration; + baseConfigurationReference = 48FBA1BB6777A216F06F1BFDA7F5664A /* Alamofire.xcconfig */; + buildSettings = { + CODE_SIGN_IDENTITY = ""; + "CODE_SIGN_IDENTITY[sdk=appletvos*]" = ""; + "CODE_SIGN_IDENTITY[sdk=iphoneos*]" = ""; + "CODE_SIGN_IDENTITY[sdk=watchos*]" = ""; + CURRENT_PROJECT_VERSION = 1; + DEFINES_MODULE = YES; + DYLIB_COMPATIBILITY_VERSION = 1; + DYLIB_CURRENT_VERSION = 1; + DYLIB_INSTALL_NAME_BASE = "@rpath"; + GCC_PREFIX_HEADER = "Target Support Files/Alamofire/Alamofire-prefix.pch"; + INFOPLIST_FILE = "Target Support Files/Alamofire/Info.plist"; + INSTALL_PATH = "$(LOCAL_LIBRARY_DIR)/Frameworks"; + IPHONEOS_DEPLOYMENT_TARGET = 8.0; + LD_RUNPATH_SEARCH_PATHS = ( + "$(inherited)", + "@executable_path/Frameworks", + "@loader_path/Frameworks", + ); + MODULEMAP_FILE = "Target Support Files/Alamofire/Alamofire.modulemap"; + PRODUCT_MODULE_NAME = Alamofire; + PRODUCT_NAME = Alamofire; + SDKROOT = iphoneos; + SKIP_INSTALL = YES; + SWIFT_ACTIVE_COMPILATION_CONDITIONS = "$(inherited) "; + SWIFT_COMPILATION_MODE = wholemodule; + SWIFT_OPTIMIZATION_LEVEL = "-O"; + SWIFT_VERSION = 4.2; + TARGETED_DEVICE_FAMILY = "1,2"; + VALIDATE_PRODUCT = YES; + VERSIONING_SYSTEM = "apple-generic"; + VERSION_INFO_PREFIX = ""; + }; + name = Release; + }; + 60D9B164C2D92A9D5E15B21E3DE597E4 /* Release */ = { + isa = XCBuildConfiguration; + baseConfigurationReference = FDE4A021CB10C1C74833AE7D71CD301E /* AlamofireImage.xcconfig */; + buildSettings = { + CODE_SIGN_IDENTITY = ""; + "CODE_SIGN_IDENTITY[sdk=appletvos*]" = ""; + "CODE_SIGN_IDENTITY[sdk=iphoneos*]" = ""; + "CODE_SIGN_IDENTITY[sdk=watchos*]" = ""; + CURRENT_PROJECT_VERSION = 1; + DEFINES_MODULE = YES; + DYLIB_COMPATIBILITY_VERSION = 1; + DYLIB_CURRENT_VERSION = 1; + DYLIB_INSTALL_NAME_BASE = "@rpath"; + GCC_PREFIX_HEADER = "Target Support Files/AlamofireImage/AlamofireImage-prefix.pch"; + INFOPLIST_FILE = "Target Support Files/AlamofireImage/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/AlamofireImage/AlamofireImage.modulemap"; + PRODUCT_MODULE_NAME = AlamofireImage; + PRODUCT_NAME = AlamofireImage; + SDKROOT = iphoneos; + SKIP_INSTALL = YES; + SWIFT_ACTIVE_COMPILATION_CONDITIONS = "$(inherited) "; + SWIFT_COMPILATION_MODE = wholemodule; + SWIFT_OPTIMIZATION_LEVEL = "-O"; + SWIFT_VERSION = 4.2; + TARGETED_DEVICE_FAMILY = "1,2"; + VALIDATE_PRODUCT = YES; + VERSIONING_SYSTEM = "apple-generic"; + VERSION_INFO_PREFIX = ""; + }; + name = Release; + }; + 7C04C39AD458D252BE34D3A422496FB9 /* Debug */ = { + isa = XCBuildConfiguration; + baseConfigurationReference = CADC1CD570310F38D608A9D5603A0E84 /* Pods-Giphy Search.debug.xcconfig */; + buildSettings = { + ALWAYS_EMBED_SWIFT_STANDARD_LIBRARIES = NO; + CLANG_ENABLE_OBJC_WEAK = NO; + CODE_SIGN_IDENTITY = ""; + "CODE_SIGN_IDENTITY[sdk=appletvos*]" = ""; + "CODE_SIGN_IDENTITY[sdk=iphoneos*]" = ""; + "CODE_SIGN_IDENTITY[sdk=watchos*]" = ""; + CURRENT_PROJECT_VERSION = 1; + DEFINES_MODULE = YES; + DYLIB_COMPATIBILITY_VERSION = 1; + DYLIB_CURRENT_VERSION = 1; + DYLIB_INSTALL_NAME_BASE = "@rpath"; + INFOPLIST_FILE = "Target Support Files/Pods-Giphy Search/Info.plist"; + INSTALL_PATH = "$(LOCAL_LIBRARY_DIR)/Frameworks"; + IPHONEOS_DEPLOYMENT_TARGET = 11.0; + LD_RUNPATH_SEARCH_PATHS = ( + "$(inherited)", + "@executable_path/Frameworks", + "@loader_path/Frameworks", + ); + MACH_O_TYPE = staticlib; + MODULEMAP_FILE = "Target Support Files/Pods-Giphy Search/Pods-Giphy Search.modulemap"; + OTHER_LDFLAGS = ""; + OTHER_LIBTOOLFLAGS = ""; + PODS_ROOT = "$(SRCROOT)"; + PRODUCT_BUNDLE_IDENTIFIER = "org.cocoapods.${PRODUCT_NAME:rfc1034identifier}"; + PRODUCT_NAME = "$(TARGET_NAME:c99extidentifier)"; + SDKROOT = iphoneos; + SKIP_INSTALL = YES; + SWIFT_ACTIVE_COMPILATION_CONDITIONS = DEBUG; + SWIFT_OPTIMIZATION_LEVEL = "-Onone"; + TARGETED_DEVICE_FAMILY = "1,2"; + VERSIONING_SYSTEM = "apple-generic"; + VERSION_INFO_PREFIX = ""; + }; + name = Debug; + }; + 8C3D32AC054F4DBEE82EB2FD6A303D73 /* Debug */ = { + isa = XCBuildConfiguration; + buildSettings = { + ALWAYS_SEARCH_USER_PATHS = NO; + CLANG_ANALYZER_NONNULL = YES; + CLANG_ANALYZER_NUMBER_OBJECT_CONVERSION = YES_AGGRESSIVE; + CLANG_CXX_LANGUAGE_STANDARD = "gnu++14"; + CLANG_CXX_LIBRARY = "libc++"; + CLANG_ENABLE_MODULES = YES; + CLANG_ENABLE_OBJC_ARC = YES; + CLANG_ENABLE_OBJC_WEAK = YES; + CLANG_WARN_BLOCK_CAPTURE_AUTORELEASING = YES; + CLANG_WARN_BOOL_CONVERSION = YES; + CLANG_WARN_COMMA = YES; + CLANG_WARN_CONSTANT_CONVERSION = YES; + CLANG_WARN_DEPRECATED_OBJC_IMPLEMENTATIONS = YES; + CLANG_WARN_DIRECT_OBJC_ISA_USAGE = YES_ERROR; + CLANG_WARN_DOCUMENTATION_COMMENTS = YES; + CLANG_WARN_EMPTY_BODY = YES; + CLANG_WARN_ENUM_CONVERSION = YES; + CLANG_WARN_INFINITE_RECURSION = YES; + CLANG_WARN_INT_CONVERSION = YES; + CLANG_WARN_NON_LITERAL_NULL_CONVERSION = YES; + CLANG_WARN_OBJC_IMPLICIT_RETAIN_SELF = YES; + CLANG_WARN_OBJC_LITERAL_CONVERSION = YES; + CLANG_WARN_OBJC_ROOT_CLASS = YES_ERROR; + CLANG_WARN_RANGE_LOOP_ANALYSIS = YES; + CLANG_WARN_STRICT_PROTOTYPES = YES; + CLANG_WARN_SUSPICIOUS_MOVE = YES; + CLANG_WARN_UNGUARDED_AVAILABILITY = YES_AGGRESSIVE; + CLANG_WARN_UNREACHABLE_CODE = YES; + CLANG_WARN__DUPLICATE_METHOD_MATCH = YES; + CODE_SIGNING_ALLOWED = NO; + CODE_SIGNING_REQUIRED = NO; + COPY_PHASE_STRIP = NO; + DEBUG_INFORMATION_FORMAT = dwarf; + ENABLE_STRICT_OBJC_MSGSEND = YES; + ENABLE_TESTABILITY = YES; + GCC_C_LANGUAGE_STANDARD = gnu11; + GCC_DYNAMIC_NO_PIC = NO; + GCC_NO_COMMON_BLOCKS = YES; + GCC_OPTIMIZATION_LEVEL = 0; + GCC_PREPROCESSOR_DEFINITIONS = ( + "POD_CONFIGURATION_DEBUG=1", + "DEBUG=1", + "$(inherited)", + ); + GCC_WARN_64_TO_32_BIT_CONVERSION = YES; + GCC_WARN_ABOUT_RETURN_TYPE = YES_ERROR; + GCC_WARN_UNDECLARED_SELECTOR = YES; + GCC_WARN_UNINITIALIZED_AUTOS = YES_AGGRESSIVE; + GCC_WARN_UNUSED_FUNCTION = YES; + GCC_WARN_UNUSED_VARIABLE = YES; + IPHONEOS_DEPLOYMENT_TARGET = 11.0; + MTL_ENABLE_DEBUG_INFO = INCLUDE_SOURCE; + MTL_FAST_MATH = YES; + ONLY_ACTIVE_ARCH = YES; + PRODUCT_NAME = "$(TARGET_NAME)"; + STRIP_INSTALLED_PRODUCT = NO; + SWIFT_ACTIVE_COMPILATION_CONDITIONS = DEBUG; + SYMROOT = "${SRCROOT}/../build"; + }; + name = Debug; + }; + 991F72EDB3552888724AC4A6D950BBD1 /* Debug */ = { + isa = XCBuildConfiguration; + baseConfigurationReference = EC7FE4000F844EFBED4C4E96E8AD82E3 /* GiphyCoreSDK.xcconfig */; + buildSettings = { + CODE_SIGN_IDENTITY = ""; + "CODE_SIGN_IDENTITY[sdk=appletvos*]" = ""; + "CODE_SIGN_IDENTITY[sdk=iphoneos*]" = ""; + "CODE_SIGN_IDENTITY[sdk=watchos*]" = ""; + CURRENT_PROJECT_VERSION = 1; + DEFINES_MODULE = YES; + DYLIB_COMPATIBILITY_VERSION = 1; + DYLIB_CURRENT_VERSION = 1; + DYLIB_INSTALL_NAME_BASE = "@rpath"; + GCC_PREFIX_HEADER = "Target Support Files/GiphyCoreSDK/GiphyCoreSDK-prefix.pch"; + INFOPLIST_FILE = "Target Support Files/GiphyCoreSDK/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/GiphyCoreSDK/GiphyCoreSDK.modulemap"; + PRODUCT_MODULE_NAME = GiphyCoreSDK; + PRODUCT_NAME = GiphyCoreSDK; + SDKROOT = iphoneos; + SKIP_INSTALL = YES; + SWIFT_ACTIVE_COMPILATION_CONDITIONS = "$(inherited) "; + SWIFT_OPTIMIZATION_LEVEL = "-Onone"; + SWIFT_VERSION = 4.2; + TARGETED_DEVICE_FAMILY = "1,2"; + VERSIONING_SYSTEM = "apple-generic"; + VERSION_INFO_PREFIX = ""; + }; + name = Debug; + }; + B751CA5B597BFC35A6C0287C65F9E2E1 /* Release */ = { + isa = XCBuildConfiguration; + buildSettings = { + ALWAYS_SEARCH_USER_PATHS = NO; + CLANG_ANALYZER_NONNULL = YES; + CLANG_ANALYZER_NUMBER_OBJECT_CONVERSION = YES_AGGRESSIVE; + CLANG_CXX_LANGUAGE_STANDARD = "gnu++14"; + CLANG_CXX_LIBRARY = "libc++"; + CLANG_ENABLE_MODULES = YES; + CLANG_ENABLE_OBJC_ARC = YES; + CLANG_ENABLE_OBJC_WEAK = YES; + CLANG_WARN_BLOCK_CAPTURE_AUTORELEASING = YES; + CLANG_WARN_BOOL_CONVERSION = YES; + CLANG_WARN_COMMA = YES; + CLANG_WARN_CONSTANT_CONVERSION = YES; + CLANG_WARN_DEPRECATED_OBJC_IMPLEMENTATIONS = YES; + CLANG_WARN_DIRECT_OBJC_ISA_USAGE = YES_ERROR; + CLANG_WARN_DOCUMENTATION_COMMENTS = YES; + CLANG_WARN_EMPTY_BODY = YES; + CLANG_WARN_ENUM_CONVERSION = YES; + CLANG_WARN_INFINITE_RECURSION = YES; + CLANG_WARN_INT_CONVERSION = YES; + CLANG_WARN_NON_LITERAL_NULL_CONVERSION = YES; + CLANG_WARN_OBJC_IMPLICIT_RETAIN_SELF = YES; + CLANG_WARN_OBJC_LITERAL_CONVERSION = YES; + CLANG_WARN_OBJC_ROOT_CLASS = YES_ERROR; + CLANG_WARN_RANGE_LOOP_ANALYSIS = YES; + CLANG_WARN_STRICT_PROTOTYPES = YES; + CLANG_WARN_SUSPICIOUS_MOVE = YES; + CLANG_WARN_UNGUARDED_AVAILABILITY = YES_AGGRESSIVE; + CLANG_WARN_UNREACHABLE_CODE = YES; + CLANG_WARN__DUPLICATE_METHOD_MATCH = YES; + CODE_SIGNING_ALLOWED = NO; + CODE_SIGNING_REQUIRED = NO; + COPY_PHASE_STRIP = NO; + DEBUG_INFORMATION_FORMAT = "dwarf-with-dsym"; + ENABLE_NS_ASSERTIONS = NO; + ENABLE_STRICT_OBJC_MSGSEND = YES; + GCC_C_LANGUAGE_STANDARD = gnu11; + GCC_NO_COMMON_BLOCKS = YES; + GCC_PREPROCESSOR_DEFINITIONS = ( + "POD_CONFIGURATION_RELEASE=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 = 11.0; + MTL_ENABLE_DEBUG_INFO = NO; + MTL_FAST_MATH = YES; + PRODUCT_NAME = "$(TARGET_NAME)"; + STRIP_INSTALLED_PRODUCT = NO; + SYMROOT = "${SRCROOT}/../build"; + }; + name = Release; + }; + FDF6ACECC103C62769643F4CB4DF6B3A /* Debug */ = { + isa = XCBuildConfiguration; + baseConfigurationReference = FDE4A021CB10C1C74833AE7D71CD301E /* AlamofireImage.xcconfig */; + buildSettings = { + CODE_SIGN_IDENTITY = ""; + "CODE_SIGN_IDENTITY[sdk=appletvos*]" = ""; + "CODE_SIGN_IDENTITY[sdk=iphoneos*]" = ""; + "CODE_SIGN_IDENTITY[sdk=watchos*]" = ""; + CURRENT_PROJECT_VERSION = 1; + DEFINES_MODULE = YES; + DYLIB_COMPATIBILITY_VERSION = 1; + DYLIB_CURRENT_VERSION = 1; + DYLIB_INSTALL_NAME_BASE = "@rpath"; + GCC_PREFIX_HEADER = "Target Support Files/AlamofireImage/AlamofireImage-prefix.pch"; + INFOPLIST_FILE = "Target Support Files/AlamofireImage/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/AlamofireImage/AlamofireImage.modulemap"; + PRODUCT_MODULE_NAME = AlamofireImage; + PRODUCT_NAME = AlamofireImage; + SDKROOT = iphoneos; + SKIP_INSTALL = YES; + SWIFT_ACTIVE_COMPILATION_CONDITIONS = "$(inherited) "; + SWIFT_OPTIMIZATION_LEVEL = "-Onone"; + SWIFT_VERSION = 4.2; + TARGETED_DEVICE_FAMILY = "1,2"; + VERSIONING_SYSTEM = "apple-generic"; + VERSION_INFO_PREFIX = ""; + }; + name = Debug; + }; +/* End XCBuildConfiguration section */ + +/* Begin XCConfigurationList section */ + 166D00443DEEE6DD3F026CFBF8A8E523 /* Build configuration list for PBXNativeTarget "Pods-Giphy Search" */ = { + isa = XCConfigurationList; + buildConfigurations = ( + 7C04C39AD458D252BE34D3A422496FB9 /* Debug */, + 1FAC42999DB6B764662174F6D556AB8E /* Release */, + ); + defaultConfigurationIsVisible = 0; + defaultConfigurationName = Release; + }; + 2D8E8EC45A3A1A1D94AE762CB5028504 /* Build configuration list for PBXProject "Pods" */ = { + isa = XCConfigurationList; + buildConfigurations = ( + 8C3D32AC054F4DBEE82EB2FD6A303D73 /* Debug */, + B751CA5B597BFC35A6C0287C65F9E2E1 /* Release */, + ); + defaultConfigurationIsVisible = 0; + defaultConfigurationName = Release; + }; + 345CDDB6E42B3ED1847D232C452F4F1C /* Build configuration list for PBXNativeTarget "GiphyCoreSDK" */ = { + isa = XCConfigurationList; + buildConfigurations = ( + 991F72EDB3552888724AC4A6D950BBD1 /* Debug */, + 077FA22CDC93B120D917D3D89AAFDFEA /* Release */, + ); + defaultConfigurationIsVisible = 0; + defaultConfigurationName = Release; + }; + 427F0F003A1AD80AE00155AFCDEFAC20 /* Build configuration list for PBXNativeTarget "Alamofire" */ = { + isa = XCConfigurationList; + buildConfigurations = ( + 0CE3AF37574381AF901BDA40A1F17C0E /* Debug */, + 29461B23402771DC36BB84FE023D99B9 /* Release */, + ); + defaultConfigurationIsVisible = 0; + defaultConfigurationName = Release; + }; + FECA52B188EB8A276F28B478D92AF353 /* Build configuration list for PBXNativeTarget "AlamofireImage" */ = { + isa = XCConfigurationList; + buildConfigurations = ( + FDF6ACECC103C62769643F4CB4DF6B3A /* Debug */, + 60D9B164C2D92A9D5E15B21E3DE597E4 /* Release */, + ); + defaultConfigurationIsVisible = 0; + defaultConfigurationName = Release; + }; +/* End XCConfigurationList section */ + }; + rootObject = D41D8CD98F00B204E9800998ECF8427E /* Project object */; +} 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..1453c10 --- /dev/null +++ b/Pods/Target Support Files/Alamofire/Alamofire.xcconfig @@ -0,0 +1,9 @@ +CONFIGURATION_BUILD_DIR = ${PODS_CONFIGURATION_BUILD_DIR}/Alamofire +GCC_PREPROCESSOR_DEFINITIONS = $(inherited) COCOAPODS=1 +OTHER_SWIFT_FLAGS = $(inherited) "-D" "COCOAPODS" "-suppress-warnings" +PODS_BUILD_DIR = ${BUILD_DIR} +PODS_CONFIGURATION_BUILD_DIR = ${PODS_BUILD_DIR}/$(CONFIGURATION)$(EFFECTIVE_PLATFORM_NAME) +PODS_ROOT = ${SRCROOT} +PODS_TARGET_SRCROOT = ${PODS_ROOT}/Alamofire +PRODUCT_BUNDLE_IDENTIFIER = org.cocoapods.${PRODUCT_NAME:rfc1034identifier} +SKIP_INSTALL = YES diff --git a/Pods/Target Support Files/Alamofire/Info.plist b/Pods/Target Support Files/Alamofire/Info.plist new file mode 100644 index 0000000..2aba7e5 --- /dev/null +++ b/Pods/Target Support Files/Alamofire/Info.plist @@ -0,0 +1,26 @@ + + + + + CFBundleDevelopmentRegion + en + CFBundleExecutable + ${EXECUTABLE_NAME} + CFBundleIdentifier + ${PRODUCT_BUNDLE_IDENTIFIER} + CFBundleInfoDictionaryVersion + 6.0 + CFBundleName + ${PRODUCT_NAME} + CFBundlePackageType + FMWK + CFBundleShortVersionString + 4.7.3 + CFBundleSignature + ???? + CFBundleVersion + ${CURRENT_PROJECT_VERSION} + NSPrincipalClass + + + diff --git a/Pods/Target Support Files/AlamofireImage/AlamofireImage-dummy.m b/Pods/Target Support Files/AlamofireImage/AlamofireImage-dummy.m new file mode 100644 index 0000000..ff0744b --- /dev/null +++ b/Pods/Target Support Files/AlamofireImage/AlamofireImage-dummy.m @@ -0,0 +1,5 @@ +#import +@interface PodsDummy_AlamofireImage : NSObject +@end +@implementation PodsDummy_AlamofireImage +@end diff --git a/Pods/Target Support Files/AlamofireImage/AlamofireImage-prefix.pch b/Pods/Target Support Files/AlamofireImage/AlamofireImage-prefix.pch new file mode 100644 index 0000000..beb2a24 --- /dev/null +++ b/Pods/Target Support Files/AlamofireImage/AlamofireImage-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/AlamofireImage/AlamofireImage-umbrella.h b/Pods/Target Support Files/AlamofireImage/AlamofireImage-umbrella.h new file mode 100644 index 0000000..483fa10 --- /dev/null +++ b/Pods/Target Support Files/AlamofireImage/AlamofireImage-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 AlamofireImageVersionNumber; +FOUNDATION_EXPORT const unsigned char AlamofireImageVersionString[]; + diff --git a/Pods/Target Support Files/AlamofireImage/AlamofireImage.modulemap b/Pods/Target Support Files/AlamofireImage/AlamofireImage.modulemap new file mode 100644 index 0000000..d43423a --- /dev/null +++ b/Pods/Target Support Files/AlamofireImage/AlamofireImage.modulemap @@ -0,0 +1,6 @@ +framework module AlamofireImage { + umbrella header "AlamofireImage-umbrella.h" + + export * + module * { export * } +} diff --git a/Pods/Target Support Files/AlamofireImage/AlamofireImage.xcconfig b/Pods/Target Support Files/AlamofireImage/AlamofireImage.xcconfig new file mode 100644 index 0000000..56a89e2 --- /dev/null +++ b/Pods/Target Support Files/AlamofireImage/AlamofireImage.xcconfig @@ -0,0 +1,10 @@ +CONFIGURATION_BUILD_DIR = ${PODS_CONFIGURATION_BUILD_DIR}/AlamofireImage +FRAMEWORK_SEARCH_PATHS = $(inherited) "${PODS_CONFIGURATION_BUILD_DIR}/Alamofire" +GCC_PREPROCESSOR_DEFINITIONS = $(inherited) COCOAPODS=1 +OTHER_SWIFT_FLAGS = $(inherited) "-D" "COCOAPODS" "-suppress-warnings" +PODS_BUILD_DIR = ${BUILD_DIR} +PODS_CONFIGURATION_BUILD_DIR = ${PODS_BUILD_DIR}/$(CONFIGURATION)$(EFFECTIVE_PLATFORM_NAME) +PODS_ROOT = ${SRCROOT} +PODS_TARGET_SRCROOT = ${PODS_ROOT}/AlamofireImage +PRODUCT_BUNDLE_IDENTIFIER = org.cocoapods.${PRODUCT_NAME:rfc1034identifier} +SKIP_INSTALL = YES diff --git a/Pods/Target Support Files/AlamofireImage/Info.plist b/Pods/Target Support Files/AlamofireImage/Info.plist new file mode 100644 index 0000000..7694605 --- /dev/null +++ b/Pods/Target Support Files/AlamofireImage/Info.plist @@ -0,0 +1,26 @@ + + + + + CFBundleDevelopmentRegion + en + CFBundleExecutable + ${EXECUTABLE_NAME} + CFBundleIdentifier + ${PRODUCT_BUNDLE_IDENTIFIER} + CFBundleInfoDictionaryVersion + 6.0 + CFBundleName + ${PRODUCT_NAME} + CFBundlePackageType + FMWK + CFBundleShortVersionString + 3.4.1 + CFBundleSignature + ???? + CFBundleVersion + ${CURRENT_PROJECT_VERSION} + NSPrincipalClass + + + diff --git a/Pods/Target Support Files/GiphyCoreSDK/GiphyCoreSDK-dummy.m b/Pods/Target Support Files/GiphyCoreSDK/GiphyCoreSDK-dummy.m new file mode 100644 index 0000000..274343f --- /dev/null +++ b/Pods/Target Support Files/GiphyCoreSDK/GiphyCoreSDK-dummy.m @@ -0,0 +1,5 @@ +#import +@interface PodsDummy_GiphyCoreSDK : NSObject +@end +@implementation PodsDummy_GiphyCoreSDK +@end diff --git a/Pods/Target Support Files/GiphyCoreSDK/GiphyCoreSDK-prefix.pch b/Pods/Target Support Files/GiphyCoreSDK/GiphyCoreSDK-prefix.pch new file mode 100644 index 0000000..beb2a24 --- /dev/null +++ b/Pods/Target Support Files/GiphyCoreSDK/GiphyCoreSDK-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/GiphyCoreSDK/GiphyCoreSDK-umbrella.h b/Pods/Target Support Files/GiphyCoreSDK/GiphyCoreSDK-umbrella.h new file mode 100644 index 0000000..7194923 --- /dev/null +++ b/Pods/Target Support Files/GiphyCoreSDK/GiphyCoreSDK-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 GiphyCoreSDKVersionNumber; +FOUNDATION_EXPORT const unsigned char GiphyCoreSDKVersionString[]; + diff --git a/Pods/Target Support Files/GiphyCoreSDK/GiphyCoreSDK.modulemap b/Pods/Target Support Files/GiphyCoreSDK/GiphyCoreSDK.modulemap new file mode 100644 index 0000000..f22f8fb --- /dev/null +++ b/Pods/Target Support Files/GiphyCoreSDK/GiphyCoreSDK.modulemap @@ -0,0 +1,6 @@ +framework module GiphyCoreSDK { + umbrella header "GiphyCoreSDK-umbrella.h" + + export * + module * { export * } +} diff --git a/Pods/Target Support Files/GiphyCoreSDK/GiphyCoreSDK.xcconfig b/Pods/Target Support Files/GiphyCoreSDK/GiphyCoreSDK.xcconfig new file mode 100644 index 0000000..82fd2c2 --- /dev/null +++ b/Pods/Target Support Files/GiphyCoreSDK/GiphyCoreSDK.xcconfig @@ -0,0 +1,9 @@ +CONFIGURATION_BUILD_DIR = ${PODS_CONFIGURATION_BUILD_DIR}/GiphyCoreSDK +GCC_PREPROCESSOR_DEFINITIONS = $(inherited) COCOAPODS=1 +OTHER_SWIFT_FLAGS = $(inherited) "-D" "COCOAPODS" "-suppress-warnings" +PODS_BUILD_DIR = ${BUILD_DIR} +PODS_CONFIGURATION_BUILD_DIR = ${PODS_BUILD_DIR}/$(CONFIGURATION)$(EFFECTIVE_PLATFORM_NAME) +PODS_ROOT = ${SRCROOT} +PODS_TARGET_SRCROOT = ${PODS_ROOT}/GiphyCoreSDK +PRODUCT_BUNDLE_IDENTIFIER = org.cocoapods.${PRODUCT_NAME:rfc1034identifier} +SKIP_INSTALL = YES diff --git a/Pods/Target Support Files/GiphyCoreSDK/Info.plist b/Pods/Target Support Files/GiphyCoreSDK/Info.plist new file mode 100644 index 0000000..7b6b52a --- /dev/null +++ b/Pods/Target Support Files/GiphyCoreSDK/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.4.0 + CFBundleSignature + ???? + CFBundleVersion + ${CURRENT_PROJECT_VERSION} + NSPrincipalClass + + + diff --git a/Pods/Target Support Files/Pods-Giphy Search/Info.plist b/Pods/Target Support Files/Pods-Giphy Search/Info.plist new file mode 100644 index 0000000..2243fe6 --- /dev/null +++ b/Pods/Target Support Files/Pods-Giphy Search/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-Giphy Search/Pods-Giphy Search-acknowledgements.markdown b/Pods/Target Support Files/Pods-Giphy Search/Pods-Giphy Search-acknowledgements.markdown new file mode 100644 index 0000000..54ec70c --- /dev/null +++ b/Pods/Target Support Files/Pods-Giphy Search/Pods-Giphy Search-acknowledgements.markdown @@ -0,0 +1,426 @@ +# Acknowledgements +This application makes use of the following third party libraries: + +## Alamofire + +Copyright (c) 2014-2018 Alamofire Software Foundation (http://alamofire.org/) + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in +all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN +THE SOFTWARE. + + +## AlamofireImage + +Copyright (c) 2015-2018 Alamofire Software Foundation (http://alamofire.org/) + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in +all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN +THE SOFTWARE. + + +## GiphyCoreSDK + +Mozilla Public License Version 2.0 +================================== + +1. Definitions +-------------- + +1.1. "Contributor" + means each individual or legal entity that creates, contributes to + the creation of, or owns Covered Software. + +1.2. "Contributor Version" + means the combination of the Contributions of others (if any) used + by a Contributor and that particular Contributor's Contribution. + +1.3. "Contribution" + means Covered Software of a particular Contributor. + +1.4. "Covered Software" + means Source Code Form to which the initial Contributor has attached + the notice in Exhibit A, the Executable Form of such Source Code + Form, and Modifications of such Source Code Form, in each case + including portions thereof. + +1.5. "Incompatible With Secondary Licenses" + means + + (a) that the initial Contributor has attached the notice described + in Exhibit B to the Covered Software; or + + (b) that the Covered Software was made available under the terms of + version 1.1 or earlier of the License, but not also under the + terms of a Secondary License. + +1.6. "Executable Form" + means any form of the work other than Source Code Form. + +1.7. "Larger Work" + means a work that combines Covered Software with other material, in + a separate file or files, that is not Covered Software. + +1.8. "License" + means this document. + +1.9. "Licensable" + means having the right to grant, to the maximum extent possible, + whether at the time of the initial grant or subsequently, any and + all of the rights conveyed by this License. + +1.10. "Modifications" + means any of the following: + + (a) any file in Source Code Form that results from an addition to, + deletion from, or modification of the contents of Covered + Software; or + + (b) any new file in Source Code Form that contains any Covered + Software. + +1.11. "Patent Claims" of a Contributor + means any patent claim(s), including without limitation, method, + process, and apparatus claims, in any patent Licensable by such + Contributor that would be infringed, but for the grant of the + License, by the making, using, selling, offering for sale, having + made, import, or transfer of either its Contributions or its + Contributor Version. + +1.12. "Secondary License" + means either the GNU General Public License, Version 2.0, the GNU + Lesser General Public License, Version 2.1, the GNU Affero General + Public License, Version 3.0, or any later versions of those + licenses. + +1.13. "Source Code Form" + means the form of the work preferred for making modifications. + +1.14. "You" (or "Your") + means an individual or a legal entity exercising rights under this + License. For legal entities, "You" includes any entity that + controls, is controlled by, or is under common control with You. For + purposes of this definition, "control" means (a) the power, direct + or indirect, to cause the direction or management of such entity, + whether by contract or otherwise, or (b) ownership of more than + fifty percent (50%) of the outstanding shares or beneficial + ownership of such entity. + +2. License Grants and Conditions +-------------------------------- + +2.1. Grants + +Each Contributor hereby grants You a world-wide, royalty-free, +non-exclusive license: + +(a) under intellectual property rights (other than patent or trademark) + Licensable by such Contributor to use, reproduce, make available, + modify, display, perform, distribute, and otherwise exploit its + Contributions, either on an unmodified basis, with Modifications, or + as part of a Larger Work; and + +(b) under Patent Claims of such Contributor to make, use, sell, offer + for sale, have made, import, and otherwise transfer either its + Contributions or its Contributor Version. + +2.2. Effective Date + +The licenses granted in Section 2.1 with respect to any Contribution +become effective for each Contribution on the date the Contributor first +distributes such Contribution. + +2.3. Limitations on Grant Scope + +The licenses granted in this Section 2 are the only rights granted under +this License. No additional rights or licenses will be implied from the +distribution or licensing of Covered Software under this License. +Notwithstanding Section 2.1(b) above, no patent license is granted by a +Contributor: + +(a) for any code that a Contributor has removed from Covered Software; + or + +(b) for infringements caused by: (i) Your and any other third party's + modifications of Covered Software, or (ii) the combination of its + Contributions with other software (except as part of its Contributor + Version); or + +(c) under Patent Claims infringed by Covered Software in the absence of + its Contributions. + +This License does not grant any rights in the trademarks, service marks, +or logos of any Contributor (except as may be necessary to comply with +the notice requirements in Section 3.4). + +2.4. Subsequent Licenses + +No Contributor makes additional grants as a result of Your choice to +distribute the Covered Software under a subsequent version of this +License (see Section 10.2) or under the terms of a Secondary License (if +permitted under the terms of Section 3.3). + +2.5. Representation + +Each Contributor represents that the Contributor believes its +Contributions are its original creation(s) or it has sufficient rights +to grant the rights to its Contributions conveyed by this License. + +2.6. Fair Use + +This License is not intended to limit any rights You have under +applicable copyright doctrines of fair use, fair dealing, or other +equivalents. + +2.7. Conditions + +Sections 3.1, 3.2, 3.3, and 3.4 are conditions of the licenses granted +in Section 2.1. + +3. Responsibilities +------------------- + +3.1. Distribution of Source Form + +All distribution of Covered Software in Source Code Form, including any +Modifications that You create or to which You contribute, must be under +the terms of this License. You must inform recipients that the Source +Code Form of the Covered Software is governed by the terms of this +License, and how they can obtain a copy of this License. You may not +attempt to alter or restrict the recipients' rights in the Source Code +Form. + +3.2. Distribution of Executable Form + +If You distribute Covered Software in Executable Form then: + +(a) such Covered Software must also be made available in Source Code + Form, as described in Section 3.1, and You must inform recipients of + the Executable Form how they can obtain a copy of such Source Code + Form by reasonable means in a timely manner, at a charge no more + than the cost of distribution to the recipient; and + +(b) You may distribute such Executable Form under the terms of this + License, or sublicense it under different terms, provided that the + license for the Executable Form does not attempt to limit or alter + the recipients' rights in the Source Code Form under this License. + +3.3. Distribution of a Larger Work + +You may create and distribute a Larger Work under terms of Your choice, +provided that You also comply with the requirements of this License for +the Covered Software. If the Larger Work is a combination of Covered +Software with a work governed by one or more Secondary Licenses, and the +Covered Software is not Incompatible With Secondary Licenses, this +License permits You to additionally distribute such Covered Software +under the terms of such Secondary License(s), so that the recipient of +the Larger Work may, at their option, further distribute the Covered +Software under the terms of either this License or such Secondary +License(s). + +3.4. Notices + +You may not remove or alter the substance of any license notices +(including copyright notices, patent notices, disclaimers of warranty, +or limitations of liability) contained within the Source Code Form of +the Covered Software, except that You may alter any license notices to +the extent required to remedy known factual inaccuracies. + +3.5. Application of Additional Terms + +You may choose to offer, and to charge a fee for, warranty, support, +indemnity or liability obligations to one or more recipients of Covered +Software. However, You may do so only on Your own behalf, and not on +behalf of any Contributor. You must make it absolutely clear that any +such warranty, support, indemnity, or liability obligation is offered by +You alone, and You hereby agree to indemnify every Contributor for any +liability incurred by such Contributor as a result of warranty, support, +indemnity or liability terms You offer. You may include additional +disclaimers of warranty and limitations of liability specific to any +jurisdiction. + +4. Inability to Comply Due to Statute or Regulation +--------------------------------------------------- + +If it is impossible for You to comply with any of the terms of this +License with respect to some or all of the Covered Software due to +statute, judicial order, or regulation then You must: (a) comply with +the terms of this License to the maximum extent possible; and (b) +describe the limitations and the code they affect. Such description must +be placed in a text file included with all distributions of the Covered +Software under this License. Except to the extent prohibited by statute +or regulation, such description must be sufficiently detailed for a +recipient of ordinary skill to be able to understand it. + +5. Termination +-------------- + +5.1. The rights granted under this License will terminate automatically +if You fail to comply with any of its terms. However, if You become +compliant, then the rights granted under this License from a particular +Contributor are reinstated (a) provisionally, unless and until such +Contributor explicitly and finally terminates Your grants, and (b) on an +ongoing basis, if such Contributor fails to notify You of the +non-compliance by some reasonable means prior to 60 days after You have +come back into compliance. Moreover, Your grants from a particular +Contributor are reinstated on an ongoing basis if such Contributor +notifies You of the non-compliance by some reasonable means, this is the +first time You have received notice of non-compliance with this License +from such Contributor, and You become compliant prior to 30 days after +Your receipt of the notice. + +5.2. If You initiate litigation against any entity by asserting a patent +infringement claim (excluding declaratory judgment actions, +counter-claims, and cross-claims) alleging that a Contributor Version +directly or indirectly infringes any patent, then the rights granted to +You by any and all Contributors for the Covered Software under Section +2.1 of this License shall terminate. + +5.3. In the event of termination under Sections 5.1 or 5.2 above, all +end user license agreements (excluding distributors and resellers) which +have been validly granted by You or Your distributors under this License +prior to termination shall survive termination. + +************************************************************************ +* * +* 6. Disclaimer of Warranty * +* ------------------------- * +* * +* Covered Software is provided under this License on an "as is" * +* basis, without warranty of any kind, either expressed, implied, or * +* statutory, including, without limitation, warranties that the * +* Covered Software is free of defects, merchantable, fit for a * +* particular purpose or non-infringing. The entire risk as to the * +* quality and performance of the Covered Software is with You. * +* Should any Covered Software prove defective in any respect, You * +* (not any Contributor) assume the cost of any necessary servicing, * +* repair, or correction. This disclaimer of warranty constitutes an * +* essential part of this License. No use of any Covered Software is * +* authorized under this License except under this disclaimer. * +* * +************************************************************************ + +************************************************************************ +* * +* 7. Limitation of Liability * +* -------------------------- * +* * +* Under no circumstances and under no legal theory, whether tort * +* (including negligence), contract, or otherwise, shall any * +* Contributor, or anyone who distributes Covered Software as * +* permitted above, be liable to You for any direct, indirect, * +* special, incidental, or consequential damages of any character * +* including, without limitation, damages for lost profits, loss of * +* goodwill, work stoppage, computer failure or malfunction, or any * +* and all other commercial damages or losses, even if such party * +* shall have been informed of the possibility of such damages. This * +* limitation of liability shall not apply to liability for death or * +* personal injury resulting from such party's negligence to the * +* extent applicable law prohibits such limitation. Some * +* jurisdictions do not allow the exclusion or limitation of * +* incidental or consequential damages, so this exclusion and * +* limitation may not apply to You. * +* * +************************************************************************ + +8. Litigation +------------- + +Any litigation relating to this License may be brought only in the +courts of a jurisdiction where the defendant maintains its principal +place of business and such litigation shall be governed by laws of that +jurisdiction, without reference to its conflict-of-law provisions. +Nothing in this Section shall prevent a party's ability to bring +cross-claims or counter-claims. + +9. Miscellaneous +---------------- + +This License represents the complete agreement concerning the subject +matter hereof. If any provision of this License is held to be +unenforceable, such provision shall be reformed only to the extent +necessary to make it enforceable. Any law or regulation which provides +that the language of a contract shall be construed against the drafter +shall not be used to construe this License against a Contributor. + +10. Versions of the License +--------------------------- + +10.1. New Versions + +Mozilla Foundation is the license steward. Except as provided in Section +10.3, no one other than the license steward has the right to modify or +publish new versions of this License. Each version will be given a +distinguishing version number. + +10.2. Effect of New Versions + +You may distribute the Covered Software under the terms of the version +of the License under which You originally received the Covered Software, +or under the terms of any subsequent version published by the license +steward. + +10.3. Modified Versions + +If you create software not governed by this License, and you want to +create a new license for such software, you may create and use a +modified version of this License if you rename the license and remove +any references to the name of the license steward (except to note that +such modified license differs from this License). + +10.4. Distributing Source Code Form that is Incompatible With Secondary +Licenses + +If You choose to distribute Source Code Form that is Incompatible With +Secondary Licenses under the terms of this version of the License, the +notice described in Exhibit B of this License must be attached. + +Exhibit A - Source Code Form License Notice +------------------------------------------- + + This Source Code Form is subject to the terms of the Mozilla Public + License, v. 2.0. If a copy of the MPL was not distributed with this + file, You can obtain one at http://mozilla.org/MPL/2.0/. + +If it is not possible or desirable to put the notice in a particular +file, then You may include the notice in a location (such as a LICENSE +file in a relevant directory) where a recipient would be likely to look +for such a notice. + +You may add additional accurate notices of copyright ownership. + +Exhibit B - "Incompatible With Secondary Licenses" Notice +--------------------------------------------------------- + + This Source Code Form is "Incompatible With Secondary Licenses", as + defined by the Mozilla Public License, v. 2.0. + +Generated by CocoaPods - https://cocoapods.org diff --git a/Pods/Target Support Files/Pods-Giphy Search/Pods-Giphy Search-acknowledgements.plist b/Pods/Target Support Files/Pods-Giphy Search/Pods-Giphy Search-acknowledgements.plist new file mode 100644 index 0000000..cf3b45b --- /dev/null +++ b/Pods/Target Support Files/Pods-Giphy Search/Pods-Giphy Search-acknowledgements.plist @@ -0,0 +1,470 @@ + + + + + PreferenceSpecifiers + + + FooterText + This application makes use of the following third party libraries: + Title + Acknowledgements + Type + PSGroupSpecifier + + + FooterText + Copyright (c) 2014-2018 Alamofire Software Foundation (http://alamofire.org/) + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in +all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN +THE SOFTWARE. + + License + MIT + Title + Alamofire + Type + PSGroupSpecifier + + + FooterText + Copyright (c) 2015-2018 Alamofire Software Foundation (http://alamofire.org/) + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in +all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN +THE SOFTWARE. + + License + MIT + Title + AlamofireImage + Type + PSGroupSpecifier + + + FooterText + Mozilla Public License Version 2.0 +================================== + +1. Definitions +-------------- + +1.1. "Contributor" + means each individual or legal entity that creates, contributes to + the creation of, or owns Covered Software. + +1.2. "Contributor Version" + means the combination of the Contributions of others (if any) used + by a Contributor and that particular Contributor's Contribution. + +1.3. "Contribution" + means Covered Software of a particular Contributor. + +1.4. "Covered Software" + means Source Code Form to which the initial Contributor has attached + the notice in Exhibit A, the Executable Form of such Source Code + Form, and Modifications of such Source Code Form, in each case + including portions thereof. + +1.5. "Incompatible With Secondary Licenses" + means + + (a) that the initial Contributor has attached the notice described + in Exhibit B to the Covered Software; or + + (b) that the Covered Software was made available under the terms of + version 1.1 or earlier of the License, but not also under the + terms of a Secondary License. + +1.6. "Executable Form" + means any form of the work other than Source Code Form. + +1.7. "Larger Work" + means a work that combines Covered Software with other material, in + a separate file or files, that is not Covered Software. + +1.8. "License" + means this document. + +1.9. "Licensable" + means having the right to grant, to the maximum extent possible, + whether at the time of the initial grant or subsequently, any and + all of the rights conveyed by this License. + +1.10. "Modifications" + means any of the following: + + (a) any file in Source Code Form that results from an addition to, + deletion from, or modification of the contents of Covered + Software; or + + (b) any new file in Source Code Form that contains any Covered + Software. + +1.11. "Patent Claims" of a Contributor + means any patent claim(s), including without limitation, method, + process, and apparatus claims, in any patent Licensable by such + Contributor that would be infringed, but for the grant of the + License, by the making, using, selling, offering for sale, having + made, import, or transfer of either its Contributions or its + Contributor Version. + +1.12. "Secondary License" + means either the GNU General Public License, Version 2.0, the GNU + Lesser General Public License, Version 2.1, the GNU Affero General + Public License, Version 3.0, or any later versions of those + licenses. + +1.13. "Source Code Form" + means the form of the work preferred for making modifications. + +1.14. "You" (or "Your") + means an individual or a legal entity exercising rights under this + License. For legal entities, "You" includes any entity that + controls, is controlled by, or is under common control with You. For + purposes of this definition, "control" means (a) the power, direct + or indirect, to cause the direction or management of such entity, + whether by contract or otherwise, or (b) ownership of more than + fifty percent (50%) of the outstanding shares or beneficial + ownership of such entity. + +2. License Grants and Conditions +-------------------------------- + +2.1. Grants + +Each Contributor hereby grants You a world-wide, royalty-free, +non-exclusive license: + +(a) under intellectual property rights (other than patent or trademark) + Licensable by such Contributor to use, reproduce, make available, + modify, display, perform, distribute, and otherwise exploit its + Contributions, either on an unmodified basis, with Modifications, or + as part of a Larger Work; and + +(b) under Patent Claims of such Contributor to make, use, sell, offer + for sale, have made, import, and otherwise transfer either its + Contributions or its Contributor Version. + +2.2. Effective Date + +The licenses granted in Section 2.1 with respect to any Contribution +become effective for each Contribution on the date the Contributor first +distributes such Contribution. + +2.3. Limitations on Grant Scope + +The licenses granted in this Section 2 are the only rights granted under +this License. No additional rights or licenses will be implied from the +distribution or licensing of Covered Software under this License. +Notwithstanding Section 2.1(b) above, no patent license is granted by a +Contributor: + +(a) for any code that a Contributor has removed from Covered Software; + or + +(b) for infringements caused by: (i) Your and any other third party's + modifications of Covered Software, or (ii) the combination of its + Contributions with other software (except as part of its Contributor + Version); or + +(c) under Patent Claims infringed by Covered Software in the absence of + its Contributions. + +This License does not grant any rights in the trademarks, service marks, +or logos of any Contributor (except as may be necessary to comply with +the notice requirements in Section 3.4). + +2.4. Subsequent Licenses + +No Contributor makes additional grants as a result of Your choice to +distribute the Covered Software under a subsequent version of this +License (see Section 10.2) or under the terms of a Secondary License (if +permitted under the terms of Section 3.3). + +2.5. Representation + +Each Contributor represents that the Contributor believes its +Contributions are its original creation(s) or it has sufficient rights +to grant the rights to its Contributions conveyed by this License. + +2.6. Fair Use + +This License is not intended to limit any rights You have under +applicable copyright doctrines of fair use, fair dealing, or other +equivalents. + +2.7. Conditions + +Sections 3.1, 3.2, 3.3, and 3.4 are conditions of the licenses granted +in Section 2.1. + +3. Responsibilities +------------------- + +3.1. Distribution of Source Form + +All distribution of Covered Software in Source Code Form, including any +Modifications that You create or to which You contribute, must be under +the terms of this License. You must inform recipients that the Source +Code Form of the Covered Software is governed by the terms of this +License, and how they can obtain a copy of this License. You may not +attempt to alter or restrict the recipients' rights in the Source Code +Form. + +3.2. Distribution of Executable Form + +If You distribute Covered Software in Executable Form then: + +(a) such Covered Software must also be made available in Source Code + Form, as described in Section 3.1, and You must inform recipients of + the Executable Form how they can obtain a copy of such Source Code + Form by reasonable means in a timely manner, at a charge no more + than the cost of distribution to the recipient; and + +(b) You may distribute such Executable Form under the terms of this + License, or sublicense it under different terms, provided that the + license for the Executable Form does not attempt to limit or alter + the recipients' rights in the Source Code Form under this License. + +3.3. Distribution of a Larger Work + +You may create and distribute a Larger Work under terms of Your choice, +provided that You also comply with the requirements of this License for +the Covered Software. If the Larger Work is a combination of Covered +Software with a work governed by one or more Secondary Licenses, and the +Covered Software is not Incompatible With Secondary Licenses, this +License permits You to additionally distribute such Covered Software +under the terms of such Secondary License(s), so that the recipient of +the Larger Work may, at their option, further distribute the Covered +Software under the terms of either this License or such Secondary +License(s). + +3.4. Notices + +You may not remove or alter the substance of any license notices +(including copyright notices, patent notices, disclaimers of warranty, +or limitations of liability) contained within the Source Code Form of +the Covered Software, except that You may alter any license notices to +the extent required to remedy known factual inaccuracies. + +3.5. Application of Additional Terms + +You may choose to offer, and to charge a fee for, warranty, support, +indemnity or liability obligations to one or more recipients of Covered +Software. However, You may do so only on Your own behalf, and not on +behalf of any Contributor. You must make it absolutely clear that any +such warranty, support, indemnity, or liability obligation is offered by +You alone, and You hereby agree to indemnify every Contributor for any +liability incurred by such Contributor as a result of warranty, support, +indemnity or liability terms You offer. You may include additional +disclaimers of warranty and limitations of liability specific to any +jurisdiction. + +4. Inability to Comply Due to Statute or Regulation +--------------------------------------------------- + +If it is impossible for You to comply with any of the terms of this +License with respect to some or all of the Covered Software due to +statute, judicial order, or regulation then You must: (a) comply with +the terms of this License to the maximum extent possible; and (b) +describe the limitations and the code they affect. Such description must +be placed in a text file included with all distributions of the Covered +Software under this License. Except to the extent prohibited by statute +or regulation, such description must be sufficiently detailed for a +recipient of ordinary skill to be able to understand it. + +5. Termination +-------------- + +5.1. The rights granted under this License will terminate automatically +if You fail to comply with any of its terms. However, if You become +compliant, then the rights granted under this License from a particular +Contributor are reinstated (a) provisionally, unless and until such +Contributor explicitly and finally terminates Your grants, and (b) on an +ongoing basis, if such Contributor fails to notify You of the +non-compliance by some reasonable means prior to 60 days after You have +come back into compliance. Moreover, Your grants from a particular +Contributor are reinstated on an ongoing basis if such Contributor +notifies You of the non-compliance by some reasonable means, this is the +first time You have received notice of non-compliance with this License +from such Contributor, and You become compliant prior to 30 days after +Your receipt of the notice. + +5.2. If You initiate litigation against any entity by asserting a patent +infringement claim (excluding declaratory judgment actions, +counter-claims, and cross-claims) alleging that a Contributor Version +directly or indirectly infringes any patent, then the rights granted to +You by any and all Contributors for the Covered Software under Section +2.1 of this License shall terminate. + +5.3. In the event of termination under Sections 5.1 or 5.2 above, all +end user license agreements (excluding distributors and resellers) which +have been validly granted by You or Your distributors under this License +prior to termination shall survive termination. + +************************************************************************ +* * +* 6. Disclaimer of Warranty * +* ------------------------- * +* * +* Covered Software is provided under this License on an "as is" * +* basis, without warranty of any kind, either expressed, implied, or * +* statutory, including, without limitation, warranties that the * +* Covered Software is free of defects, merchantable, fit for a * +* particular purpose or non-infringing. The entire risk as to the * +* quality and performance of the Covered Software is with You. * +* Should any Covered Software prove defective in any respect, You * +* (not any Contributor) assume the cost of any necessary servicing, * +* repair, or correction. This disclaimer of warranty constitutes an * +* essential part of this License. No use of any Covered Software is * +* authorized under this License except under this disclaimer. * +* * +************************************************************************ + +************************************************************************ +* * +* 7. Limitation of Liability * +* -------------------------- * +* * +* Under no circumstances and under no legal theory, whether tort * +* (including negligence), contract, or otherwise, shall any * +* Contributor, or anyone who distributes Covered Software as * +* permitted above, be liable to You for any direct, indirect, * +* special, incidental, or consequential damages of any character * +* including, without limitation, damages for lost profits, loss of * +* goodwill, work stoppage, computer failure or malfunction, or any * +* and all other commercial damages or losses, even if such party * +* shall have been informed of the possibility of such damages. This * +* limitation of liability shall not apply to liability for death or * +* personal injury resulting from such party's negligence to the * +* extent applicable law prohibits such limitation. Some * +* jurisdictions do not allow the exclusion or limitation of * +* incidental or consequential damages, so this exclusion and * +* limitation may not apply to You. * +* * +************************************************************************ + +8. Litigation +------------- + +Any litigation relating to this License may be brought only in the +courts of a jurisdiction where the defendant maintains its principal +place of business and such litigation shall be governed by laws of that +jurisdiction, without reference to its conflict-of-law provisions. +Nothing in this Section shall prevent a party's ability to bring +cross-claims or counter-claims. + +9. Miscellaneous +---------------- + +This License represents the complete agreement concerning the subject +matter hereof. If any provision of this License is held to be +unenforceable, such provision shall be reformed only to the extent +necessary to make it enforceable. Any law or regulation which provides +that the language of a contract shall be construed against the drafter +shall not be used to construe this License against a Contributor. + +10. Versions of the License +--------------------------- + +10.1. New Versions + +Mozilla Foundation is the license steward. Except as provided in Section +10.3, no one other than the license steward has the right to modify or +publish new versions of this License. Each version will be given a +distinguishing version number. + +10.2. Effect of New Versions + +You may distribute the Covered Software under the terms of the version +of the License under which You originally received the Covered Software, +or under the terms of any subsequent version published by the license +steward. + +10.3. Modified Versions + +If you create software not governed by this License, and you want to +create a new license for such software, you may create and use a +modified version of this License if you rename the license and remove +any references to the name of the license steward (except to note that +such modified license differs from this License). + +10.4. Distributing Source Code Form that is Incompatible With Secondary +Licenses + +If You choose to distribute Source Code Form that is Incompatible With +Secondary Licenses under the terms of this version of the License, the +notice described in Exhibit B of this License must be attached. + +Exhibit A - Source Code Form License Notice +------------------------------------------- + + This Source Code Form is subject to the terms of the Mozilla Public + License, v. 2.0. If a copy of the MPL was not distributed with this + file, You can obtain one at http://mozilla.org/MPL/2.0/. + +If it is not possible or desirable to put the notice in a particular +file, then You may include the notice in a location (such as a LICENSE +file in a relevant directory) where a recipient would be likely to look +for such a notice. + +You may add additional accurate notices of copyright ownership. + +Exhibit B - "Incompatible With Secondary Licenses" Notice +--------------------------------------------------------- + + This Source Code Form is "Incompatible With Secondary Licenses", as + defined by the Mozilla Public License, v. 2.0. + + License + Mozilla Public License v2 + Title + GiphyCoreSDK + Type + PSGroupSpecifier + + + FooterText + Generated by CocoaPods - https://cocoapods.org + Title + + Type + PSGroupSpecifier + + + StringsTable + Acknowledgements + Title + Acknowledgements + + diff --git a/Pods/Target Support Files/Pods-Giphy Search/Pods-Giphy Search-dummy.m b/Pods/Target Support Files/Pods-Giphy Search/Pods-Giphy Search-dummy.m new file mode 100644 index 0000000..24c8581 --- /dev/null +++ b/Pods/Target Support Files/Pods-Giphy Search/Pods-Giphy Search-dummy.m @@ -0,0 +1,5 @@ +#import +@interface PodsDummy_Pods_Giphy_Search : NSObject +@end +@implementation PodsDummy_Pods_Giphy_Search +@end diff --git a/Pods/Target Support Files/Pods-Giphy Search/Pods-Giphy Search-frameworks.sh b/Pods/Target Support Files/Pods-Giphy Search/Pods-Giphy Search-frameworks.sh new file mode 100755 index 0000000..1657e59 --- /dev/null +++ b/Pods/Target Support Files/Pods-Giphy Search/Pods-Giphy Search-frameworks.sh @@ -0,0 +1,157 @@ +#!/bin/sh +set -e +set -u +set -o pipefail + +if [ -z ${FRAMEWORKS_FOLDER_PATH+x} ]; then + # If FRAMEWORKS_FOLDER_PATH is not set, then there's nowhere for us to copy + # frameworks to, so exit 0 (signalling the script phase was successful). + exit 0 +fi + +echo "mkdir -p ${CONFIGURATION_BUILD_DIR}/${FRAMEWORKS_FOLDER_PATH}" +mkdir -p "${CONFIGURATION_BUILD_DIR}/${FRAMEWORKS_FOLDER_PATH}" + +COCOAPODS_PARALLEL_CODE_SIGN="${COCOAPODS_PARALLEL_CODE_SIGN:-false}" +SWIFT_STDLIB_PATH="${DT_TOOLCHAIN_DIR}/usr/lib/swift/${PLATFORM_NAME}" + +# Used as a return value for each invocation of `strip_invalid_archs` function. +STRIP_BINARY_RETVAL=0 + +# This protects against multiple targets copying the same framework dependency at the same time. The solution +# was originally proposed here: https://lists.samba.org/archive/rsync/2008-February/020158.html +RSYNC_PROTECT_TMP_FILES=(--filter "P .*.??????") + +# Copies and strips a vendored framework +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 don't throw errors. + echo "rsync --delete -av "${RSYNC_PROTECT_TMP_FILES[@]}" --filter \"- CVS/\" --filter \"- .svn/\" --filter \"- .git/\" --filter \"- .hg/\" --filter \"- Headers\" --filter \"- PrivateHeaders\" --filter \"- Modules\" \"${source}\" \"${destination}\"" + rsync --delete -av "${RSYNC_PROTECT_TMP_FILES[@]}" --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 +} + +# Copies and strips a vendored dSYM +install_dsym() { + local source="$1" + if [ -r "$source" ]; then + # Copy the dSYM into a the targets temp dir. + echo "rsync --delete -av "${RSYNC_PROTECT_TMP_FILES[@]}" --filter \"- CVS/\" --filter \"- .svn/\" --filter \"- .git/\" --filter \"- .hg/\" --filter \"- Headers\" --filter \"- PrivateHeaders\" --filter \"- Modules\" \"${source}\" \"${DERIVED_FILES_DIR}\"" + rsync --delete -av "${RSYNC_PROTECT_TMP_FILES[@]}" --filter "- CVS/" --filter "- .svn/" --filter "- .git/" --filter "- .hg/" --filter "- Headers" --filter "- PrivateHeaders" --filter "- Modules" "${source}" "${DERIVED_FILES_DIR}" + + local basename + basename="$(basename -s .framework.dSYM "$source")" + binary="${DERIVED_FILES_DIR}/${basename}.framework.dSYM/Contents/Resources/DWARF/${basename}" + + # Strip invalid architectures so "fat" simulator / device frameworks work on device + if [[ "$(file "$binary")" == *"Mach-O dSYM companion"* ]]; then + strip_invalid_archs "$binary" + fi + + if [[ $STRIP_BINARY_RETVAL == 1 ]]; then + # Move the stripped file into its final destination. + echo "rsync --delete -av "${RSYNC_PROTECT_TMP_FILES[@]}" --filter \"- CVS/\" --filter \"- .svn/\" --filter \"- .git/\" --filter \"- .hg/\" --filter \"- Headers\" --filter \"- PrivateHeaders\" --filter \"- Modules\" \"${DERIVED_FILES_DIR}/${basename}.framework.dSYM\" \"${DWARF_DSYM_FOLDER_PATH}\"" + rsync --delete -av "${RSYNC_PROTECT_TMP_FILES[@]}" --filter "- CVS/" --filter "- .svn/" --filter "- .git/" --filter "- .hg/" --filter "- Headers" --filter "- PrivateHeaders" --filter "- Modules" "${DERIVED_FILES_DIR}/${basename}.framework.dSYM" "${DWARF_DSYM_FOLDER_PATH}" + else + # The dSYM was not stripped at all, in this case touch a fake folder so the input/output paths from Xcode do not reexecute this script because the file is missing. + touch "${DWARF_DSYM_FOLDER_PATH}/${basename}.framework.dSYM" + fi + 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 target binary + binary_archs="$(lipo -info "$binary" | rev | cut -d ':' -f1 | awk '{$1=$1;print}' | rev)" + # Intersect them with the architectures we are building for + intersected_archs="$(echo ${ARCHS[@]} ${binary_archs[@]} | tr ' ' '\n' | sort | uniq -d)" + # If there are no archs supported by this binary then warn the user + if [[ -z "$intersected_archs" ]]; then + echo "warning: [CP] Vendored binary '$binary' contains architectures ($binary_archs) none of which match the current build architectures ($ARCHS)." + STRIP_BINARY_RETVAL=0 + return + fi + stripped="" + for arch in $binary_archs; do + if ! [[ "${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 + STRIP_BINARY_RETVAL=1 +} + + +if [[ "$CONFIGURATION" == "Debug" ]]; then + install_framework "${BUILT_PRODUCTS_DIR}/Alamofire/Alamofire.framework" + install_framework "${BUILT_PRODUCTS_DIR}/AlamofireImage/AlamofireImage.framework" + install_framework "${BUILT_PRODUCTS_DIR}/GiphyCoreSDK/GiphyCoreSDK.framework" +fi +if [[ "$CONFIGURATION" == "Release" ]]; then + install_framework "${BUILT_PRODUCTS_DIR}/Alamofire/Alamofire.framework" + install_framework "${BUILT_PRODUCTS_DIR}/AlamofireImage/AlamofireImage.framework" + install_framework "${BUILT_PRODUCTS_DIR}/GiphyCoreSDK/GiphyCoreSDK.framework" +fi +if [ "${COCOAPODS_PARALLEL_CODE_SIGN}" == "true" ]; then + wait +fi diff --git a/Pods/Target Support Files/Pods-Giphy Search/Pods-Giphy Search-resources.sh b/Pods/Target Support Files/Pods-Giphy Search/Pods-Giphy Search-resources.sh new file mode 100755 index 0000000..345301f --- /dev/null +++ b/Pods/Target Support Files/Pods-Giphy Search/Pods-Giphy Search-resources.sh @@ -0,0 +1,118 @@ +#!/bin/sh +set -e +set -u +set -o pipefail + +if [ -z ${UNLOCALIZED_RESOURCES_FOLDER_PATH+x} ]; then + # If UNLOCALIZED_RESOURCES_FOLDER_PATH is not set, then there's nowhere for us to copy + # resources to, so exit 0 (signalling the script phase was successful). + exit 0 +fi + +mkdir -p "${TARGET_BUILD_DIR}/${UNLOCALIZED_RESOURCES_FOLDER_PATH}" + +RESOURCES_TO_COPY=${PODS_ROOT}/resources-to-copy-${TARGETNAME}.txt +> "$RESOURCES_TO_COPY" + +XCASSET_FILES=() + +# This protects against multiple targets copying the same framework dependency at the same time. The solution +# was originally proposed here: https://lists.samba.org/archive/rsync/2008-February/020158.html +RSYNC_PROTECT_TMP_FILES=(--filter "P .*.??????") + +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" + ;; + 4) + TARGET_DEVICE_ARGS="--target-device watch" + ;; + *) + 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}" || true + 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}" || true + 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}" || true + mkdir -p "${TARGET_BUILD_DIR}/${FRAMEWORKS_FOLDER_PATH}" + echo "rsync --delete -av "${RSYNC_PROTECT_TMP_FILES[@]}" $RESOURCE_PATH ${TARGET_BUILD_DIR}/${FRAMEWORKS_FOLDER_PATH}" || true + rsync --delete -av "${RSYNC_PROTECT_TMP_FILES[@]}" "$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\"" || true + 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\"" || true + 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\"" || true + 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" || true + 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" + + if [ -z ${ASSETCATALOG_COMPILER_APPICON_NAME+x} ]; then + 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}" + else + 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}" --app-icon "${ASSETCATALOG_COMPILER_APPICON_NAME}" --output-partial-info-plist "${TARGET_TEMP_DIR}/assetcatalog_generated_info_cocoapods.plist" + fi +fi diff --git a/Pods/Target Support Files/Pods-Giphy Search/Pods-Giphy Search-umbrella.h b/Pods/Target Support Files/Pods-Giphy Search/Pods-Giphy Search-umbrella.h new file mode 100644 index 0000000..f3513d6 --- /dev/null +++ b/Pods/Target Support Files/Pods-Giphy Search/Pods-Giphy Search-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_Giphy_SearchVersionNumber; +FOUNDATION_EXPORT const unsigned char Pods_Giphy_SearchVersionString[]; + diff --git a/Pods/Target Support Files/Pods-Giphy Search/Pods-Giphy Search.debug.xcconfig b/Pods/Target Support Files/Pods-Giphy Search/Pods-Giphy Search.debug.xcconfig new file mode 100644 index 0000000..1712e97 --- /dev/null +++ b/Pods/Target Support Files/Pods-Giphy Search/Pods-Giphy Search.debug.xcconfig @@ -0,0 +1,11 @@ +ALWAYS_EMBED_SWIFT_STANDARD_LIBRARIES = YES +FRAMEWORK_SEARCH_PATHS = $(inherited) "${PODS_CONFIGURATION_BUILD_DIR}/Alamofire" "${PODS_CONFIGURATION_BUILD_DIR}/AlamofireImage" "${PODS_CONFIGURATION_BUILD_DIR}/GiphyCoreSDK" +GCC_PREPROCESSOR_DEFINITIONS = $(inherited) COCOAPODS=1 +LD_RUNPATH_SEARCH_PATHS = $(inherited) '@executable_path/Frameworks' '@loader_path/Frameworks' +OTHER_CFLAGS = $(inherited) -iquote "${PODS_CONFIGURATION_BUILD_DIR}/Alamofire/Alamofire.framework/Headers" -iquote "${PODS_CONFIGURATION_BUILD_DIR}/AlamofireImage/AlamofireImage.framework/Headers" -iquote "${PODS_CONFIGURATION_BUILD_DIR}/GiphyCoreSDK/GiphyCoreSDK.framework/Headers" +OTHER_LDFLAGS = $(inherited) -framework "Alamofire" -framework "AlamofireImage" -framework "GiphyCoreSDK" +OTHER_SWIFT_FLAGS = $(inherited) "-D" "COCOAPODS" +PODS_BUILD_DIR = ${BUILD_DIR} +PODS_CONFIGURATION_BUILD_DIR = ${PODS_BUILD_DIR}/$(CONFIGURATION)$(EFFECTIVE_PLATFORM_NAME) +PODS_PODFILE_DIR_PATH = ${SRCROOT}/. +PODS_ROOT = ${SRCROOT}/Pods diff --git a/Pods/Target Support Files/Pods-Giphy Search/Pods-Giphy Search.modulemap b/Pods/Target Support Files/Pods-Giphy Search/Pods-Giphy Search.modulemap new file mode 100644 index 0000000..b2035ae --- /dev/null +++ b/Pods/Target Support Files/Pods-Giphy Search/Pods-Giphy Search.modulemap @@ -0,0 +1,6 @@ +framework module Pods_Giphy_Search { + umbrella header "Pods-Giphy Search-umbrella.h" + + export * + module * { export * } +} diff --git a/Pods/Target Support Files/Pods-Giphy Search/Pods-Giphy Search.release.xcconfig b/Pods/Target Support Files/Pods-Giphy Search/Pods-Giphy Search.release.xcconfig new file mode 100644 index 0000000..1712e97 --- /dev/null +++ b/Pods/Target Support Files/Pods-Giphy Search/Pods-Giphy Search.release.xcconfig @@ -0,0 +1,11 @@ +ALWAYS_EMBED_SWIFT_STANDARD_LIBRARIES = YES +FRAMEWORK_SEARCH_PATHS = $(inherited) "${PODS_CONFIGURATION_BUILD_DIR}/Alamofire" "${PODS_CONFIGURATION_BUILD_DIR}/AlamofireImage" "${PODS_CONFIGURATION_BUILD_DIR}/GiphyCoreSDK" +GCC_PREPROCESSOR_DEFINITIONS = $(inherited) COCOAPODS=1 +LD_RUNPATH_SEARCH_PATHS = $(inherited) '@executable_path/Frameworks' '@loader_path/Frameworks' +OTHER_CFLAGS = $(inherited) -iquote "${PODS_CONFIGURATION_BUILD_DIR}/Alamofire/Alamofire.framework/Headers" -iquote "${PODS_CONFIGURATION_BUILD_DIR}/AlamofireImage/AlamofireImage.framework/Headers" -iquote "${PODS_CONFIGURATION_BUILD_DIR}/GiphyCoreSDK/GiphyCoreSDK.framework/Headers" +OTHER_LDFLAGS = $(inherited) -framework "Alamofire" -framework "AlamofireImage" -framework "GiphyCoreSDK" +OTHER_SWIFT_FLAGS = $(inherited) "-D" "COCOAPODS" +PODS_BUILD_DIR = ${BUILD_DIR} +PODS_CONFIGURATION_BUILD_DIR = ${PODS_BUILD_DIR}/$(CONFIGURATION)$(EFFECTIVE_PLATFORM_NAME) +PODS_PODFILE_DIR_PATH = ${SRCROOT}/. +PODS_ROOT = ${SRCROOT}/Pods diff --git a/README.md b/README.md new file mode 100644 index 0000000..4f6e44e --- /dev/null +++ b/README.md @@ -0,0 +1,2 @@ +Please create a simple prototype app that uses the Giphy API to search for gifs and display them in a group. Would be great if you used VIPER or Clean swift +The app does not need to be perfect, but a little bit of polish goes a long way. We’re mostly interested in seeing clean separation between the business logic, presentation code, and use of Apple best practices. \ No newline at end of file