commit dc62dcf4b8a18e226b661695221b92fc445f5a00 Author: fengshuo <963787902@qq.com> Date: Wed Feb 21 21:30:13 2024 +0800 初始化 diff --git a/.gitignore b/.gitignore new file mode 100644 index 0000000..b4163eb --- /dev/null +++ b/.gitignore @@ -0,0 +1,153 @@ +# Xcode +# +# gitignore contributors: remember to update Global/Xcode.gitignore, Objective-C.gitignore & Swift.gitignore + +## Build generated +build/ +DerivedData/ + +PlanetStar.xcodeproj/xcuserdata/ +PlanetStar.xcworkspace/ + +*.swp +PlanetStar.xcodeproj/project.xcworkspace/xcuserdata/ + +## 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 + +# 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/ + +# 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 +fastlane/test_output + +# Code Injection +# +# After new code Injection tools there's a generated folder /iOSInjectionProject +# https://github.com/johnno1962/injectionforxcode + +iOSInjectionProject/ + + + +# Compiled class file +*.class + +# Log file +*.log + +# BlueJ files +*.ctxt + +# Mobile Tools for Java (J2ME) +.mtj.tmp/ + +# Package Files # +*.war +*.ear +*.zip +*.tar.gz +*.rar + +# virtual machine crash logs, see http://www.java.com/en/download/help/error_hotspot.xml +hs_err_pid* + + + +# Built application files +*.apk +*.ap_ + +# Files for the ART/Dalvik VM +*.dex + +# Java class files +*.class + +# Generated files +bin/ +gen/ +out/ + +# Gradle files +.gradle/ +build/ + +# Local configuration file (sdk path, etc) +local.properties + +# Proguard folder generated by Eclipse +proguard/ + +# Log Files +*.log + +# Android Studio Navigation editor temp files +.navigation/ + +# Android Studio captures folder +captures/ + +# Intellij +*.iml +build/ +.idea/ +.gradle/ +local.properties + +# Keystore files + +# External native build folder generated in Android Studio 2.2 and later +.externalNativeBuild + +# Google Services (e.g. APIs or Firebase) +google-services.json + +# Freeline +freeline.py +freeline/ +freeline_project_description.json +iOS/Podfile.lock +Podfile.lock +*/.DS_Store +.DS_Store diff --git a/Podfile b/Podfile new file mode 100644 index 0000000..8d7563d --- /dev/null +++ b/Podfile @@ -0,0 +1,20 @@ +# Uncomment the next line to define a global platform for your project +platform :ios, '13.0' +source 'https://mirrors.tuna.tsinghua.edu.cn/git/CocoaPods/Specs.git' +target 'yinmeng-ios' do + # Comment the next line if you don't want to use dynamic frameworks + use_frameworks! + pod 'RxCocoa' + pod 'RxSwift' + pod 'HandyJSON' + pod 'Moya' + pod 'MBProgressHUD' + #加载图片 + pod 'Kingfisher' + #cell + pod 'Reusable' + #约束 + pod 'SnapKit', '~> 5.6.0' + # Pods for yinmeng-ios + +end diff --git a/Podfile.lock b/Podfile.lock new file mode 100644 index 0000000..ce84de4 --- /dev/null +++ b/Podfile.lock @@ -0,0 +1,60 @@ +PODS: + - Alamofire (5.7.1) + - HandyJSON (5.0.2) + - Kingfisher (7.10.2) + - MBProgressHUD (1.2.0) + - Moya (15.0.0): + - Moya/Core (= 15.0.0) + - Moya/Core (15.0.0): + - Alamofire (~> 5.0) + - Reusable (4.1.2): + - Reusable/Storyboard (= 4.1.2) + - Reusable/View (= 4.1.2) + - Reusable/Storyboard (4.1.2) + - Reusable/View (4.1.2) + - RxCocoa (6.5.0): + - RxRelay (= 6.5.0) + - RxSwift (= 6.5.0) + - RxRelay (6.5.0): + - RxSwift (= 6.5.0) + - RxSwift (6.5.0) + - SnapKit (5.6.0) + +DEPENDENCIES: + - HandyJSON + - Kingfisher + - MBProgressHUD + - Moya + - Reusable + - RxCocoa + - RxSwift + - SnapKit (~> 5.6.0) + +SPEC REPOS: + https://mirrors.tuna.tsinghua.edu.cn/git/CocoaPods/Specs.git: + - Alamofire + - HandyJSON + - Kingfisher + - MBProgressHUD + - Moya + - Reusable + - RxCocoa + - RxRelay + - RxSwift + - SnapKit + +SPEC CHECKSUMS: + Alamofire: 0123a34370cb170936ae79a8df46cc62b2edeb88 + HandyJSON: 9e4e236f5d2dbefad5155a77417bbea438201c03 + Kingfisher: 99edc495d3b7607e6425f0d6f6847b2abd6d716d + MBProgressHUD: 3ee5efcc380f6a79a7cc9b363dd669c5e1ae7406 + Moya: 138f0573e53411fb3dc17016add0b748dfbd78ee + Reusable: 6bae6a5e8aa793c9c441db0213c863a64bce9136 + RxCocoa: 94f817b71c07517321eb4f9ad299112ca8af743b + RxRelay: 1de1523e604c72b6c68feadedd1af3b1b4d0ecbd + RxSwift: 5710a9e6b17f3c3d6e40d6e559b9fa1e813b2ef8 + SnapKit: e01d52ebb8ddbc333eefe2132acf85c8227d9c25 + +PODFILE CHECKSUM: e291658151a1fcada5c9dd297587942ae9475225 + +COCOAPODS: 1.12.1 diff --git a/Pods/Alamofire/LICENSE b/Pods/Alamofire/LICENSE new file mode 100644 index 0000000..cae030a --- /dev/null +++ b/Pods/Alamofire/LICENSE @@ -0,0 +1,19 @@ +Copyright (c) 2014-2022 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..b0ba4d5 --- /dev/null +++ b/Pods/Alamofire/README.md @@ -0,0 +1,227 @@ +![Alamofire: Elegant Networking in Swift](https://raw.githubusercontent.com/Alamofire/Alamofire/master/Resources/AlamofireLogo.png) + +[![Swift](https://img.shields.io/badge/Swift-5.5_5.6_5.7_5.8-orange?style=flat-square)](https://img.shields.io/badge/Swift-5.5_5.6_5.7_5.8-Orange?style=flat-square) +[![Platforms](https://img.shields.io/badge/Platforms-macOS_iOS_tvOS_watchOS_Linux_Windows-yellowgreen?style=flat-square)](https://img.shields.io/badge/Platforms-macOS_iOS_tvOS_watchOS_Linux_Windows-Green?style=flat-square) +[![CocoaPods Compatible](https://img.shields.io/cocoapods/v/Alamofire.svg?style=flat-square)](https://img.shields.io/cocoapods/v/Alamofire.svg) +[![Carthage Compatible](https://img.shields.io/badge/Carthage-compatible-4BC51D.svg?style=flat-square)](https://github.com/Carthage/Carthage) +[![Swift Package Manager](https://img.shields.io/badge/Swift_Package_Manager-compatible-orange?style=flat-square)](https://img.shields.io/badge/Swift_Package_Manager-compatible-orange?style=flat-square) +[![Twitter](https://img.shields.io/badge/twitter-@AlamofireSF-blue.svg?style=flat-square)](https://twitter.com/AlamofireSF) +[![Swift Forums](https://img.shields.io/badge/Swift_Forums-Alamofire-orange?style=flat-square)](https://forums.swift.org/c/related-projects/alamofire/37) + +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) +- [Contributing](#contributing) +- [Usage](https://github.com/Alamofire/Alamofire/blob/master/Documentation/Usage.md#using-alamofire) + - [**Introduction -**](https://github.com/Alamofire/Alamofire/blob/master/Documentation/Usage.md#introduction) [Making Requests](https://github.com/Alamofire/Alamofire/blob/master/Documentation/Usage.md#making-requests), [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), [Parameters and Parameter Encoder](https://github.com/Alamofire/Alamofire/blob/master/Documentation/Usage.md##request-parameters-and-parameter-encoders), [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), [Session Delegate](https://github.com/Alamofire/Alamofire/blob/master/Documentation/AdvancedUsage.md#sessiondelegate), [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-with-requestinterceptor) + - **Model Objects -** [Custom Response Handlers](https://github.com/Alamofire/Alamofire/blob/master/Documentation/AdvancedUsage.md#customizing-response-handlers) + - **Advanced Concurrency -** [Swift Concurrency](https://github.com/Alamofire/Alamofire/blob/master/Documentation/AdvancedUsage.md#using-alamofire-with-swift-concurrency) and [Combine](https://github.com/Alamofire/Alamofire/blob/master/Documentation/AdvancedUsage.md#using-alamofire-with-combine) + - **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] Swift Concurrency Support Back to iOS 13, macOS 10.15, tvOS 13, and watchOS 6. +- [x] Combine Support +- [x] URL / JSON 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 + +| Platform | Minimum Swift Version | Installation | Status | +| --- | --- | --- | --- | +| iOS 10.0+ / macOS 10.12+ / tvOS 10.0+ / watchOS 3.0+ | 5.5 | [CocoaPods](#cocoapods), [Carthage](#carthage), [Swift Package Manager](#swift-package-manager), [Manual](#manually) | Fully Tested | +| Linux | Latest Only | [Swift Package Manager](#swift-package-manager) | Building But Unsupported | +| Windows | Latest Only | [Swift Package Manager](#swift-package-manager) | Building But Unsupported | + +#### Known Issues on Linux and Windows + +Alamofire builds on Linux and Windows but there are missing features and many issues in the underlying `swift-corelibs-foundation` that prevent full functionality and may cause crashes. These include: +- `ServerTrustManager` and associated certificate functionality is unavailable, so there is no certificate pinning and no client certificate support. +- Various methods of HTTP authentication may crash, including HTTP Basic and HTTP Digest. Crashes may occur if responses contain server challenges. +- Cache control through `CachedResponseHandler` and associated APIs is unavailable, as the underlying delegate methods aren't called. +- `URLSessionTaskMetrics` are never gathered. + +Due to these issues, Alamofire is unsupported on Linux and Windows. Please report any crashes to the [Swift bug reporter](https://bugs.swift.org). + +## Migration Guides + +- [Alamofire 5.0 Migration Guide](https://github.com/Alamofire/Alamofire/blob/master/Documentation/Alamofire%205.0%20Migration%20Guide.md) +- [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 with making network requests** using Alamofire, use [Stack Overflow](https://stackoverflow.com/questions/tagged/alamofire) and tag `alamofire`. +- If you need to **find or understand an API**, check [our documentation](http://alamofire.github.io/Alamofire/) or [Apple's documentation for `URLSession`](https://developer.apple.com/documentation/foundation/url_loading_system), on top of which Alamofire is built. +- If you need **help with an Alamofire feature**, use [our forum on swift.org](https://forums.swift.org/c/related-projects/alamofire). +- If you'd like to **discuss Alamofire 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 here on GitHub and follow the guide. The more detail the better! + +## Installation + +### CocoaPods + +[CocoaPods](https://cocoapods.org) is a dependency manager for Cocoa projects. For usage and installation instructions, visit their website. To integrate Alamofire into your Xcode project using CocoaPods, specify it in your `Podfile`: + +```ruby +pod 'Alamofire' +``` + +### Carthage + +[Carthage](https://github.com/Carthage/Carthage) is a decentralized dependency manager that builds your dependencies and provides you with binary frameworks. To integrate Alamofire into your Xcode project using Carthage, specify it in your `Cartfile`: + +```ogdl +github "Alamofire/Alamofire" +``` + +### 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. + +Once you have your Swift package set up, adding Alamofire as a dependency is as easy as adding it to the `dependencies` value of your `Package.swift`. + +```swift +dependencies: [ + .package(url: "https://github.com/Alamofire/Alamofire.git", .upToNextMajor(from: "5.6.4")) +] +``` + +### 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 macOS. + + > You can verify which one you selected by inspecting the build log for your project. The build target for `Alamofire` will be listed as `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. + +## Contributing + +Before contributing to Alamofire, please read the instructions detailed in our [contribution guide](https://github.com/Alamofire/Alamofire/blob/master/CONTRIBUTING.md). + +## 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 the test case +- `rdar://26870455` - Background URL Session Configurations do not work in the simulator +- `rdar://26849668` - Some URLProtocol APIs do not properly handle `URLRequest` + +## Resolved Radars + +The following radars have been resolved over time after being filed against the Alamofire project. + +- [`rdar://26761490`](http://www.openradar.me/radar?id=5010235949318144) - Swift string interpolation causing memory leak with common usage. + - (Resolved): 9/1/17 in Xcode 9 beta 6. +- [`rdar://36082113`](http://openradar.appspot.com/radar?id=4942308441063424) - `URLSessionTaskMetrics` failing to link on watchOS 3.0+ + - (Resolved): Just add `CFNetwork` to your linked frameworks. +- `FB7624529` - `urlSession(_:task:didFinishCollecting:)` never called on watchOS + - (Resolved): Metrics now collected on watchOS 7+. + +## 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. + +## 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. + +## Sponsorship + +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 Foundation members to gain some legal protections and also allow us to put donations to use, tax-free. +Sponsoring 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, whether once or monthly, to help us reach our goal would be greatly appreciated. + +[Sponsor Alamofire](https://github.com/sponsors/Alamofire) + +## Supporters + +[MacStadium](https://macstadium.com) provides Alamofire with a free, hosted Mac mini. + +![Powered by MacStadium](https://raw.githubusercontent.com/Alamofire/Alamofire/master/Resources/MacStadiumLogo.png) + +## 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..8cd60c7 --- /dev/null +++ b/Pods/Alamofire/Source/AFError.swift @@ -0,0 +1,870 @@ +// +// 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. +public enum AFError: Error { + /// The underlying reason the `.multipartEncodingFailed` error occurred. + public enum MultipartEncodingFailureReason { + /// The `fileURL` provided for reading an encodable body part isn't a file `URL`. + case bodyPartURLInvalid(url: URL) + /// The filename of the `fileURL` provided has either an empty `lastPathComponent` or `pathExtension. + case bodyPartFilenameInvalid(in: URL) + /// The file at the `fileURL` provided was not reachable. + case bodyPartFileNotReachable(at: URL) + /// Attempting to check the reachability of the `fileURL` provided threw an error. + case bodyPartFileNotReachableWithError(atURL: URL, error: Error) + /// The file at the `fileURL` provided is actually a directory. + case bodyPartFileIsDirectory(at: URL) + /// The size of the file at the `fileURL` provided was not returned by the system. + case bodyPartFileSizeNotAvailable(at: URL) + /// The attempt to find the size of the file at the `fileURL` provided threw an error. + case bodyPartFileSizeQueryFailedWithError(forURL: URL, error: Error) + /// An `InputStream` could not be created for the provided `fileURL`. + case bodyPartInputStreamCreationFailed(for: URL) + /// An `OutputStream` could not be created when attempting to write the encoded data to disk. + case outputStreamCreationFailed(for: URL) + /// The encoded body data could not be written to disk because a file already exists at the provided `fileURL`. + case outputStreamFileAlreadyExists(at: URL) + /// The `fileURL` provided for writing the encoded body data to disk is not a file `URL`. + case outputStreamURLInvalid(url: URL) + /// The attempt to write the encoded body data to disk failed with an underlying error. + case outputStreamWriteFailed(error: Error) + /// The attempt to read an encoded body part `InputStream` failed with underlying system error. + case inputStreamReadFailed(error: Error) + } + + /// Represents unexpected input stream length that occur when encoding the `MultipartFormData`. Instances will be + /// embedded within an `AFError.multipartEncodingFailed` `.inputStreamReadFailed` case. + public struct UnexpectedInputStreamLength: Error { + /// The expected byte count to read. + public var bytesExpected: UInt64 + /// The actual byte count read. + public var bytesRead: UInt64 + } + + /// The underlying reason the `.parameterEncodingFailed` error occurred. + public enum ParameterEncodingFailureReason { + /// The `URLRequest` did not have a `URL` to encode. + case missingURL + /// JSON serialization failed with an underlying system error during the encoding process. + case jsonEncodingFailed(error: Error) + /// Custom parameter encoding failed due to the associated `Error`. + case customEncodingFailed(error: Error) + } + + /// The underlying reason the `.parameterEncoderFailed` error occurred. + public enum ParameterEncoderFailureReason { + /// Possible missing components. + public enum RequiredComponent { + /// The `URL` was missing or unable to be extracted from the passed `URLRequest` or during encoding. + case url + /// The `HTTPMethod` could not be extracted from the passed `URLRequest`. + case httpMethod(rawValue: String) + } + + /// A `RequiredComponent` was missing during encoding. + case missingRequiredComponent(RequiredComponent) + /// The underlying encoder failed with the associated error. + case encoderFailed(error: Error) + } + + /// The underlying reason the `.responseValidationFailed` error occurred. + public enum ResponseValidationFailureReason { + /// The data file containing the server response did not exist. + case dataFileNil + /// The data file containing the server response at the associated `URL` could not be read. + case dataFileReadFailed(at: URL) + /// The response did not contain a `Content-Type` and the `acceptableContentTypes` provided did not contain a + /// wildcard type. + case missingContentType(acceptableContentTypes: [String]) + /// The response `Content-Type` did not match any type in the provided `acceptableContentTypes`. + case unacceptableContentType(acceptableContentTypes: [String], responseContentType: String) + /// The response status code was not acceptable. + case unacceptableStatusCode(code: Int) + /// Custom response validation failed due to the associated `Error`. + case customValidationFailed(error: Error) + } + + /// The underlying reason the response serialization error occurred. + public enum ResponseSerializationFailureReason { + /// The server response contained no data or the data was zero length. + case inputDataNilOrZeroLength + /// The file containing the server response did not exist. + case inputFileNil + /// The file containing the server response could not be read from the associated `URL`. + case inputFileReadFailed(at: URL) + /// String serialization failed using the provided `String.Encoding`. + case stringSerializationFailed(encoding: String.Encoding) + /// JSON serialization failed with an underlying system error. + case jsonSerializationFailed(error: Error) + /// A `DataDecoder` failed to decode the response due to the associated `Error`. + case decodingFailed(error: Error) + /// A custom response serializer failed due to the associated `Error`. + case customSerializationFailed(error: Error) + /// Generic serialization failed for an empty response that wasn't type `Empty` but instead the associated type. + case invalidEmptyResponse(type: String) + } + + #if !(os(Linux) || os(Windows)) + /// Underlying reason a server trust evaluation error occurred. + public enum ServerTrustFailureReason { + /// The output of a server trust evaluation. + public struct Output { + /// The host for which the evaluation was performed. + public let host: String + /// The `SecTrust` value which was evaluated. + public let trust: SecTrust + /// The `OSStatus` of evaluation operation. + public let status: OSStatus + /// The result of the evaluation operation. + public let result: SecTrustResultType + + /// Creates an `Output` value from the provided values. + init(_ host: String, _ trust: SecTrust, _ status: OSStatus, _ result: SecTrustResultType) { + self.host = host + self.trust = trust + self.status = status + self.result = result + } + } + + /// No `ServerTrustEvaluator` was found for the associated host. + case noRequiredEvaluator(host: String) + /// No certificates were found with which to perform the trust evaluation. + case noCertificatesFound + /// No public keys were found with which to perform the trust evaluation. + case noPublicKeysFound + /// During evaluation, application of the associated `SecPolicy` failed. + case policyApplicationFailed(trust: SecTrust, policy: SecPolicy, status: OSStatus) + /// During evaluation, setting the associated anchor certificates failed. + case settingAnchorCertificatesFailed(status: OSStatus, certificates: [SecCertificate]) + /// During evaluation, creation of the revocation policy failed. + case revocationPolicyCreationFailed + /// `SecTrust` evaluation failed with the associated `Error`, if one was produced. + case trustEvaluationFailed(error: Error?) + /// Default evaluation failed with the associated `Output`. + case defaultEvaluationFailed(output: Output) + /// Host validation failed with the associated `Output`. + case hostValidationFailed(output: Output) + /// Revocation check failed with the associated `Output` and options. + case revocationCheckFailed(output: Output, options: RevocationTrustEvaluator.Options) + /// Certificate pinning failed. + case certificatePinningFailed(host: String, trust: SecTrust, pinnedCertificates: [SecCertificate], serverCertificates: [SecCertificate]) + /// Public key pinning failed. + case publicKeyPinningFailed(host: String, trust: SecTrust, pinnedKeys: [SecKey], serverKeys: [SecKey]) + /// Custom server trust evaluation failed due to the associated `Error`. + case customEvaluationFailed(error: Error) + } + #endif + + /// The underlying reason the `.urlRequestValidationFailed` + public enum URLRequestValidationFailureReason { + /// URLRequest with GET method had body data. + case bodyDataInGETRequest(Data) + } + + /// `UploadableConvertible` threw an error in `createUploadable()`. + case createUploadableFailed(error: Error) + /// `URLRequestConvertible` threw an error in `asURLRequest()`. + case createURLRequestFailed(error: Error) + /// `SessionDelegate` threw an error while attempting to move downloaded file to destination URL. + case downloadedFileMoveFailed(error: Error, source: URL, destination: URL) + /// `Request` was explicitly cancelled. + case explicitlyCancelled + /// `URLConvertible` type failed to create a valid `URL`. + case invalidURL(url: URLConvertible) + /// Multipart form encoding failed. + case multipartEncodingFailed(reason: MultipartEncodingFailureReason) + /// `ParameterEncoding` threw an error during the encoding process. + case parameterEncodingFailed(reason: ParameterEncodingFailureReason) + /// `ParameterEncoder` threw an error while running the encoder. + case parameterEncoderFailed(reason: ParameterEncoderFailureReason) + /// `RequestAdapter` threw an error during adaptation. + case requestAdaptationFailed(error: Error) + /// `RequestRetrier` threw an error during the request retry process. + case requestRetryFailed(retryError: Error, originalError: Error) + /// Response validation failed. + case responseValidationFailed(reason: ResponseValidationFailureReason) + /// Response serialization failed. + case responseSerializationFailed(reason: ResponseSerializationFailureReason) + #if !(os(Linux) || os(Windows)) + /// `ServerTrustEvaluating` instance threw an error during trust evaluation. + case serverTrustEvaluationFailed(reason: ServerTrustFailureReason) + #endif + /// `Session` which issued the `Request` was deinitialized, most likely because its reference went out of scope. + case sessionDeinitialized + /// `Session` was explicitly invalidated, possibly with the `Error` produced by the underlying `URLSession`. + case sessionInvalidated(error: Error?) + /// `URLSessionTask` completed with error. + case sessionTaskFailed(error: Error) + /// `URLRequest` failed validation. + case urlRequestValidationFailed(reason: URLRequestValidationFailureReason) +} + +extension Error { + /// Returns the instance cast as an `AFError`. + public var asAFError: AFError? { + self as? AFError + } + + /// Returns the instance cast as an `AFError`. If casting fails, a `fatalError` with the specified `message` is thrown. + public func asAFError(orFailWith message: @autoclosure () -> String, file: StaticString = #file, line: UInt = #line) -> AFError { + guard let afError = self as? AFError else { + fatalError(message(), file: file, line: line) + } + return afError + } + + /// Casts the instance as `AFError` or returns `defaultAFError` + func asAFError(or defaultAFError: @autoclosure () -> AFError) -> AFError { + self as? AFError ?? defaultAFError() + } +} + +// MARK: - Error Booleans + +extension AFError { + /// Returns whether the instance is `.sessionDeinitialized`. + public var isSessionDeinitializedError: Bool { + if case .sessionDeinitialized = self { return true } + return false + } + + /// Returns whether the instance is `.sessionInvalidated`. + public var isSessionInvalidatedError: Bool { + if case .sessionInvalidated = self { return true } + return false + } + + /// Returns whether the instance is `.explicitlyCancelled`. + public var isExplicitlyCancelledError: Bool { + if case .explicitlyCancelled = self { return true } + return false + } + + /// Returns whether the instance is `.invalidURL`. + public var isInvalidURLError: Bool { + if case .invalidURL = self { return true } + return false + } + + /// Returns whether the instance is `.parameterEncodingFailed`. 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 instance is `.parameterEncoderFailed`. When `true`, the `underlyingError` property will + /// contain the associated value. + public var isParameterEncoderError: Bool { + if case .parameterEncoderFailed = self { return true } + return false + } + + /// Returns whether the instance is `.multipartEncodingFailed`. 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 instance is `.requestAdaptationFailed`. When `true`, the `underlyingError` property will + /// contain the associated value. + public var isRequestAdaptationError: Bool { + if case .requestAdaptationFailed = self { return true } + return false + } + + /// Returns whether the instance is `.responseValidationFailed`. When `true`, the `acceptableContentTypes`, + /// `responseContentType`, `responseCode`, and `underlyingError` properties will contain the associated values. + public var isResponseValidationError: Bool { + if case .responseValidationFailed = self { return true } + return false + } + + /// Returns whether the instance is `.responseSerializationFailed`. When `true`, the `failedStringEncoding` and + /// `underlyingError` properties will contain the associated values. + public var isResponseSerializationError: Bool { + if case .responseSerializationFailed = self { return true } + return false + } + + #if !(os(Linux) || os(Windows)) + /// Returns whether the instance is `.serverTrustEvaluationFailed`. When `true`, the `underlyingError` property will + /// contain the associated value. + public var isServerTrustEvaluationError: Bool { + if case .serverTrustEvaluationFailed = self { return true } + return false + } + #endif + + /// Returns whether the instance is `requestRetryFailed`. When `true`, the `underlyingError` property will + /// contain the associated value. + public var isRequestRetryError: Bool { + if case .requestRetryFailed = self { return true } + return false + } + + /// Returns whether the instance is `createUploadableFailed`. When `true`, the `underlyingError` property will + /// contain the associated value. + public var isCreateUploadableError: Bool { + if case .createUploadableFailed = self { return true } + return false + } + + /// Returns whether the instance is `createURLRequestFailed`. When `true`, the `underlyingError` property will + /// contain the associated value. + public var isCreateURLRequestError: Bool { + if case .createURLRequestFailed = self { return true } + return false + } + + /// Returns whether the instance is `downloadedFileMoveFailed`. When `true`, the `destination` and `underlyingError` properties will + /// contain the associated values. + public var isDownloadedFileMoveError: Bool { + if case .downloadedFileMoveFailed = self { return true } + return false + } + + /// Returns whether the instance is `createURLRequestFailed`. When `true`, the `underlyingError` property will + /// contain the associated value. + public var isSessionTaskError: Bool { + if case .sessionTaskFailed = self { return true } + return false + } +} + +// MARK: - Convenience Properties + +extension AFError { + /// The `URLConvertible` associated with the error. + public var urlConvertible: URLConvertible? { + guard case let .invalidURL(url) = self else { return nil } + return url + } + + /// The `URL` associated with the error. + public var url: URL? { + guard case let .multipartEncodingFailed(reason) = self else { return nil } + return reason.url + } + + /// The underlying `Error` responsible for generating the failure associated with `.sessionInvalidated`, + /// `.parameterEncodingFailed`, `.parameterEncoderFailed`, `.multipartEncodingFailed`, `.requestAdaptationFailed`, + /// `.responseSerializationFailed`, `.requestRetryFailed` errors. + public var underlyingError: Error? { + switch self { + case let .multipartEncodingFailed(reason): + return reason.underlyingError + case let .parameterEncodingFailed(reason): + return reason.underlyingError + case let .parameterEncoderFailed(reason): + return reason.underlyingError + case let .requestAdaptationFailed(error): + return error + case let .requestRetryFailed(retryError, _): + return retryError + case let .responseValidationFailed(reason): + return reason.underlyingError + case let .responseSerializationFailed(reason): + return reason.underlyingError + #if !(os(Linux) || os(Windows)) + case let .serverTrustEvaluationFailed(reason): + return reason.underlyingError + #endif + case let .sessionInvalidated(error): + return error + case let .createUploadableFailed(error): + return error + case let .createURLRequestFailed(error): + return error + case let .downloadedFileMoveFailed(error, _, _): + return error + case let .sessionTaskFailed(error): + return error + case .explicitlyCancelled, + .invalidURL, + .sessionDeinitialized, + .urlRequestValidationFailed: + return nil + } + } + + /// The acceptable `Content-Type`s of a `.responseValidationFailed` error. + public var acceptableContentTypes: [String]? { + guard case let .responseValidationFailed(reason) = self else { return nil } + return reason.acceptableContentTypes + } + + /// The response `Content-Type` of a `.responseValidationFailed` error. + public var responseContentType: String? { + guard case let .responseValidationFailed(reason) = self else { return nil } + return reason.responseContentType + } + + /// The response code of a `.responseValidationFailed` error. + public var responseCode: Int? { + guard case let .responseValidationFailed(reason) = self else { return nil } + return reason.responseCode + } + + /// The `String.Encoding` associated with a failed `.stringResponse()` call. + public var failedStringEncoding: String.Encoding? { + guard case let .responseSerializationFailed(reason) = self else { return nil } + return reason.failedStringEncoding + } + + /// The `source` URL of a `.downloadedFileMoveFailed` error. + public var sourceURL: URL? { + guard case let .downloadedFileMoveFailed(_, source, _) = self else { return nil } + return source + } + + /// The `destination` URL of a `.downloadedFileMoveFailed` error. + public var destinationURL: URL? { + guard case let .downloadedFileMoveFailed(_, _, destination) = self else { return nil } + return destination + } + + #if !(os(Linux) || os(Windows)) + /// The download resume data of any underlying network error. Only produced by `DownloadRequest`s. + public var downloadResumeData: Data? { + (underlyingError as? URLError)?.userInfo[NSURLSessionDownloadTaskResumeData] as? Data + } + #endif +} + +extension AFError.ParameterEncodingFailureReason { + var underlyingError: Error? { + switch self { + case let .jsonEncodingFailed(error), + let .customEncodingFailed(error): + return error + case .missingURL: + return nil + } + } +} + +extension AFError.ParameterEncoderFailureReason { + var underlyingError: Error? { + switch self { + case let .encoderFailed(error): + return error + case .missingRequiredComponent: + return nil + } + } +} + +extension AFError.MultipartEncodingFailureReason { + var url: URL? { + switch self { + case let .bodyPartURLInvalid(url), + let .bodyPartFilenameInvalid(url), + let .bodyPartFileNotReachable(url), + let .bodyPartFileIsDirectory(url), + let .bodyPartFileSizeNotAvailable(url), + let .bodyPartInputStreamCreationFailed(url), + let .outputStreamCreationFailed(url), + let .outputStreamFileAlreadyExists(url), + let .outputStreamURLInvalid(url), + let .bodyPartFileNotReachableWithError(url, _), + let .bodyPartFileSizeQueryFailedWithError(url, _): + return url + case .outputStreamWriteFailed, + .inputStreamReadFailed: + return nil + } + } + + var underlyingError: Error? { + switch self { + case let .bodyPartFileNotReachableWithError(_, error), + let .bodyPartFileSizeQueryFailedWithError(_, error), + let .outputStreamWriteFailed(error), + let .inputStreamReadFailed(error): + return error + case .bodyPartURLInvalid, + .bodyPartFilenameInvalid, + .bodyPartFileNotReachable, + .bodyPartFileIsDirectory, + .bodyPartFileSizeNotAvailable, + .bodyPartInputStreamCreationFailed, + .outputStreamCreationFailed, + .outputStreamFileAlreadyExists, + .outputStreamURLInvalid: + return nil + } + } +} + +extension AFError.ResponseValidationFailureReason { + var acceptableContentTypes: [String]? { + switch self { + case let .missingContentType(types), + let .unacceptableContentType(types, _): + return types + case .dataFileNil, + .dataFileReadFailed, + .unacceptableStatusCode, + .customValidationFailed: + return nil + } + } + + var responseContentType: String? { + switch self { + case let .unacceptableContentType(_, responseType): + return responseType + case .dataFileNil, + .dataFileReadFailed, + .missingContentType, + .unacceptableStatusCode, + .customValidationFailed: + return nil + } + } + + var responseCode: Int? { + switch self { + case let .unacceptableStatusCode(code): + return code + case .dataFileNil, + .dataFileReadFailed, + .missingContentType, + .unacceptableContentType, + .customValidationFailed: + return nil + } + } + + var underlyingError: Error? { + switch self { + case let .customValidationFailed(error): + return error + case .dataFileNil, + .dataFileReadFailed, + .missingContentType, + .unacceptableContentType, + .unacceptableStatusCode: + return nil + } + } +} + +extension AFError.ResponseSerializationFailureReason { + var failedStringEncoding: String.Encoding? { + switch self { + case let .stringSerializationFailed(encoding): + return encoding + case .inputDataNilOrZeroLength, + .inputFileNil, + .inputFileReadFailed(_), + .jsonSerializationFailed(_), + .decodingFailed(_), + .customSerializationFailed(_), + .invalidEmptyResponse: + return nil + } + } + + var underlyingError: Error? { + switch self { + case let .jsonSerializationFailed(error), + let .decodingFailed(error), + let .customSerializationFailed(error): + return error + case .inputDataNilOrZeroLength, + .inputFileNil, + .inputFileReadFailed, + .stringSerializationFailed, + .invalidEmptyResponse: + return nil + } + } +} + +#if !(os(Linux) || os(Windows)) +extension AFError.ServerTrustFailureReason { + var output: AFError.ServerTrustFailureReason.Output? { + switch self { + case let .defaultEvaluationFailed(output), + let .hostValidationFailed(output), + let .revocationCheckFailed(output, _): + return output + case .noRequiredEvaluator, + .noCertificatesFound, + .noPublicKeysFound, + .policyApplicationFailed, + .settingAnchorCertificatesFailed, + .revocationPolicyCreationFailed, + .trustEvaluationFailed, + .certificatePinningFailed, + .publicKeyPinningFailed, + .customEvaluationFailed: + return nil + } + } + + var underlyingError: Error? { + switch self { + case let .customEvaluationFailed(error): + return error + case let .trustEvaluationFailed(error): + return error + case .noRequiredEvaluator, + .noCertificatesFound, + .noPublicKeysFound, + .policyApplicationFailed, + .settingAnchorCertificatesFailed, + .revocationPolicyCreationFailed, + .defaultEvaluationFailed, + .hostValidationFailed, + .revocationCheckFailed, + .certificatePinningFailed, + .publicKeyPinningFailed: + return nil + } + } +} +#endif + +// MARK: - Error Descriptions + +extension AFError: LocalizedError { + public var errorDescription: String? { + switch self { + case .explicitlyCancelled: + return "Request explicitly cancelled." + case let .invalidURL(url): + return "URL is not valid: \(url)" + case let .parameterEncodingFailed(reason): + return reason.localizedDescription + case let .parameterEncoderFailed(reason): + return reason.localizedDescription + case let .multipartEncodingFailed(reason): + return reason.localizedDescription + case let .requestAdaptationFailed(error): + return "Request adaption failed with error: \(error.localizedDescription)" + case let .responseValidationFailed(reason): + return reason.localizedDescription + case let .responseSerializationFailed(reason): + return reason.localizedDescription + case let .requestRetryFailed(retryError, originalError): + return """ + Request retry failed with retry error: \(retryError.localizedDescription), \ + original error: \(originalError.localizedDescription) + """ + case .sessionDeinitialized: + return """ + Session was invalidated without error, so it was likely deinitialized unexpectedly. \ + Be sure to retain a reference to your Session for the duration of your requests. + """ + case let .sessionInvalidated(error): + return "Session was invalidated with error: \(error?.localizedDescription ?? "No description.")" + #if !(os(Linux) || os(Windows)) + case let .serverTrustEvaluationFailed(reason): + return "Server trust evaluation failed due to reason: \(reason.localizedDescription)" + #endif + case let .urlRequestValidationFailed(reason): + return "URLRequest validation failed due to reason: \(reason.localizedDescription)" + case let .createUploadableFailed(error): + return "Uploadable creation failed with error: \(error.localizedDescription)" + case let .createURLRequestFailed(error): + return "URLRequest creation failed with error: \(error.localizedDescription)" + case let .downloadedFileMoveFailed(error, source, destination): + return "Moving downloaded file from: \(source) to: \(destination) failed with error: \(error.localizedDescription)" + case let .sessionTaskFailed(error): + return "URLSessionTask failed with error: \(error.localizedDescription)" + } + } +} + +extension AFError.ParameterEncodingFailureReason { + var localizedDescription: String { + switch self { + case .missingURL: + return "URL request to encode was missing a URL" + case let .jsonEncodingFailed(error): + return "JSON could not be encoded because of error:\n\(error.localizedDescription)" + case let .customEncodingFailed(error): + return "Custom parameter encoder failed with error: \(error.localizedDescription)" + } + } +} + +extension AFError.ParameterEncoderFailureReason { + var localizedDescription: String { + switch self { + case let .missingRequiredComponent(component): + return "Encoding failed due to a missing request component: \(component)" + case let .encoderFailed(error): + return "The underlying encoder failed with the error: \(error)" + } + } +} + +extension AFError.MultipartEncodingFailureReason { + var localizedDescription: String { + switch self { + case let .bodyPartURLInvalid(url): + return "The URL provided is not a file URL: \(url)" + case let .bodyPartFilenameInvalid(url): + return "The URL provided does not have a valid filename: \(url)" + case let .bodyPartFileNotReachable(url): + return "The URL provided is not reachable: \(url)" + case let .bodyPartFileNotReachableWithError(url, error): + return """ + The system returned an error while checking the provided URL for reachability. + URL: \(url) + Error: \(error) + """ + case let .bodyPartFileIsDirectory(url): + return "The URL provided is a directory: \(url)" + case let .bodyPartFileSizeNotAvailable(url): + return "Could not fetch the file size from the provided URL: \(url)" + case let .bodyPartFileSizeQueryFailedWithError(url, error): + return """ + The system returned an error while attempting to fetch the file size from the provided URL. + URL: \(url) + Error: \(error) + """ + case let .bodyPartInputStreamCreationFailed(url): + return "Failed to create an InputStream for the provided URL: \(url)" + case let .outputStreamCreationFailed(url): + return "Failed to create an OutputStream for URL: \(url)" + case let .outputStreamFileAlreadyExists(url): + return "A file already exists at the provided URL: \(url)" + case let .outputStreamURLInvalid(url): + return "The provided OutputStream URL is invalid: \(url)" + case let .outputStreamWriteFailed(error): + return "OutputStream write failed with error: \(error)" + case let .inputStreamReadFailed(error): + return "InputStream read failed with error: \(error)" + } + } +} + +extension AFError.ResponseSerializationFailureReason { + var localizedDescription: String { + switch self { + 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 let .inputFileReadFailed(url): + return "Response could not be serialized, input file could not be read: \(url)." + case let .stringSerializationFailed(encoding): + return "String could not be serialized with encoding: \(encoding)." + case let .jsonSerializationFailed(error): + return "JSON could not be serialized because of error:\n\(error.localizedDescription)" + case let .invalidEmptyResponse(type): + return """ + Empty response could not be serialized to type: \(type). \ + Use Empty as the expected type for such responses. + """ + case let .decodingFailed(error): + return "Response could not be decoded because of error:\n\(error.localizedDescription)" + case let .customSerializationFailed(error): + return "Custom response serializer failed with 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 let .dataFileReadFailed(url): + return "Response could not be validated, data file could not be read: \(url)." + case let .missingContentType(types): + return """ + Response Content-Type was missing and acceptable content types \ + (\(types.joined(separator: ","))) do not match "*/*". + """ + case let .unacceptableContentType(acceptableTypes, responseType): + return """ + Response Content-Type "\(responseType)" does not match any acceptable types: \ + \(acceptableTypes.joined(separator: ",")). + """ + case let .unacceptableStatusCode(code): + return "Response status code was unacceptable: \(code)." + case let .customValidationFailed(error): + return "Custom response validation failed with error: \(error.localizedDescription)" + } + } +} + +#if !(os(Linux) || os(Windows)) +extension AFError.ServerTrustFailureReason { + var localizedDescription: String { + switch self { + case let .noRequiredEvaluator(host): + return "A ServerTrustEvaluating value is required for host \(host) but none was found." + case .noCertificatesFound: + return "No certificates were found or provided for evaluation." + case .noPublicKeysFound: + return "No public keys were found or provided for evaluation." + case .policyApplicationFailed: + return "Attempting to set a SecPolicy failed." + case .settingAnchorCertificatesFailed: + return "Attempting to set the provided certificates as anchor certificates failed." + case .revocationPolicyCreationFailed: + return "Attempting to create a revocation policy failed." + case let .trustEvaluationFailed(error): + return "SecTrust evaluation failed with error: \(error?.localizedDescription ?? "None")" + case let .defaultEvaluationFailed(output): + return "Default evaluation failed for host \(output.host)." + case let .hostValidationFailed(output): + return "Host validation failed for host \(output.host)." + case let .revocationCheckFailed(output, _): + return "Revocation check failed for host \(output.host)." + case let .certificatePinningFailed(host, _, _, _): + return "Certificate pinning failed for host \(host)." + case let .publicKeyPinningFailed(host, _, _, _): + return "Public key pinning failed for host \(host)." + case let .customEvaluationFailed(error): + return "Custom trust evaluation failed with error: \(error.localizedDescription)" + } + } +} +#endif + +extension AFError.URLRequestValidationFailureReason { + var localizedDescription: String { + switch self { + case let .bodyDataInGETRequest(data): + return """ + Invalid URLRequest: Requests with GET method cannot have body data: + \(String(decoding: data, as: UTF8.self)) + """ + } + } +} diff --git a/Pods/Alamofire/Source/Alamofire.swift b/Pods/Alamofire/Source/Alamofire.swift new file mode 100644 index 0000000..52ea3de --- /dev/null +++ b/Pods/Alamofire/Source/Alamofire.swift @@ -0,0 +1,40 @@ +// +// Alamofire.swift +// +// Copyright (c) 2014-2021 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 +#if canImport(FoundationNetworking) +@_exported import FoundationNetworking +#endif + +// Enforce minimum Swift version for all platforms and build systems. +#if swift(<5.5) +#error("Alamofire doesn't support Swift versions below 5.5.") +#endif + +/// Reference to `Session.default` for quick bootstrapping and examples. +public let AF = Session.default + +/// Current Alamofire version. Necessary since SPM doesn't use dynamic libraries. Plus this will be more accurate. +let version = "5.7.1" diff --git a/Pods/Alamofire/Source/AlamofireExtended.swift b/Pods/Alamofire/Source/AlamofireExtended.swift new file mode 100644 index 0000000..280c6de --- /dev/null +++ b/Pods/Alamofire/Source/AlamofireExtended.swift @@ -0,0 +1,61 @@ +// +// AlamofireExtended.swift +// +// Copyright (c) 2019 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. +// + +/// Type that acts as a generic extension point for all `AlamofireExtended` types. +public struct AlamofireExtension { + /// Stores the type or meta-type of any extended type. + public private(set) var type: ExtendedType + + /// Create an instance from the provided value. + /// + /// - Parameter type: Instance being extended. + public init(_ type: ExtendedType) { + self.type = type + } +} + +/// Protocol describing the `af` extension points for Alamofire extended types. +public protocol AlamofireExtended { + /// Type being extended. + associatedtype ExtendedType + + /// Static Alamofire extension point. + static var af: AlamofireExtension.Type { get set } + /// Instance Alamofire extension point. + var af: AlamofireExtension { get set } +} + +extension AlamofireExtended { + /// Static Alamofire extension point. + public static var af: AlamofireExtension.Type { + get { AlamofireExtension.self } + set {} + } + + /// Instance Alamofire extension point. + public var af: AlamofireExtension { + get { AlamofireExtension(self) } + set {} + } +} diff --git a/Pods/Alamofire/Source/AuthenticationInterceptor.swift b/Pods/Alamofire/Source/AuthenticationInterceptor.swift new file mode 100644 index 0000000..c3a3f31 --- /dev/null +++ b/Pods/Alamofire/Source/AuthenticationInterceptor.swift @@ -0,0 +1,403 @@ +// +// AuthenticationInterceptor.swift +// +// Copyright (c) 2020 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 `AuthenticationCredential` protocol can be used to authenticate `URLRequest`s. +/// +/// One common example of an `AuthenticationCredential` is an OAuth2 credential containing an access token used to +/// authenticate all requests on behalf of a user. The access token generally has an expiration window of 60 minutes +/// which will then require a refresh of the credential using the refresh token to generate a new access token. +public protocol AuthenticationCredential { + /// Whether the credential requires a refresh. This property should always return `true` when the credential is + /// expired. It is also wise to consider returning `true` when the credential will expire in several seconds or + /// minutes depending on the expiration window of the credential. + /// + /// For example, if the credential is valid for 60 minutes, then it would be wise to return `true` when the + /// credential is only valid for 5 minutes or less. That ensures the credential will not expire as it is passed + /// around backend services. + var requiresRefresh: Bool { get } +} + +// MARK: - + +/// Types adopting the `Authenticator` protocol can be used to authenticate `URLRequest`s with an +/// `AuthenticationCredential` as well as refresh the `AuthenticationCredential` when required. +public protocol Authenticator: AnyObject { + /// The type of credential associated with the `Authenticator` instance. + associatedtype Credential: AuthenticationCredential + + /// Applies the `Credential` to the `URLRequest`. + /// + /// In the case of OAuth2, the access token of the `Credential` would be added to the `URLRequest` as a Bearer + /// token to the `Authorization` header. + /// + /// - Parameters: + /// - credential: The `Credential`. + /// - urlRequest: The `URLRequest`. + func apply(_ credential: Credential, to urlRequest: inout URLRequest) + + /// Refreshes the `Credential` and executes the `completion` closure with the `Result` once complete. + /// + /// Refresh can be called in one of two ways. It can be called before the `Request` is actually executed due to + /// a `requiresRefresh` returning `true` during the adapt portion of the `Request` creation process. It can also + /// be triggered by a failed `Request` where the authentication server denied access due to an expired or + /// invalidated access token. + /// + /// In the case of OAuth2, this method would use the refresh token of the `Credential` to generate a new + /// `Credential` using the authentication service. Once complete, the `completion` closure should be called with + /// the new `Credential`, or the error that occurred. + /// + /// In general, if the refresh call fails with certain status codes from the authentication server (commonly a 401), + /// the refresh token in the `Credential` can no longer be used to generate a valid `Credential`. In these cases, + /// you will need to reauthenticate the user with their username / password. + /// + /// Please note, these are just general examples of common use cases. They are not meant to solve your specific + /// authentication server challenges. Please work with your authentication server team to ensure your + /// `Authenticator` logic matches their expectations. + /// + /// - Parameters: + /// - credential: The `Credential` to refresh. + /// - session: The `Session` requiring the refresh. + /// - completion: The closure to be executed once the refresh is complete. + func refresh(_ credential: Credential, for session: Session, completion: @escaping (Result) -> Void) + + /// Determines whether the `URLRequest` failed due to an authentication error based on the `HTTPURLResponse`. + /// + /// If the authentication server **CANNOT** invalidate credentials after they are issued, then simply return `false` + /// for this method. If the authentication server **CAN** invalidate credentials due to security breaches, then you + /// will need to work with your authentication server team to understand how to identify when this occurs. + /// + /// In the case of OAuth2, where an authentication server can invalidate credentials, you will need to inspect the + /// `HTTPURLResponse` or possibly the `Error` for when this occurs. This is commonly handled by the authentication + /// server returning a 401 status code and some additional header to indicate an OAuth2 failure occurred. + /// + /// It is very important to understand how your authentication server works to be able to implement this correctly. + /// For example, if your authentication server returns a 401 when an OAuth2 error occurs, and your downstream + /// service also returns a 401 when you are not authorized to perform that operation, how do you know which layer + /// of the backend returned you a 401? You do not want to trigger a refresh unless you know your authentication + /// server is actually the layer rejecting the request. Again, work with your authentication server team to understand + /// how to identify an OAuth2 401 error vs. a downstream 401 error to avoid endless refresh loops. + /// + /// - Parameters: + /// - urlRequest: The `URLRequest`. + /// - response: The `HTTPURLResponse`. + /// - error: The `Error`. + /// + /// - Returns: `true` if the `URLRequest` failed due to an authentication error, `false` otherwise. + func didRequest(_ urlRequest: URLRequest, with response: HTTPURLResponse, failDueToAuthenticationError error: Error) -> Bool + + /// Determines whether the `URLRequest` is authenticated with the `Credential`. + /// + /// If the authentication server **CANNOT** invalidate credentials after they are issued, then simply return `true` + /// for this method. If the authentication server **CAN** invalidate credentials due to security breaches, then + /// read on. + /// + /// When an authentication server can invalidate credentials, it means that you may have a non-expired credential + /// that appears to be valid, but will be rejected by the authentication server when used. Generally when this + /// happens, a number of requests are all sent when the application is foregrounded, and all of them will be + /// rejected by the authentication server in the order they are received. The first failed request will trigger a + /// refresh internally, which will update the credential, and then retry all the queued requests with the new + /// credential. However, it is possible that some of the original requests will not return from the authentication + /// server until the refresh has completed. This is where this method comes in. + /// + /// When the authentication server rejects a credential, we need to check to make sure we haven't refreshed the + /// credential while the request was in flight. If it has already refreshed, then we don't need to trigger an + /// additional refresh. If it hasn't refreshed, then we need to refresh. + /// + /// Now that it is understood how the result of this method is used in the refresh lifecyle, let's walk through how + /// to implement it. You should return `true` in this method if the `URLRequest` is authenticated in a way that + /// matches the values in the `Credential`. In the case of OAuth2, this would mean that the Bearer token in the + /// `Authorization` header of the `URLRequest` matches the access token in the `Credential`. If it matches, then we + /// know the `Credential` was used to authenticate the `URLRequest` and should return `true`. If the Bearer token + /// did not match the access token, then you should return `false`. + /// + /// - Parameters: + /// - urlRequest: The `URLRequest`. + /// - credential: The `Credential`. + /// + /// - Returns: `true` if the `URLRequest` is authenticated with the `Credential`, `false` otherwise. + func isRequest(_ urlRequest: URLRequest, authenticatedWith credential: Credential) -> Bool +} + +// MARK: - + +/// Represents various authentication failures that occur when using the `AuthenticationInterceptor`. All errors are +/// still vended from Alamofire as `AFError` types. The `AuthenticationError` instances will be embedded within +/// `AFError` `.requestAdaptationFailed` or `.requestRetryFailed` cases. +public enum AuthenticationError: Error { + /// The credential was missing so the request could not be authenticated. + case missingCredential + /// The credential was refreshed too many times within the `RefreshWindow`. + case excessiveRefresh +} + +// MARK: - + +/// The `AuthenticationInterceptor` class manages the queuing and threading complexity of authenticating requests. +/// It relies on an `Authenticator` type to handle the actual `URLRequest` authentication and `Credential` refresh. +public class AuthenticationInterceptor: RequestInterceptor where AuthenticatorType: Authenticator { + // MARK: Typealiases + + /// Type of credential used to authenticate requests. + public typealias Credential = AuthenticatorType.Credential + + // MARK: Helper Types + + /// Type that defines a time window used to identify excessive refresh calls. When enabled, prior to executing a + /// refresh, the `AuthenticationInterceptor` compares the timestamp history of previous refresh calls against the + /// `RefreshWindow`. If more refreshes have occurred within the refresh window than allowed, the refresh is + /// cancelled and an `AuthorizationError.excessiveRefresh` error is thrown. + public struct RefreshWindow { + /// `TimeInterval` defining the duration of the time window before the current time in which the number of + /// refresh attempts is compared against `maximumAttempts`. For example, if `interval` is 30 seconds, then the + /// `RefreshWindow` represents the past 30 seconds. If more attempts occurred in the past 30 seconds than + /// `maximumAttempts`, an `.excessiveRefresh` error will be thrown. + public let interval: TimeInterval + + /// Total refresh attempts allowed within `interval` before throwing an `.excessiveRefresh` error. + public let maximumAttempts: Int + + /// Creates a `RefreshWindow` instance from the specified `interval` and `maximumAttempts`. + /// + /// - Parameters: + /// - interval: `TimeInterval` defining the duration of the time window before the current time. + /// - maximumAttempts: The maximum attempts allowed within the `TimeInterval`. + public init(interval: TimeInterval = 30.0, maximumAttempts: Int = 5) { + self.interval = interval + self.maximumAttempts = maximumAttempts + } + } + + private struct AdaptOperation { + let urlRequest: URLRequest + let session: Session + let completion: (Result) -> Void + } + + private enum AdaptResult { + case adapt(Credential) + case doNotAdapt(AuthenticationError) + case adaptDeferred + } + + private struct MutableState { + var credential: Credential? + + var isRefreshing = false + var refreshTimestamps: [TimeInterval] = [] + var refreshWindow: RefreshWindow? + + var adaptOperations: [AdaptOperation] = [] + var requestsToRetry: [(RetryResult) -> Void] = [] + } + + // MARK: Properties + + /// The `Credential` used to authenticate requests. + public var credential: Credential? { + get { $mutableState.credential } + set { $mutableState.credential = newValue } + } + + let authenticator: AuthenticatorType + let queue = DispatchQueue(label: "org.alamofire.authentication.inspector") + + @Protected + private var mutableState: MutableState + + // MARK: Initialization + + /// Creates an `AuthenticationInterceptor` instance from the specified parameters. + /// + /// A `nil` `RefreshWindow` will result in the `AuthenticationInterceptor` not checking for excessive refresh calls. + /// It is recommended to always use a `RefreshWindow` to avoid endless refresh cycles. + /// + /// - Parameters: + /// - authenticator: The `Authenticator` type. + /// - credential: The `Credential` if it exists. `nil` by default. + /// - refreshWindow: The `RefreshWindow` used to identify excessive refresh calls. `RefreshWindow()` by default. + public init(authenticator: AuthenticatorType, + credential: Credential? = nil, + refreshWindow: RefreshWindow? = RefreshWindow()) { + self.authenticator = authenticator + mutableState = MutableState(credential: credential, refreshWindow: refreshWindow) + } + + // MARK: Adapt + + public func adapt(_ urlRequest: URLRequest, for session: Session, completion: @escaping (Result) -> Void) { + let adaptResult: AdaptResult = $mutableState.write { mutableState in + // Queue the adapt operation if a refresh is already in place. + guard !mutableState.isRefreshing else { + let operation = AdaptOperation(urlRequest: urlRequest, session: session, completion: completion) + mutableState.adaptOperations.append(operation) + return .adaptDeferred + } + + // Throw missing credential error is the credential is missing. + guard let credential = mutableState.credential else { + let error = AuthenticationError.missingCredential + return .doNotAdapt(error) + } + + // Queue the adapt operation and trigger refresh operation if credential requires refresh. + guard !credential.requiresRefresh else { + let operation = AdaptOperation(urlRequest: urlRequest, session: session, completion: completion) + mutableState.adaptOperations.append(operation) + refresh(credential, for: session, insideLock: &mutableState) + return .adaptDeferred + } + + return .adapt(credential) + } + + switch adaptResult { + case let .adapt(credential): + var authenticatedRequest = urlRequest + authenticator.apply(credential, to: &authenticatedRequest) + completion(.success(authenticatedRequest)) + + case let .doNotAdapt(adaptError): + completion(.failure(adaptError)) + + case .adaptDeferred: + // No-op: adapt operation captured during refresh. + break + } + } + + // MARK: Retry + + public func retry(_ request: Request, for session: Session, dueTo error: Error, completion: @escaping (RetryResult) -> Void) { + // Do not attempt retry if there was not an original request and response from the server. + guard let urlRequest = request.request, let response = request.response else { + completion(.doNotRetry) + return + } + + // Do not attempt retry unless the `Authenticator` verifies failure was due to authentication error (i.e. 401 status code). + guard authenticator.didRequest(urlRequest, with: response, failDueToAuthenticationError: error) else { + completion(.doNotRetry) + return + } + + // Do not attempt retry if there is no credential. + guard let credential = credential else { + let error = AuthenticationError.missingCredential + completion(.doNotRetryWithError(error)) + return + } + + // Retry the request if the `Authenticator` verifies it was authenticated with a previous credential. + guard authenticator.isRequest(urlRequest, authenticatedWith: credential) else { + completion(.retry) + return + } + + $mutableState.write { mutableState in + mutableState.requestsToRetry.append(completion) + + guard !mutableState.isRefreshing else { return } + + refresh(credential, for: session, insideLock: &mutableState) + } + } + + // MARK: Refresh + + private func refresh(_ credential: Credential, for session: Session, insideLock mutableState: inout MutableState) { + guard !isRefreshExcessive(insideLock: &mutableState) else { + let error = AuthenticationError.excessiveRefresh + handleRefreshFailure(error, insideLock: &mutableState) + return + } + + mutableState.refreshTimestamps.append(ProcessInfo.processInfo.systemUptime) + mutableState.isRefreshing = true + + // Dispatch to queue to hop out of the lock in case authenticator.refresh is implemented synchronously. + queue.async { + self.authenticator.refresh(credential, for: session) { result in + self.$mutableState.write { mutableState in + switch result { + case let .success(credential): + self.handleRefreshSuccess(credential, insideLock: &mutableState) + case let .failure(error): + self.handleRefreshFailure(error, insideLock: &mutableState) + } + } + } + } + } + + private func isRefreshExcessive(insideLock mutableState: inout MutableState) -> Bool { + guard let refreshWindow = mutableState.refreshWindow else { return false } + + let refreshWindowMin = ProcessInfo.processInfo.systemUptime - refreshWindow.interval + + let refreshAttemptsWithinWindow = mutableState.refreshTimestamps.reduce(into: 0) { attempts, refreshTimestamp in + guard refreshWindowMin <= refreshTimestamp else { return } + attempts += 1 + } + + let isRefreshExcessive = refreshAttemptsWithinWindow >= refreshWindow.maximumAttempts + + return isRefreshExcessive + } + + private func handleRefreshSuccess(_ credential: Credential, insideLock mutableState: inout MutableState) { + mutableState.credential = credential + + let adaptOperations = mutableState.adaptOperations + let requestsToRetry = mutableState.requestsToRetry + + mutableState.adaptOperations.removeAll() + mutableState.requestsToRetry.removeAll() + + mutableState.isRefreshing = false + + // Dispatch to queue to hop out of the mutable state lock + queue.async { + adaptOperations.forEach { self.adapt($0.urlRequest, for: $0.session, completion: $0.completion) } + requestsToRetry.forEach { $0(.retry) } + } + } + + private func handleRefreshFailure(_ error: Error, insideLock mutableState: inout MutableState) { + let adaptOperations = mutableState.adaptOperations + let requestsToRetry = mutableState.requestsToRetry + + mutableState.adaptOperations.removeAll() + mutableState.requestsToRetry.removeAll() + + mutableState.isRefreshing = false + + // Dispatch to queue to hop out of the mutable state lock + queue.async { + adaptOperations.forEach { $0.completion(.failure(error)) } + requestsToRetry.forEach { $0(.doNotRetryWithError(error)) } + } + } +} diff --git a/Pods/Alamofire/Source/CachedResponseHandler.swift b/Pods/Alamofire/Source/CachedResponseHandler.swift new file mode 100644 index 0000000..1371b6e --- /dev/null +++ b/Pods/Alamofire/Source/CachedResponseHandler.swift @@ -0,0 +1,107 @@ +// +// CachedResponseHandler.swift +// +// Copyright (c) 2019 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 handles whether the data task should store the HTTP response in the cache. +public protocol CachedResponseHandler { + /// Determines whether the HTTP response should be stored in the cache. + /// + /// The `completion` closure should be passed one of three possible options: + /// + /// 1. The cached response provided by the server (this is the most common use case). + /// 2. A modified version of the cached response (you may want to modify it in some way before caching). + /// 3. A `nil` value to prevent the cached response from being stored in the cache. + /// + /// - Parameters: + /// - task: The data task whose request resulted in the cached response. + /// - response: The cached response to potentially store in the cache. + /// - completion: The closure to execute containing cached response, a modified response, or `nil`. + func dataTask(_ task: URLSessionDataTask, + willCacheResponse response: CachedURLResponse, + completion: @escaping (CachedURLResponse?) -> Void) +} + +// MARK: - + +/// `ResponseCacher` is a convenience `CachedResponseHandler` making it easy to cache, not cache, or modify a cached +/// response. +public struct ResponseCacher { + /// Defines the behavior of the `ResponseCacher` type. + public enum Behavior { + /// Stores the cached response in the cache. + case cache + /// Prevents the cached response from being stored in the cache. + case doNotCache + /// Modifies the cached response before storing it in the cache. + case modify((URLSessionDataTask, CachedURLResponse) -> CachedURLResponse?) + } + + /// Returns a `ResponseCacher` with a `.cache` `Behavior`. + public static let cache = ResponseCacher(behavior: .cache) + /// Returns a `ResponseCacher` with a `.doNotCache` `Behavior`. + public static let doNotCache = ResponseCacher(behavior: .doNotCache) + + /// The `Behavior` of the `ResponseCacher`. + public let behavior: Behavior + + /// Creates a `ResponseCacher` instance from the `Behavior`. + /// + /// - Parameter behavior: The `Behavior`. + public init(behavior: Behavior) { + self.behavior = behavior + } +} + +extension ResponseCacher: CachedResponseHandler { + public func dataTask(_ task: URLSessionDataTask, + willCacheResponse response: CachedURLResponse, + completion: @escaping (CachedURLResponse?) -> Void) { + switch behavior { + case .cache: + completion(response) + case .doNotCache: + completion(nil) + case let .modify(closure): + let response = closure(task, response) + completion(response) + } + } +} + +extension CachedResponseHandler where Self == ResponseCacher { + /// Provides a `ResponseCacher` which caches the response, if allowed. Equivalent to `ResponseCacher.cache`. + public static var cache: ResponseCacher { .cache } + + /// Provides a `ResponseCacher` which does not cache the response. Equivalent to `ResponseCacher.doNotCache`. + public static var doNotCache: ResponseCacher { .doNotCache } + + /// Creates a `ResponseCacher` which modifies the proposed `CachedURLResponse` using the provided closure. + /// + /// - Parameter closure: Closure used to modify the `CachedURLResponse`. + /// - Returns: The `ResponseCacher`. + public static func modify(using closure: @escaping ((URLSessionDataTask, CachedURLResponse) -> CachedURLResponse?)) -> ResponseCacher { + ResponseCacher(behavior: .modify(closure)) + } +} diff --git a/Pods/Alamofire/Source/Combine.swift b/Pods/Alamofire/Source/Combine.swift new file mode 100644 index 0000000..08329fc --- /dev/null +++ b/Pods/Alamofire/Source/Combine.swift @@ -0,0 +1,655 @@ +// +// Combine.swift +// +// Copyright (c) 2020 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) && (arch(i386) || arch(arm))) || os(Windows) || os(Linux)) + +import Combine +import Dispatch +import Foundation + +// MARK: - DataRequest / UploadRequest + +/// A Combine `Publisher` that publishes the `DataResponse` of the provided `DataRequest`. +@available(macOS 10.15, iOS 13, watchOS 6, tvOS 13, *) +public struct DataResponsePublisher: Publisher { + public typealias Output = DataResponse + public typealias Failure = Never + + private typealias Handler = (@escaping (_ response: DataResponse) -> Void) -> DataRequest + + private let request: DataRequest + private let responseHandler: Handler + + /// Creates an instance which will serialize responses using the provided `ResponseSerializer`. + /// + /// - Parameters: + /// - request: `DataRequest` for which to publish the response. + /// - queue: `DispatchQueue` on which the `DataResponse` value will be published. `.main` by default. + /// - serializer: `ResponseSerializer` used to produce the published `DataResponse`. + public init(_ request: DataRequest, queue: DispatchQueue, serializer: Serializer) + where Value == Serializer.SerializedObject { + self.request = request + responseHandler = { request.response(queue: queue, responseSerializer: serializer, completionHandler: $0) } + } + + /// Creates an instance which will serialize responses using the provided `DataResponseSerializerProtocol`. + /// + /// - Parameters: + /// - request: `DataRequest` for which to publish the response. + /// - queue: `DispatchQueue` on which the `DataResponse` value will be published. `.main` by default. + /// - serializer: `DataResponseSerializerProtocol` used to produce the published `DataResponse`. + public init(_ request: DataRequest, + queue: DispatchQueue, + serializer: Serializer) + where Value == Serializer.SerializedObject { + self.request = request + responseHandler = { request.response(queue: queue, responseSerializer: serializer, completionHandler: $0) } + } + + /// Publishes only the `Result` of the `DataResponse` value. + /// + /// - Returns: The `AnyPublisher` publishing the `Result` value. + public func result() -> AnyPublisher, Never> { + map(\.result).eraseToAnyPublisher() + } + + /// Publishes the `Result` of the `DataResponse` as a single `Value` or fail with the `AFError` instance. + /// + /// - Returns: The `AnyPublisher` publishing the stream. + public func value() -> AnyPublisher { + setFailureType(to: AFError.self).flatMap(\.result.publisher).eraseToAnyPublisher() + } + + public func receive(subscriber: S) where S: Subscriber, DataResponsePublisher.Failure == S.Failure, DataResponsePublisher.Output == S.Input { + subscriber.receive(subscription: Inner(request: request, + responseHandler: responseHandler, + downstream: subscriber)) + } + + private final class Inner: Subscription + where Downstream.Input == Output { + typealias Failure = Downstream.Failure + + @Protected + private var downstream: Downstream? + private let request: DataRequest + private let responseHandler: Handler + + init(request: DataRequest, responseHandler: @escaping Handler, downstream: Downstream) { + self.request = request + self.responseHandler = responseHandler + self.downstream = downstream + } + + func request(_ demand: Subscribers.Demand) { + assert(demand > 0) + + guard let downstream = downstream else { return } + + self.downstream = nil + responseHandler { response in + _ = downstream.receive(response) + downstream.receive(completion: .finished) + }.resume() + } + + func cancel() { + request.cancel() + downstream = nil + } + } +} + +@available(macOS 10.15, iOS 13, watchOS 6, tvOS 13, *) +extension DataResponsePublisher where Value == Data? { + /// Creates an instance which publishes a `DataResponse` value without serialization. + @available(macOS 10.15, iOS 13, watchOS 6, tvOS 13, *) + public init(_ request: DataRequest, queue: DispatchQueue) { + self.request = request + responseHandler = { request.response(queue: queue, completionHandler: $0) } + } +} + +extension DataRequest { + /// Creates a `DataResponsePublisher` for this instance using the given `ResponseSerializer` and `DispatchQueue`. + /// + /// - Parameters: + /// - serializer: `ResponseSerializer` used to serialize response `Data`. + /// - queue: `DispatchQueue` on which the `DataResponse` will be published. `.main` by default. + /// + /// - Returns: The `DataResponsePublisher`. + @available(macOS 10.15, iOS 13, watchOS 6, tvOS 13, *) + public func publishResponse(using serializer: Serializer, on queue: DispatchQueue = .main) -> DataResponsePublisher + where Serializer.SerializedObject == T { + DataResponsePublisher(self, queue: queue, serializer: serializer) + } + + /// Creates a `DataResponsePublisher` for this instance and uses a `DataResponseSerializer` to serialize the + /// response. + /// + /// - Parameters: + /// - queue: `DispatchQueue` on which the `DataResponse` will be published. `.main` by default. + /// - preprocessor: `DataPreprocessor` which filters the `Data` before serialization. `PassthroughPreprocessor()` + /// by default. + /// - emptyResponseCodes: `Set` of HTTP status codes for which empty responses are allowed. `[204, 205]` by + /// default. + /// - emptyRequestMethods: `Set` of `HTTPMethod`s for which empty responses are allowed, regardless of + /// status code. `[.head]` by default. + /// - Returns: The `DataResponsePublisher`. + @available(macOS 10.15, iOS 13, watchOS 6, tvOS 13, *) + public func publishData(queue: DispatchQueue = .main, + preprocessor: DataPreprocessor = DataResponseSerializer.defaultDataPreprocessor, + emptyResponseCodes: Set = DataResponseSerializer.defaultEmptyResponseCodes, + emptyRequestMethods: Set = DataResponseSerializer.defaultEmptyRequestMethods) -> DataResponsePublisher { + publishResponse(using: DataResponseSerializer(dataPreprocessor: preprocessor, + emptyResponseCodes: emptyResponseCodes, + emptyRequestMethods: emptyRequestMethods), + on: queue) + } + + /// Creates a `DataResponsePublisher` for this instance and uses a `StringResponseSerializer` to serialize the + /// response. + /// + /// - Parameters: + /// - queue: `DispatchQueue` on which the `DataResponse` will be published. `.main` by default. + /// - preprocessor: `DataPreprocessor` which filters the `Data` before serialization. `PassthroughPreprocessor()` + /// by default. + /// - encoding: `String.Encoding` to parse the response. `nil` by default, in which case the encoding + /// will be determined by the server response, falling back to the default HTTP character + /// set, `ISO-8859-1`. + /// - emptyResponseCodes: `Set` of HTTP status codes for which empty responses are allowed. `[204, 205]` by + /// default. + /// - emptyRequestMethods: `Set` of `HTTPMethod`s for which empty responses are allowed, regardless of + /// status code. `[.head]` by default. + /// + /// - Returns: The `DataResponsePublisher`. + @available(macOS 10.15, iOS 13, watchOS 6, tvOS 13, *) + public func publishString(queue: DispatchQueue = .main, + preprocessor: DataPreprocessor = StringResponseSerializer.defaultDataPreprocessor, + encoding: String.Encoding? = nil, + emptyResponseCodes: Set = StringResponseSerializer.defaultEmptyResponseCodes, + emptyRequestMethods: Set = StringResponseSerializer.defaultEmptyRequestMethods) -> DataResponsePublisher { + publishResponse(using: StringResponseSerializer(dataPreprocessor: preprocessor, + encoding: encoding, + emptyResponseCodes: emptyResponseCodes, + emptyRequestMethods: emptyRequestMethods), + on: queue) + } + + @_disfavoredOverload + @available(macOS 10.15, iOS 13, watchOS 6, tvOS 13, *) + @available(*, deprecated, message: "Renamed publishDecodable(type:queue:preprocessor:decoder:emptyResponseCodes:emptyRequestMethods).") + public func publishDecodable(type: T.Type = T.self, + queue: DispatchQueue = .main, + preprocessor: DataPreprocessor = DecodableResponseSerializer.defaultDataPreprocessor, + decoder: DataDecoder = JSONDecoder(), + emptyResponseCodes: Set = DecodableResponseSerializer.defaultEmptyResponseCodes, + emptyResponseMethods: Set = DecodableResponseSerializer.defaultEmptyRequestMethods) -> DataResponsePublisher { + publishResponse(using: DecodableResponseSerializer(dataPreprocessor: preprocessor, + decoder: decoder, + emptyResponseCodes: emptyResponseCodes, + emptyRequestMethods: emptyResponseMethods), + on: queue) + } + + /// Creates a `DataResponsePublisher` for this instance and uses a `DecodableResponseSerializer` to serialize the + /// response. + /// + /// - Parameters: + /// - type: `Decodable` type to which to decode response `Data`. Inferred from the context by + /// default. + /// - queue: `DispatchQueue` on which the `DataResponse` will be published. `.main` by default. + /// - preprocessor: `DataPreprocessor` which filters the `Data` before serialization. + /// `PassthroughPreprocessor()` by default. + /// - decoder: `DataDecoder` instance used to decode response `Data`. `JSONDecoder()` by default. + /// - emptyResponseCodes: `Set` of HTTP status codes for which empty responses are allowed. `[204, 205]` by + /// default. + /// - emptyRequestMethods: `Set` of `HTTPMethod`s for which empty responses are allowed, regardless of + /// status code. `[.head]` by default. + /// + /// - Returns: The `DataResponsePublisher`. + @available(macOS 10.15, iOS 13, watchOS 6, tvOS 13, *) + public func publishDecodable(type: T.Type = T.self, + queue: DispatchQueue = .main, + preprocessor: DataPreprocessor = DecodableResponseSerializer.defaultDataPreprocessor, + decoder: DataDecoder = JSONDecoder(), + emptyResponseCodes: Set = DecodableResponseSerializer.defaultEmptyResponseCodes, + emptyRequestMethods: Set = DecodableResponseSerializer.defaultEmptyRequestMethods) -> DataResponsePublisher { + publishResponse(using: DecodableResponseSerializer(dataPreprocessor: preprocessor, + decoder: decoder, + emptyResponseCodes: emptyResponseCodes, + emptyRequestMethods: emptyRequestMethods), + on: queue) + } + + /// Creates a `DataResponsePublisher` for this instance which does not serialize the response before publishing. + /// + /// - queue: `DispatchQueue` on which the `DataResponse` will be published. `.main` by default. + /// + /// - Returns: The `DataResponsePublisher`. + @available(macOS 10.15, iOS 13, watchOS 6, tvOS 13, *) + public func publishUnserialized(queue: DispatchQueue = .main) -> DataResponsePublisher { + DataResponsePublisher(self, queue: queue) + } +} + +// A Combine `Publisher` that publishes a sequence of `Stream` values received by the provided `DataStreamRequest`. +@available(macOS 10.15, iOS 13, watchOS 6, tvOS 13, *) +public struct DataStreamPublisher: Publisher { + public typealias Output = DataStreamRequest.Stream + public typealias Failure = Never + + private typealias Handler = (@escaping DataStreamRequest.Handler) -> DataStreamRequest + + private let request: DataStreamRequest + private let streamHandler: Handler + + /// Creates an instance which will serialize responses using the provided `DataStreamSerializer`. + /// + /// - Parameters: + /// - request: `DataStreamRequest` for which to publish the response. + /// - queue: `DispatchQueue` on which the `Stream` values will be published. `.main` by + /// default. + /// - serializer: `DataStreamSerializer` used to produce the published `Stream` values. + public init(_ request: DataStreamRequest, queue: DispatchQueue, serializer: Serializer) + where Value == Serializer.SerializedObject { + self.request = request + streamHandler = { request.responseStream(using: serializer, on: queue, stream: $0) } + } + + /// Publishes only the `Result` of the `DataStreamRequest.Stream`'s `Event`s. + /// + /// - Returns: The `AnyPublisher` publishing the `Result` value. + public func result() -> AnyPublisher, Never> { + compactMap { stream in + switch stream.event { + case let .stream(result): + return result + // If the stream has completed with an error, send the error value downstream as a `.failure`. + case let .complete(completion): + return completion.error.map(Result.failure) + } + } + .eraseToAnyPublisher() + } + + /// Publishes the streamed values of the `DataStreamRequest.Stream` as a sequence of `Value` or fail with the + /// `AFError` instance. + /// + /// - Returns: The `AnyPublisher` publishing the stream. + public func value() -> AnyPublisher { + result().setFailureType(to: AFError.self).flatMap(\.publisher).eraseToAnyPublisher() + } + + public func receive(subscriber: S) where S: Subscriber, DataStreamPublisher.Failure == S.Failure, DataStreamPublisher.Output == S.Input { + subscriber.receive(subscription: Inner(request: request, + streamHandler: streamHandler, + downstream: subscriber)) + } + + private final class Inner: Subscription + where Downstream.Input == Output { + typealias Failure = Downstream.Failure + + @Protected + private var downstream: Downstream? + private let request: DataStreamRequest + private let streamHandler: Handler + + init(request: DataStreamRequest, streamHandler: @escaping Handler, downstream: Downstream) { + self.request = request + self.streamHandler = streamHandler + self.downstream = downstream + } + + func request(_ demand: Subscribers.Demand) { + assert(demand > 0) + + guard let downstream = downstream else { return } + + self.downstream = nil + streamHandler { stream in + _ = downstream.receive(stream) + if case .complete = stream.event { + downstream.receive(completion: .finished) + } + }.resume() + } + + func cancel() { + request.cancel() + downstream = nil + } + } +} + +extension DataStreamRequest { + /// Creates a `DataStreamPublisher` for this instance using the given `DataStreamSerializer` and `DispatchQueue`. + /// + /// - Parameters: + /// - serializer: `DataStreamSerializer` used to serialize the streamed `Data`. + /// - queue: `DispatchQueue` on which the `DataRequest.Stream` values will be published. `.main` by default. + /// - Returns: The `DataStreamPublisher`. + @available(macOS 10.15, iOS 13, watchOS 6, tvOS 13, *) + public func publishStream(using serializer: Serializer, + on queue: DispatchQueue = .main) -> DataStreamPublisher { + DataStreamPublisher(self, queue: queue, serializer: serializer) + } + + /// Creates a `DataStreamPublisher` for this instance which uses a `PassthroughStreamSerializer` to stream `Data` + /// unserialized. + /// + /// - Parameters: + /// - queue: `DispatchQueue` on which the `DataRequest.Stream` values will be published. `.main` by default. + /// - Returns: The `DataStreamPublisher`. + @available(macOS 10.15, iOS 13, watchOS 6, tvOS 13, *) + public func publishData(queue: DispatchQueue = .main) -> DataStreamPublisher { + publishStream(using: PassthroughStreamSerializer(), on: queue) + } + + /// Creates a `DataStreamPublisher` for this instance which uses a `StringStreamSerializer` to serialize stream + /// `Data` values into `String` values. + /// + /// - Parameters: + /// - queue: `DispatchQueue` on which the `DataRequest.Stream` values will be published. `.main` by default. + /// - Returns: The `DataStreamPublisher`. + @available(macOS 10.15, iOS 13, watchOS 6, tvOS 13, *) + public func publishString(queue: DispatchQueue = .main) -> DataStreamPublisher { + publishStream(using: StringStreamSerializer(), on: queue) + } + + /// Creates a `DataStreamPublisher` for this instance which uses a `DecodableStreamSerializer` with the provided + /// parameters to serialize stream `Data` values into the provided type. + /// + /// - Parameters: + /// - type: `Decodable` type to which to decode stream `Data`. Inferred from the context by default. + /// - queue: `DispatchQueue` on which the `DataRequest.Stream` values will be published. `.main` by default. + /// - decoder: `DataDecoder` instance used to decode stream `Data`. `JSONDecoder()` by default. + /// - preprocessor: `DataPreprocessor` which filters incoming stream `Data` before serialization. + /// `PassthroughPreprocessor()` by default. + /// - Returns: The `DataStreamPublisher`. + @available(macOS 10.15, iOS 13, watchOS 6, tvOS 13, *) + public func publishDecodable(type: T.Type = T.self, + queue: DispatchQueue = .main, + decoder: DataDecoder = JSONDecoder(), + preprocessor: DataPreprocessor = PassthroughPreprocessor()) -> DataStreamPublisher { + publishStream(using: DecodableStreamSerializer(decoder: decoder, + dataPreprocessor: preprocessor), + on: queue) + } +} + +/// A Combine `Publisher` that publishes the `DownloadResponse` of the provided `DownloadRequest`. +@available(macOS 10.15, iOS 13, watchOS 6, tvOS 13, *) +public struct DownloadResponsePublisher: Publisher { + public typealias Output = DownloadResponse + public typealias Failure = Never + + private typealias Handler = (@escaping (_ response: DownloadResponse) -> Void) -> DownloadRequest + + private let request: DownloadRequest + private let responseHandler: Handler + + /// Creates an instance which will serialize responses using the provided `ResponseSerializer`. + /// + /// - Parameters: + /// - request: `DownloadRequest` for which to publish the response. + /// - queue: `DispatchQueue` on which the `DownloadResponse` value will be published. `.main` by default. + /// - serializer: `ResponseSerializer` used to produce the published `DownloadResponse`. + public init(_ request: DownloadRequest, queue: DispatchQueue, serializer: Serializer) + where Value == Serializer.SerializedObject { + self.request = request + responseHandler = { request.response(queue: queue, responseSerializer: serializer, completionHandler: $0) } + } + + /// Creates an instance which will serialize responses using the provided `DownloadResponseSerializerProtocol` value. + /// + /// - Parameters: + /// - request: `DownloadRequest` for which to publish the response. + /// - queue: `DispatchQueue` on which the `DataResponse` value will be published. `.main` by default. + /// - serializer: `DownloadResponseSerializerProtocol` used to produce the published `DownloadResponse`. + @available(macOS 10.15, iOS 13, watchOS 6, tvOS 13, *) + public init(_ request: DownloadRequest, + queue: DispatchQueue, + serializer: Serializer) + where Value == Serializer.SerializedObject { + self.request = request + responseHandler = { request.response(queue: queue, responseSerializer: serializer, completionHandler: $0) } + } + + /// Publishes only the `Result` of the `DownloadResponse` value. + /// + /// - Returns: The `AnyPublisher` publishing the `Result` value. + public func result() -> AnyPublisher, Never> { + map(\.result).eraseToAnyPublisher() + } + + /// Publishes the `Result` of the `DownloadResponse` as a single `Value` or fail with the `AFError` instance. + /// + /// - Returns: The `AnyPublisher` publishing the stream. + public func value() -> AnyPublisher { + setFailureType(to: AFError.self).flatMap(\.result.publisher).eraseToAnyPublisher() + } + + public func receive(subscriber: S) where S: Subscriber, DownloadResponsePublisher.Failure == S.Failure, DownloadResponsePublisher.Output == S.Input { + subscriber.receive(subscription: Inner(request: request, + responseHandler: responseHandler, + downstream: subscriber)) + } + + private final class Inner: Subscription + where Downstream.Input == Output { + typealias Failure = Downstream.Failure + + @Protected + private var downstream: Downstream? + private let request: DownloadRequest + private let responseHandler: Handler + + init(request: DownloadRequest, responseHandler: @escaping Handler, downstream: Downstream) { + self.request = request + self.responseHandler = responseHandler + self.downstream = downstream + } + + func request(_ demand: Subscribers.Demand) { + assert(demand > 0) + + guard let downstream = downstream else { return } + + self.downstream = nil + responseHandler { response in + _ = downstream.receive(response) + downstream.receive(completion: .finished) + }.resume() + } + + func cancel() { + request.cancel() + downstream = nil + } + } +} + +extension DownloadRequest { + /// Creates a `DownloadResponsePublisher` for this instance using the given `ResponseSerializer` and `DispatchQueue`. + /// + /// - Parameters: + /// - serializer: `ResponseSerializer` used to serialize the response `Data` from disk. + /// - queue: `DispatchQueue` on which the `DownloadResponse` will be published.`.main` by default. + /// + /// - Returns: The `DownloadResponsePublisher`. + @available(macOS 10.15, iOS 13, watchOS 6, tvOS 13, *) + public func publishResponse(using serializer: Serializer, on queue: DispatchQueue = .main) -> DownloadResponsePublisher + where Serializer.SerializedObject == T { + DownloadResponsePublisher(self, queue: queue, serializer: serializer) + } + + /// Creates a `DownloadResponsePublisher` for this instance using the given `DownloadResponseSerializerProtocol` and + /// `DispatchQueue`. + /// + /// - Parameters: + /// - serializer: `DownloadResponseSerializer` used to serialize the response `Data` from disk. + /// - queue: `DispatchQueue` on which the `DownloadResponse` will be published.`.main` by default. + /// + /// - Returns: The `DownloadResponsePublisher`. + @available(macOS 10.15, iOS 13, watchOS 6, tvOS 13, *) + public func publishResponse(using serializer: Serializer, on queue: DispatchQueue = .main) -> DownloadResponsePublisher + where Serializer.SerializedObject == T { + DownloadResponsePublisher(self, queue: queue, serializer: serializer) + } + + /// Creates a `DownloadResponsePublisher` for this instance and uses a `URLResponseSerializer` to serialize the + /// response. + /// + /// - Parameter queue: `DispatchQueue` on which the `DownloadResponse` will be published. `.main` by default. + /// + /// - Returns: The `DownloadResponsePublisher`. + @available(macOS 10.15, iOS 13, watchOS 6, tvOS 13, *) + public func publishURL(queue: DispatchQueue = .main) -> DownloadResponsePublisher { + publishResponse(using: URLResponseSerializer(), on: queue) + } + + /// Creates a `DownloadResponsePublisher` for this instance and uses a `DataResponseSerializer` to serialize the + /// response. + /// + /// - Parameters: + /// - queue: `DispatchQueue` on which the `DownloadResponse` will be published. `.main` by default. + /// - preprocessor: `DataPreprocessor` which filters the `Data` before serialization. `PassthroughPreprocessor()` + /// by default. + /// - emptyResponseCodes: `Set` of HTTP status codes for which empty responses are allowed. `[204, 205]` by + /// default. + /// - emptyRequestMethods: `Set` of `HTTPMethod`s for which empty responses are allowed, regardless of + /// status code. `[.head]` by default. + /// + /// - Returns: The `DownloadResponsePublisher`. + @available(macOS 10.15, iOS 13, watchOS 6, tvOS 13, *) + public func publishData(queue: DispatchQueue = .main, + preprocessor: DataPreprocessor = DataResponseSerializer.defaultDataPreprocessor, + emptyResponseCodes: Set = DataResponseSerializer.defaultEmptyResponseCodes, + emptyRequestMethods: Set = DataResponseSerializer.defaultEmptyRequestMethods) -> DownloadResponsePublisher { + publishResponse(using: DataResponseSerializer(dataPreprocessor: preprocessor, + emptyResponseCodes: emptyResponseCodes, + emptyRequestMethods: emptyRequestMethods), + on: queue) + } + + /// Creates a `DownloadResponsePublisher` for this instance and uses a `StringResponseSerializer` to serialize the + /// response. + /// + /// - Parameters: + /// - queue: `DispatchQueue` on which the `DataResponse` will be published. `.main` by default. + /// - preprocessor: `DataPreprocessor` which filters the `Data` before serialization. `PassthroughPreprocessor()` + /// by default. + /// - encoding: `String.Encoding` to parse the response. `nil` by default, in which case the encoding + /// will be determined by the server response, falling back to the default HTTP character + /// set, `ISO-8859-1`. + /// - emptyResponseCodes: `Set` of HTTP status codes for which empty responses are allowed. `[204, 205]` by + /// default. + /// - emptyRequestMethods: `Set` of `HTTPMethod`s for which empty responses are allowed, regardless of + /// status code. `[.head]` by default. + /// + /// - Returns: The `DownloadResponsePublisher`. + @available(macOS 10.15, iOS 13, watchOS 6, tvOS 13, *) + public func publishString(queue: DispatchQueue = .main, + preprocessor: DataPreprocessor = StringResponseSerializer.defaultDataPreprocessor, + encoding: String.Encoding? = nil, + emptyResponseCodes: Set = StringResponseSerializer.defaultEmptyResponseCodes, + emptyRequestMethods: Set = StringResponseSerializer.defaultEmptyRequestMethods) -> DownloadResponsePublisher { + publishResponse(using: StringResponseSerializer(dataPreprocessor: preprocessor, + encoding: encoding, + emptyResponseCodes: emptyResponseCodes, + emptyRequestMethods: emptyRequestMethods), + on: queue) + } + + @_disfavoredOverload + @available(macOS 10.15, iOS 13, watchOS 6, tvOS 13, *) + @available(*, deprecated, message: "Renamed publishDecodable(type:queue:preprocessor:decoder:emptyResponseCodes:emptyRequestMethods).") + public func publishDecodable(type: T.Type = T.self, + queue: DispatchQueue = .main, + preprocessor: DataPreprocessor = DecodableResponseSerializer.defaultDataPreprocessor, + decoder: DataDecoder = JSONDecoder(), + emptyResponseCodes: Set = DecodableResponseSerializer.defaultEmptyResponseCodes, + emptyResponseMethods: Set = DecodableResponseSerializer.defaultEmptyRequestMethods) -> DownloadResponsePublisher { + publishResponse(using: DecodableResponseSerializer(dataPreprocessor: preprocessor, + decoder: decoder, + emptyResponseCodes: emptyResponseCodes, + emptyRequestMethods: emptyResponseMethods), + on: queue) + } + + /// Creates a `DownloadResponsePublisher` for this instance and uses a `DecodableResponseSerializer` to serialize + /// the response. + /// + /// - Parameters: + /// - type: `Decodable` type to which to decode response `Data`. Inferred from the context by default. + /// - queue: `DispatchQueue` on which the `DataResponse` will be published. `.main` by default. + /// - preprocessor: `DataPreprocessor` which filters the `Data` before serialization. + /// `PassthroughPreprocessor()` by default. + /// - decoder: `DataDecoder` instance used to decode response `Data`. `JSONDecoder()` by default. + /// - emptyResponseCodes: `Set` of HTTP status codes for which empty responses are allowed. `[204, 205]` by + /// default. + /// - emptyRequestMethods: `Set` of `HTTPMethod`s for which empty responses are allowed, regardless + /// of status code. `[.head]` by default. + /// + /// - Returns: The `DownloadResponsePublisher`. + @available(macOS 10.15, iOS 13, watchOS 6, tvOS 13, *) + public func publishDecodable(type: T.Type = T.self, + queue: DispatchQueue = .main, + preprocessor: DataPreprocessor = DecodableResponseSerializer.defaultDataPreprocessor, + decoder: DataDecoder = JSONDecoder(), + emptyResponseCodes: Set = DecodableResponseSerializer.defaultEmptyResponseCodes, + emptyRequestMethods: Set = DecodableResponseSerializer.defaultEmptyRequestMethods) -> DownloadResponsePublisher { + publishResponse(using: DecodableResponseSerializer(dataPreprocessor: preprocessor, + decoder: decoder, + emptyResponseCodes: emptyResponseCodes, + emptyRequestMethods: emptyRequestMethods), + on: queue) + } +} + +@available(macOS 10.15, iOS 13, watchOS 6, tvOS 13, *) +extension DownloadResponsePublisher where Value == URL? { + /// Creates an instance which publishes a `DownloadResponse` value without serialization. + @available(macOS 10.15, iOS 13, watchOS 6, tvOS 13, *) + public init(_ request: DownloadRequest, queue: DispatchQueue) { + self.request = request + responseHandler = { request.response(queue: queue, completionHandler: $0) } + } +} + +extension DownloadRequest { + /// Creates a `DownloadResponsePublisher` for this instance which does not serialize the response before publishing. + /// + /// - Parameter queue: `DispatchQueue` on which the `DownloadResponse` will be published. `.main` by default. + /// + /// - Returns: The `DownloadResponsePublisher`. + @available(macOS 10.15, iOS 13, watchOS 6, tvOS 13, *) + public func publishUnserialized(on queue: DispatchQueue = .main) -> DownloadResponsePublisher { + DownloadResponsePublisher(self, queue: queue) + } +} + +#endif diff --git a/Pods/Alamofire/Source/Concurrency.swift b/Pods/Alamofire/Source/Concurrency.swift new file mode 100644 index 0000000..95008f9 --- /dev/null +++ b/Pods/Alamofire/Source/Concurrency.swift @@ -0,0 +1,704 @@ +// +// Concurrency.swift +// +// Copyright (c) 2021 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 compiler(>=5.6.0) && canImport(_Concurrency) + +import Foundation + +// MARK: - Request Event Streams + +@available(macOS 10.15, iOS 13, tvOS 13, watchOS 6, *) +extension Request { + /// Creates a `StreamOf` for the instance's upload progress. + /// + /// - Parameter bufferingPolicy: `BufferingPolicy` that determines the stream's buffering behavior.`.unbounded` by default. + /// + /// - Returns: The `StreamOf`. + public func uploadProgress(bufferingPolicy: StreamOf.BufferingPolicy = .unbounded) -> StreamOf { + stream(bufferingPolicy: bufferingPolicy) { [unowned self] continuation in + uploadProgress(queue: .singleEventQueue) { progress in + continuation.yield(progress) + } + } + } + + /// Creates a `StreamOf` for the instance's download progress. + /// + /// - Parameter bufferingPolicy: `BufferingPolicy` that determines the stream's buffering behavior.`.unbounded` by default. + /// + /// - Returns: The `StreamOf`. + public func downloadProgress(bufferingPolicy: StreamOf.BufferingPolicy = .unbounded) -> StreamOf { + stream(bufferingPolicy: bufferingPolicy) { [unowned self] continuation in + downloadProgress(queue: .singleEventQueue) { progress in + continuation.yield(progress) + } + } + } + + /// Creates a `StreamOf` for the `URLRequest`s produced for the instance. + /// + /// - Parameter bufferingPolicy: `BufferingPolicy` that determines the stream's buffering behavior.`.unbounded` by default. + /// + /// - Returns: The `StreamOf`. + public func urlRequests(bufferingPolicy: StreamOf.BufferingPolicy = .unbounded) -> StreamOf { + stream(bufferingPolicy: bufferingPolicy) { [unowned self] continuation in + onURLRequestCreation(on: .singleEventQueue) { request in + continuation.yield(request) + } + } + } + + /// Creates a `StreamOf` for the `URLSessionTask`s produced for the instance. + /// + /// - Parameter bufferingPolicy: `BufferingPolicy` that determines the stream's buffering behavior.`.unbounded` by default. + /// + /// - Returns: The `StreamOf`. + public func urlSessionTasks(bufferingPolicy: StreamOf.BufferingPolicy = .unbounded) -> StreamOf { + stream(bufferingPolicy: bufferingPolicy) { [unowned self] continuation in + onURLSessionTaskCreation(on: .singleEventQueue) { task in + continuation.yield(task) + } + } + } + + /// Creates a `StreamOf` for the cURL descriptions produced for the instance. + /// + /// - Parameter bufferingPolicy: `BufferingPolicy` that determines the stream's buffering behavior.`.unbounded` by default. + /// + /// - Returns: The `StreamOf`. + public func cURLDescriptions(bufferingPolicy: StreamOf.BufferingPolicy = .unbounded) -> StreamOf { + stream(bufferingPolicy: bufferingPolicy) { [unowned self] continuation in + cURLDescription(on: .singleEventQueue) { description in + continuation.yield(description) + } + } + } + + private func stream(of type: T.Type = T.self, + bufferingPolicy: StreamOf.BufferingPolicy = .unbounded, + yielder: @escaping (StreamOf.Continuation) -> Void) -> StreamOf { + StreamOf(bufferingPolicy: bufferingPolicy) { [unowned self] continuation in + yielder(continuation) + // Must come after serializers run in order to catch retry progress. + onFinish { + continuation.finish() + } + } + } +} + +// MARK: - DataTask + +/// Value used to `await` a `DataResponse` and associated values. +@available(macOS 10.15, iOS 13, tvOS 13, watchOS 6, *) +public struct DataTask { + /// `DataResponse` produced by the `DataRequest` and its response handler. + public var response: DataResponse { + get async { + if shouldAutomaticallyCancel { + return await withTaskCancellationHandler { + await task.value + } onCancel: { + cancel() + } + } else { + return await task.value + } + } + } + + /// `Result` of any response serialization performed for the `response`. + public var result: Result { + get async { await response.result } + } + + /// `Value` returned by the `response`. + public var value: Value { + get async throws { + try await result.get() + } + } + + private let request: DataRequest + private let task: Task, Never> + private let shouldAutomaticallyCancel: Bool + + fileprivate init(request: DataRequest, task: Task, Never>, shouldAutomaticallyCancel: Bool) { + self.request = request + self.task = task + self.shouldAutomaticallyCancel = shouldAutomaticallyCancel + } + + /// Cancel the underlying `DataRequest` and `Task`. + public func cancel() { + task.cancel() + } + + /// Resume the underlying `DataRequest`. + public func resume() { + request.resume() + } + + /// Suspend the underlying `DataRequest`. + public func suspend() { + request.suspend() + } +} + +@available(macOS 10.15, iOS 13, tvOS 13, watchOS 6, *) +extension DataRequest { + /// Creates a `DataTask` to `await` a `Data` value. + /// + /// - Parameters: + /// - shouldAutomaticallyCancel: `Bool` determining whether or not the request should be cancelled when the + /// enclosing async context is cancelled. Only applies to `DataTask`'s async + /// properties. `false` by default. + /// - dataPreprocessor: `DataPreprocessor` which processes the received `Data` before completion. + /// - emptyResponseCodes: HTTP response codes for which empty responses are allowed. `[204, 205]` by default. + /// - emptyRequestMethods: `HTTPMethod`s for which empty responses are always valid. `[.head]` by default. + /// + /// - Returns: The `DataTask`. + public func serializingData(automaticallyCancelling shouldAutomaticallyCancel: Bool = false, + dataPreprocessor: DataPreprocessor = DataResponseSerializer.defaultDataPreprocessor, + emptyResponseCodes: Set = DataResponseSerializer.defaultEmptyResponseCodes, + emptyRequestMethods: Set = DataResponseSerializer.defaultEmptyRequestMethods) -> DataTask { + serializingResponse(using: DataResponseSerializer(dataPreprocessor: dataPreprocessor, + emptyResponseCodes: emptyResponseCodes, + emptyRequestMethods: emptyRequestMethods), + automaticallyCancelling: shouldAutomaticallyCancel) + } + + /// Creates a `DataTask` to `await` serialization of a `Decodable` value. + /// + /// - Parameters: + /// - type: `Decodable` type to decode from response data. + /// - shouldAutomaticallyCancel: `Bool` determining whether or not the request should be cancelled when the + /// enclosing async context is cancelled. Only applies to `DataTask`'s async + /// properties. `false` by default. + /// - dataPreprocessor: `DataPreprocessor` which processes the received `Data` before calling the serializer. + /// `PassthroughPreprocessor()` by default. + /// - decoder: `DataDecoder` to use to decode the response. `JSONDecoder()` by default. + /// - emptyResponseCodes: HTTP status codes for which empty responses are always valid. `[204, 205]` by default. + /// - emptyRequestMethods: `HTTPMethod`s for which empty responses are always valid. `[.head]` by default. + /// + /// - Returns: The `DataTask`. + public func serializingDecodable(_ type: Value.Type = Value.self, + automaticallyCancelling shouldAutomaticallyCancel: Bool = false, + dataPreprocessor: DataPreprocessor = DecodableResponseSerializer.defaultDataPreprocessor, + decoder: DataDecoder = JSONDecoder(), + emptyResponseCodes: Set = DecodableResponseSerializer.defaultEmptyResponseCodes, + emptyRequestMethods: Set = DecodableResponseSerializer.defaultEmptyRequestMethods) -> DataTask { + serializingResponse(using: DecodableResponseSerializer(dataPreprocessor: dataPreprocessor, + decoder: decoder, + emptyResponseCodes: emptyResponseCodes, + emptyRequestMethods: emptyRequestMethods), + automaticallyCancelling: shouldAutomaticallyCancel) + } + + /// Creates a `DataTask` to `await` serialization of a `String` value. + /// + /// - Parameters: + /// - shouldAutomaticallyCancel: `Bool` determining whether or not the request should be cancelled when the + /// enclosing async context is cancelled. Only applies to `DataTask`'s async + /// properties. `false` by default. + /// - dataPreprocessor: `DataPreprocessor` which processes the received `Data` before calling the serializer. + /// `PassthroughPreprocessor()` by default. + /// - encoding: `String.Encoding` to use during serialization. Defaults to `nil`, in which case + /// the encoding will be determined from the server response, falling back to the + /// default HTTP character set, `ISO-8859-1`. + /// - emptyResponseCodes: HTTP status codes for which empty responses are always valid. `[204, 205]` by default. + /// - emptyRequestMethods: `HTTPMethod`s for which empty responses are always valid. `[.head]` by default. + /// + /// - Returns: The `DataTask`. + public func serializingString(automaticallyCancelling shouldAutomaticallyCancel: Bool = false, + dataPreprocessor: DataPreprocessor = StringResponseSerializer.defaultDataPreprocessor, + encoding: String.Encoding? = nil, + emptyResponseCodes: Set = StringResponseSerializer.defaultEmptyResponseCodes, + emptyRequestMethods: Set = StringResponseSerializer.defaultEmptyRequestMethods) -> DataTask { + serializingResponse(using: StringResponseSerializer(dataPreprocessor: dataPreprocessor, + encoding: encoding, + emptyResponseCodes: emptyResponseCodes, + emptyRequestMethods: emptyRequestMethods), + automaticallyCancelling: shouldAutomaticallyCancel) + } + + /// Creates a `DataTask` to `await` serialization using the provided `ResponseSerializer` instance. + /// + /// - Parameters: + /// - serializer: `ResponseSerializer` responsible for serializing the request, response, and data. + /// - shouldAutomaticallyCancel: `Bool` determining whether or not the request should be cancelled when the + /// enclosing async context is cancelled. Only applies to `DataTask`'s async + /// properties. `false` by default. + /// + /// - Returns: The `DataTask`. + public func serializingResponse(using serializer: Serializer, + automaticallyCancelling shouldAutomaticallyCancel: Bool = false) + -> DataTask { + dataTask(automaticallyCancelling: shouldAutomaticallyCancel) { + self.response(queue: .singleEventQueue, + responseSerializer: serializer, + completionHandler: $0) + } + } + + /// Creates a `DataTask` to `await` serialization using the provided `DataResponseSerializerProtocol` instance. + /// + /// - Parameters: + /// - serializer: `DataResponseSerializerProtocol` responsible for serializing the request, + /// response, and data. + /// - shouldAutomaticallyCancel: `Bool` determining whether or not the request should be cancelled when the + /// enclosing async context is cancelled. Only applies to `DataTask`'s async + /// properties. `false` by default. + /// + /// - Returns: The `DataTask`. + public func serializingResponse(using serializer: Serializer, + automaticallyCancelling shouldAutomaticallyCancel: Bool = false) + -> DataTask { + dataTask(automaticallyCancelling: shouldAutomaticallyCancel) { + self.response(queue: .singleEventQueue, + responseSerializer: serializer, + completionHandler: $0) + } + } + + private func dataTask(automaticallyCancelling shouldAutomaticallyCancel: Bool, + forResponse onResponse: @escaping (@escaping (DataResponse) -> Void) -> Void) + -> DataTask { + let task = Task { + await withTaskCancellationHandler { + await withCheckedContinuation { continuation in + onResponse { + continuation.resume(returning: $0) + } + } + } onCancel: { + self.cancel() + } + } + + return DataTask(request: self, task: task, shouldAutomaticallyCancel: shouldAutomaticallyCancel) + } +} + +// MARK: - DownloadTask + +/// Value used to `await` a `DownloadResponse` and associated values. +@available(macOS 10.15, iOS 13, tvOS 13, watchOS 6, *) +public struct DownloadTask { + /// `DownloadResponse` produced by the `DownloadRequest` and its response handler. + public var response: DownloadResponse { + get async { + if shouldAutomaticallyCancel { + return await withTaskCancellationHandler { + await task.value + } onCancel: { + cancel() + } + } else { + return await task.value + } + } + } + + /// `Result` of any response serialization performed for the `response`. + public var result: Result { + get async { await response.result } + } + + /// `Value` returned by the `response`. + public var value: Value { + get async throws { + try await result.get() + } + } + + private let task: Task, Never> + private let request: DownloadRequest + private let shouldAutomaticallyCancel: Bool + + fileprivate init(request: DownloadRequest, task: Task, Never>, shouldAutomaticallyCancel: Bool) { + self.request = request + self.task = task + self.shouldAutomaticallyCancel = shouldAutomaticallyCancel + } + + /// Cancel the underlying `DownloadRequest` and `Task`. + public func cancel() { + task.cancel() + } + + /// Resume the underlying `DownloadRequest`. + public func resume() { + request.resume() + } + + /// Suspend the underlying `DownloadRequest`. + public func suspend() { + request.suspend() + } +} + +@available(macOS 10.15, iOS 13, tvOS 13, watchOS 6, *) +extension DownloadRequest { + /// Creates a `DownloadTask` to `await` a `Data` value. + /// + /// - Parameters: + /// - shouldAutomaticallyCancel: `Bool` determining whether or not the request should be cancelled when the + /// enclosing async context is cancelled. Only applies to `DownloadTask`'s async + /// properties. `false` by default. + /// - dataPreprocessor: `DataPreprocessor` which processes the received `Data` before completion. + /// - emptyResponseCodes: HTTP response codes for which empty responses are allowed. `[204, 205]` by default. + /// - emptyRequestMethods: `HTTPMethod`s for which empty responses are always valid. `[.head]` by default. + /// + /// - Returns: The `DownloadTask`. + public func serializingData(automaticallyCancelling shouldAutomaticallyCancel: Bool = false, + dataPreprocessor: DataPreprocessor = DataResponseSerializer.defaultDataPreprocessor, + emptyResponseCodes: Set = DataResponseSerializer.defaultEmptyResponseCodes, + emptyRequestMethods: Set = DataResponseSerializer.defaultEmptyRequestMethods) -> DownloadTask { + serializingDownload(using: DataResponseSerializer(dataPreprocessor: dataPreprocessor, + emptyResponseCodes: emptyResponseCodes, + emptyRequestMethods: emptyRequestMethods), + automaticallyCancelling: shouldAutomaticallyCancel) + } + + /// Creates a `DownloadTask` to `await` serialization of a `Decodable` value. + /// + /// - Note: This serializer reads the entire response into memory before parsing. + /// + /// - Parameters: + /// - type: `Decodable` type to decode from response data. + /// - shouldAutomaticallyCancel: `Bool` determining whether or not the request should be cancelled when the + /// enclosing async context is cancelled. Only applies to `DownloadTask`'s async + /// properties. `false` by default. + /// - dataPreprocessor: `DataPreprocessor` which processes the received `Data` before calling the serializer. + /// `PassthroughPreprocessor()` by default. + /// - decoder: `DataDecoder` to use to decode the response. `JSONDecoder()` by default. + /// - emptyResponseCodes: HTTP status codes for which empty responses are always valid. `[204, 205]` by default. + /// - emptyRequestMethods: `HTTPMethod`s for which empty responses are always valid. `[.head]` by default. + /// + /// - Returns: The `DownloadTask`. + public func serializingDecodable(_ type: Value.Type = Value.self, + automaticallyCancelling shouldAutomaticallyCancel: Bool = false, + dataPreprocessor: DataPreprocessor = DecodableResponseSerializer.defaultDataPreprocessor, + decoder: DataDecoder = JSONDecoder(), + emptyResponseCodes: Set = DecodableResponseSerializer.defaultEmptyResponseCodes, + emptyRequestMethods: Set = DecodableResponseSerializer.defaultEmptyRequestMethods) -> DownloadTask { + serializingDownload(using: DecodableResponseSerializer(dataPreprocessor: dataPreprocessor, + decoder: decoder, + emptyResponseCodes: emptyResponseCodes, + emptyRequestMethods: emptyRequestMethods), + automaticallyCancelling: shouldAutomaticallyCancel) + } + + /// Creates a `DownloadTask` to `await` serialization of the downloaded file's `URL` on disk. + /// + /// - Parameters: + /// - shouldAutomaticallyCancel: `Bool` determining whether or not the request should be cancelled when the + /// enclosing async context is cancelled. Only applies to `DownloadTask`'s async + /// properties. `false` by default. + /// + /// - Returns: The `DownloadTask`. + public func serializingDownloadedFileURL(automaticallyCancelling shouldAutomaticallyCancel: Bool = false) -> DownloadTask { + serializingDownload(using: URLResponseSerializer(), + automaticallyCancelling: shouldAutomaticallyCancel) + } + + /// Creates a `DownloadTask` to `await` serialization of a `String` value. + /// + /// - Parameters: + /// - shouldAutomaticallyCancel: `Bool` determining whether or not the request should be cancelled when the + /// enclosing async context is cancelled. Only applies to `DownloadTask`'s async + /// properties. `false` by default. + /// - dataPreprocessor: `DataPreprocessor` which processes the received `Data` before calling the + /// serializer. `PassthroughPreprocessor()` by default. + /// - encoding: `String.Encoding` to use during serialization. Defaults to `nil`, in which case + /// the encoding will be determined from the server response, falling back to the + /// default HTTP character set, `ISO-8859-1`. + /// - emptyResponseCodes: HTTP status codes for which empty responses are always valid. `[204, 205]` by default. + /// - emptyRequestMethods: `HTTPMethod`s for which empty responses are always valid. `[.head]` by default. + /// + /// - Returns: The `DownloadTask`. + public func serializingString(automaticallyCancelling shouldAutomaticallyCancel: Bool = false, + dataPreprocessor: DataPreprocessor = StringResponseSerializer.defaultDataPreprocessor, + encoding: String.Encoding? = nil, + emptyResponseCodes: Set = StringResponseSerializer.defaultEmptyResponseCodes, + emptyRequestMethods: Set = StringResponseSerializer.defaultEmptyRequestMethods) -> DownloadTask { + serializingDownload(using: StringResponseSerializer(dataPreprocessor: dataPreprocessor, + encoding: encoding, + emptyResponseCodes: emptyResponseCodes, + emptyRequestMethods: emptyRequestMethods), + automaticallyCancelling: shouldAutomaticallyCancel) + } + + /// Creates a `DownloadTask` to `await` serialization using the provided `ResponseSerializer` instance. + /// + /// - Parameters: + /// - serializer: `ResponseSerializer` responsible for serializing the request, response, and data. + /// - shouldAutomaticallyCancel: `Bool` determining whether or not the request should be cancelled when the + /// enclosing async context is cancelled. Only applies to `DownloadTask`'s async + /// properties. `false` by default. + /// + /// - Returns: The `DownloadTask`. + public func serializingDownload(using serializer: Serializer, + automaticallyCancelling shouldAutomaticallyCancel: Bool = false) + -> DownloadTask { + downloadTask(automaticallyCancelling: shouldAutomaticallyCancel) { + self.response(queue: .singleEventQueue, + responseSerializer: serializer, + completionHandler: $0) + } + } + + /// Creates a `DownloadTask` to `await` serialization using the provided `DownloadResponseSerializerProtocol` + /// instance. + /// + /// - Parameters: + /// - serializer: `DownloadResponseSerializerProtocol` responsible for serializing the request, + /// response, and data. + /// - shouldAutomaticallyCancel: `Bool` determining whether or not the request should be cancelled when the + /// enclosing async context is cancelled. Only applies to `DownloadTask`'s async + /// properties. `false` by default. + /// + /// - Returns: The `DownloadTask`. + public func serializingDownload(using serializer: Serializer, + automaticallyCancelling shouldAutomaticallyCancel: Bool = false) + -> DownloadTask { + downloadTask(automaticallyCancelling: shouldAutomaticallyCancel) { + self.response(queue: .singleEventQueue, + responseSerializer: serializer, + completionHandler: $0) + } + } + + private func downloadTask(automaticallyCancelling shouldAutomaticallyCancel: Bool, + forResponse onResponse: @escaping (@escaping (DownloadResponse) -> Void) -> Void) + -> DownloadTask { + let task = Task { + await withTaskCancellationHandler { + await withCheckedContinuation { continuation in + onResponse { + continuation.resume(returning: $0) + } + } + } onCancel: { + self.cancel() + } + } + + return DownloadTask(request: self, task: task, shouldAutomaticallyCancel: shouldAutomaticallyCancel) + } +} + +// MARK: - DataStreamTask + +@available(macOS 10.15, iOS 13, tvOS 13, watchOS 6, *) +public struct DataStreamTask { + // Type of created streams. + public typealias Stream = StreamOf> + + private let request: DataStreamRequest + + fileprivate init(request: DataStreamRequest) { + self.request = request + } + + /// Creates a `Stream` of `Data` values from the underlying `DataStreamRequest`. + /// + /// - Parameters: + /// - shouldAutomaticallyCancel: `Bool` indicating whether the underlying `DataStreamRequest` should be canceled + /// which observation of the stream stops. `true` by default. + /// - bufferingPolicy: ` BufferingPolicy` that determines the stream's buffering behavior.`.unbounded` by default. + /// + /// - Returns: The `Stream`. + public func streamingData(automaticallyCancelling shouldAutomaticallyCancel: Bool = true, bufferingPolicy: Stream.BufferingPolicy = .unbounded) -> Stream { + createStream(automaticallyCancelling: shouldAutomaticallyCancel, bufferingPolicy: bufferingPolicy) { onStream in + request.responseStream(on: .streamCompletionQueue(forRequestID: request.id), stream: onStream) + } + } + + /// Creates a `Stream` of `UTF-8` `String`s from the underlying `DataStreamRequest`. + /// + /// - Parameters: + /// - shouldAutomaticallyCancel: `Bool` indicating whether the underlying `DataStreamRequest` should be canceled + /// which observation of the stream stops. `true` by default. + /// - bufferingPolicy: ` BufferingPolicy` that determines the stream's buffering behavior.`.unbounded` by default. + /// - Returns: + public func streamingStrings(automaticallyCancelling shouldAutomaticallyCancel: Bool = true, bufferingPolicy: Stream.BufferingPolicy = .unbounded) -> Stream { + createStream(automaticallyCancelling: shouldAutomaticallyCancel, bufferingPolicy: bufferingPolicy) { onStream in + request.responseStreamString(on: .streamCompletionQueue(forRequestID: request.id), stream: onStream) + } + } + + /// Creates a `Stream` of `Decodable` values from the underlying `DataStreamRequest`. + /// + /// - Parameters: + /// - type: `Decodable` type to be serialized from stream payloads. + /// - shouldAutomaticallyCancel: `Bool` indicating whether the underlying `DataStreamRequest` should be canceled + /// which observation of the stream stops. `true` by default. + /// - bufferingPolicy: `BufferingPolicy` that determines the stream's buffering behavior.`.unbounded` by default. + /// + /// - Returns: The `Stream`. + public func streamingDecodables(_ type: T.Type = T.self, + automaticallyCancelling shouldAutomaticallyCancel: Bool = true, + bufferingPolicy: Stream.BufferingPolicy = .unbounded) + -> Stream where T: Decodable { + streamingResponses(serializedUsing: DecodableStreamSerializer(), + automaticallyCancelling: shouldAutomaticallyCancel, + bufferingPolicy: bufferingPolicy) + } + + /// Creates a `Stream` of values using the provided `DataStreamSerializer` from the underlying `DataStreamRequest`. + /// + /// - Parameters: + /// - serializer: `DataStreamSerializer` to use to serialize incoming `Data`. + /// - shouldAutomaticallyCancel: `Bool` indicating whether the underlying `DataStreamRequest` should be canceled + /// which observation of the stream stops. `true` by default. + /// - bufferingPolicy: `BufferingPolicy` that determines the stream's buffering behavior.`.unbounded` by default. + /// + /// - Returns: The `Stream`. + public func streamingResponses(serializedUsing serializer: Serializer, + automaticallyCancelling shouldAutomaticallyCancel: Bool = true, + bufferingPolicy: Stream.BufferingPolicy = .unbounded) + -> Stream { + createStream(automaticallyCancelling: shouldAutomaticallyCancel, bufferingPolicy: bufferingPolicy) { onStream in + request.responseStream(using: serializer, + on: .streamCompletionQueue(forRequestID: request.id), + stream: onStream) + } + } + + private func createStream(automaticallyCancelling shouldAutomaticallyCancel: Bool = true, + bufferingPolicy: Stream.BufferingPolicy = .unbounded, + forResponse onResponse: @escaping (@escaping (DataStreamRequest.Stream) -> Void) -> Void) + -> Stream { + StreamOf(bufferingPolicy: bufferingPolicy) { + guard shouldAutomaticallyCancel, + request.isInitialized || request.isResumed || request.isSuspended else { return } + + cancel() + } builder: { continuation in + onResponse { stream in + continuation.yield(stream) + if case .complete = stream.event { + continuation.finish() + } + } + } + } + + /// Cancel the underlying `DataStreamRequest`. + public func cancel() { + request.cancel() + } + + /// Resume the underlying `DataStreamRequest`. + public func resume() { + request.resume() + } + + /// Suspend the underlying `DataStreamRequest`. + public func suspend() { + request.suspend() + } +} + +@available(macOS 10.15, iOS 13, tvOS 13, watchOS 6, *) +extension DataStreamRequest { + /// Creates a `DataStreamTask` used to `await` streams of serialized values. + /// + /// - Returns: The `DataStreamTask`. + public func streamTask() -> DataStreamTask { + DataStreamTask(request: self) + } +} + +extension DispatchQueue { + fileprivate static let singleEventQueue = DispatchQueue(label: "org.alamofire.concurrencySingleEventQueue", + attributes: .concurrent) + + fileprivate static func streamCompletionQueue(forRequestID id: UUID) -> DispatchQueue { + DispatchQueue(label: "org.alamofire.concurrencyStreamCompletionQueue-\(id)", target: .singleEventQueue) + } +} + +/// An asynchronous sequence generated from an underlying `AsyncStream`. Only produced by Alamofire. +@available(macOS 10.15, iOS 13, tvOS 13, watchOS 6, *) +public struct StreamOf: AsyncSequence { + public typealias AsyncIterator = Iterator + public typealias BufferingPolicy = AsyncStream.Continuation.BufferingPolicy + fileprivate typealias Continuation = AsyncStream.Continuation + + private let bufferingPolicy: BufferingPolicy + private let onTermination: (() -> Void)? + private let builder: (Continuation) -> Void + + fileprivate init(bufferingPolicy: BufferingPolicy = .unbounded, + onTermination: (() -> Void)? = nil, + builder: @escaping (Continuation) -> Void) { + self.bufferingPolicy = bufferingPolicy + self.onTermination = onTermination + self.builder = builder + } + + public func makeAsyncIterator() -> Iterator { + var continuation: AsyncStream.Continuation? + let stream = AsyncStream(bufferingPolicy: bufferingPolicy) { innerContinuation in + continuation = innerContinuation + builder(innerContinuation) + } + + return Iterator(iterator: stream.makeAsyncIterator()) { + continuation?.finish() + onTermination?() + } + } + + public struct Iterator: AsyncIteratorProtocol { + private final class Token { + private let onDeinit: () -> Void + + init(onDeinit: @escaping () -> Void) { + self.onDeinit = onDeinit + } + + deinit { + onDeinit() + } + } + + private var iterator: AsyncStream.AsyncIterator + private let token: Token + + init(iterator: AsyncStream.AsyncIterator, onCancellation: @escaping () -> Void) { + self.iterator = iterator + token = Token(onDeinit: onCancellation) + } + + public mutating func next() async -> Element? { + await iterator.next() + } + } +} + +#endif diff --git a/Pods/Alamofire/Source/DispatchQueue+Alamofire.swift b/Pods/Alamofire/Source/DispatchQueue+Alamofire.swift new file mode 100644 index 0000000..10cd273 --- /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 { + /// Execute the provided closure after a `TimeInterval`. + /// + /// - Parameters: + /// - delay: `TimeInterval` to delay execution. + /// - closure: Closure to execute. + func after(_ delay: TimeInterval, execute closure: @escaping () -> Void) { + asyncAfter(deadline: .now() + delay, execute: closure) + } +} diff --git a/Pods/Alamofire/Source/EventMonitor.swift b/Pods/Alamofire/Source/EventMonitor.swift new file mode 100644 index 0000000..5fe22df --- /dev/null +++ b/Pods/Alamofire/Source/EventMonitor.swift @@ -0,0 +1,892 @@ +// +// EventMonitor.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 + +/// Protocol outlining the lifetime events inside Alamofire. It includes both events received from the various +/// `URLSession` delegate protocols as well as various events from the lifetime of `Request` and its subclasses. +public protocol EventMonitor { + /// The `DispatchQueue` onto which Alamofire's root `CompositeEventMonitor` will dispatch events. `.main` by default. + var queue: DispatchQueue { get } + + // MARK: - URLSession Events + + // MARK: URLSessionDelegate Events + + /// Event called during `URLSessionDelegate`'s `urlSession(_:didBecomeInvalidWithError:)` method. + func urlSession(_ session: URLSession, didBecomeInvalidWithError error: Error?) + + // MARK: URLSessionTaskDelegate Events + + /// Event called during `URLSessionTaskDelegate`'s `urlSession(_:task:didReceive:completionHandler:)` method. + func urlSession(_ session: URLSession, task: URLSessionTask, didReceive challenge: URLAuthenticationChallenge) + + /// Event called during `URLSessionTaskDelegate`'s `urlSession(_:task:didSendBodyData:totalBytesSent:totalBytesExpectedToSend:)` method. + func urlSession(_ session: URLSession, + task: URLSessionTask, + didSendBodyData bytesSent: Int64, + totalBytesSent: Int64, + totalBytesExpectedToSend: Int64) + + /// Event called during `URLSessionTaskDelegate`'s `urlSession(_:task:needNewBodyStream:)` method. + func urlSession(_ session: URLSession, taskNeedsNewBodyStream task: URLSessionTask) + + /// Event called during `URLSessionTaskDelegate`'s `urlSession(_:task:willPerformHTTPRedirection:newRequest:completionHandler:)` method. + func urlSession(_ session: URLSession, + task: URLSessionTask, + willPerformHTTPRedirection response: HTTPURLResponse, + newRequest request: URLRequest) + + /// Event called during `URLSessionTaskDelegate`'s `urlSession(_:task:didFinishCollecting:)` method. + func urlSession(_ session: URLSession, task: URLSessionTask, didFinishCollecting metrics: URLSessionTaskMetrics) + + /// Event called during `URLSessionTaskDelegate`'s `urlSession(_:task:didCompleteWithError:)` method. + func urlSession(_ session: URLSession, task: URLSessionTask, didCompleteWithError error: Error?) + + /// Event called during `URLSessionTaskDelegate`'s `urlSession(_:taskIsWaitingForConnectivity:)` method. + func urlSession(_ session: URLSession, taskIsWaitingForConnectivity task: URLSessionTask) + + // MARK: URLSessionDataDelegate Events + + /// Event called during `URLSessionDataDelegate`'s `urlSession(_:dataTask:didReceive:)` method. + func urlSession(_ session: URLSession, dataTask: URLSessionDataTask, didReceive data: Data) + + /// Event called during `URLSessionDataDelegate`'s `urlSession(_:dataTask:willCacheResponse:completionHandler:)` method. + func urlSession(_ session: URLSession, dataTask: URLSessionDataTask, willCacheResponse proposedResponse: CachedURLResponse) + + // MARK: URLSessionDownloadDelegate Events + + /// Event called during `URLSessionDownloadDelegate`'s `urlSession(_:downloadTask:didResumeAtOffset:expectedTotalBytes:)` method. + func urlSession(_ session: URLSession, + downloadTask: URLSessionDownloadTask, + didResumeAtOffset fileOffset: Int64, + expectedTotalBytes: Int64) + + /// Event called during `URLSessionDownloadDelegate`'s `urlSession(_:downloadTask:didWriteData:totalBytesWritten:totalBytesExpectedToWrite:)` method. + func urlSession(_ session: URLSession, + downloadTask: URLSessionDownloadTask, + didWriteData bytesWritten: Int64, + totalBytesWritten: Int64, + totalBytesExpectedToWrite: Int64) + + /// Event called during `URLSessionDownloadDelegate`'s `urlSession(_:downloadTask:didFinishDownloadingTo:)` method. + func urlSession(_ session: URLSession, downloadTask: URLSessionDownloadTask, didFinishDownloadingTo location: URL) + + // MARK: - Request Events + + /// Event called when a `URLRequest` is first created for a `Request`. If a `RequestAdapter` is active, the + /// `URLRequest` will be adapted before being issued. + func request(_ request: Request, didCreateInitialURLRequest urlRequest: URLRequest) + + /// Event called when the attempt to create a `URLRequest` from a `Request`'s original `URLRequestConvertible` value fails. + func request(_ request: Request, didFailToCreateURLRequestWithError error: AFError) + + /// Event called when a `RequestAdapter` adapts the `Request`'s initial `URLRequest`. + func request(_ request: Request, didAdaptInitialRequest initialRequest: URLRequest, to adaptedRequest: URLRequest) + + /// Event called when a `RequestAdapter` fails to adapt the `Request`'s initial `URLRequest`. + func request(_ request: Request, didFailToAdaptURLRequest initialRequest: URLRequest, withError error: AFError) + + /// Event called when a final `URLRequest` is created for a `Request`. + func request(_ request: Request, didCreateURLRequest urlRequest: URLRequest) + + /// Event called when a `URLSessionTask` subclass instance is created for a `Request`. + func request(_ request: Request, didCreateTask task: URLSessionTask) + + /// Event called when a `Request` receives a `URLSessionTaskMetrics` value. + func request(_ request: Request, didGatherMetrics metrics: URLSessionTaskMetrics) + + /// Event called when a `Request` fails due to an error created by Alamofire. e.g. When certificate pinning fails. + func request(_ request: Request, didFailTask task: URLSessionTask, earlyWithError error: AFError) + + /// Event called when a `Request`'s task completes, possibly with an error. A `Request` may receive this event + /// multiple times if it is retried. + func request(_ request: Request, didCompleteTask task: URLSessionTask, with error: AFError?) + + /// Event called when a `Request` is about to be retried. + func requestIsRetrying(_ request: Request) + + /// Event called when a `Request` finishes and response serializers are being called. + func requestDidFinish(_ request: Request) + + /// Event called when a `Request` receives a `resume` call. + func requestDidResume(_ request: Request) + + /// Event called when a `Request`'s associated `URLSessionTask` is resumed. + func request(_ request: Request, didResumeTask task: URLSessionTask) + + /// Event called when a `Request` receives a `suspend` call. + func requestDidSuspend(_ request: Request) + + /// Event called when a `Request`'s associated `URLSessionTask` is suspended. + func request(_ request: Request, didSuspendTask task: URLSessionTask) + + /// Event called when a `Request` receives a `cancel` call. + func requestDidCancel(_ request: Request) + + /// Event called when a `Request`'s associated `URLSessionTask` is cancelled. + func request(_ request: Request, didCancelTask task: URLSessionTask) + + // MARK: DataRequest Events + + /// Event called when a `DataRequest` calls a `Validation`. + func request(_ request: DataRequest, + didValidateRequest urlRequest: URLRequest?, + response: HTTPURLResponse, + data: Data?, + withResult result: Request.ValidationResult) + + /// Event called when a `DataRequest` creates a `DataResponse` value without calling a `ResponseSerializer`. + func request(_ request: DataRequest, didParseResponse response: DataResponse) + + /// Event called when a `DataRequest` calls a `ResponseSerializer` and creates a generic `DataResponse`. + func request(_ request: DataRequest, didParseResponse response: DataResponse) + + // MARK: DataStreamRequest Events + + /// Event called when a `DataStreamRequest` calls a `Validation` closure. + /// + /// - Parameters: + /// - request: `DataStreamRequest` which is calling the `Validation`. + /// - urlRequest: `URLRequest` of the request being validated. + /// - response: `HTTPURLResponse` of the request being validated. + /// - result: Produced `ValidationResult`. + func request(_ request: DataStreamRequest, + didValidateRequest urlRequest: URLRequest?, + response: HTTPURLResponse, + withResult result: Request.ValidationResult) + + /// Event called when a `DataStreamSerializer` produces a value from streamed `Data`. + /// + /// - Parameters: + /// - request: `DataStreamRequest` for which the value was serialized. + /// - result: `Result` of the serialization attempt. + func request(_ request: DataStreamRequest, didParseStream result: Result) + + // MARK: UploadRequest Events + + /// Event called when an `UploadRequest` creates its `Uploadable` value, indicating the type of upload it represents. + func request(_ request: UploadRequest, didCreateUploadable uploadable: UploadRequest.Uploadable) + + /// Event called when an `UploadRequest` failed to create its `Uploadable` value due to an error. + func request(_ request: UploadRequest, didFailToCreateUploadableWithError error: AFError) + + /// Event called when an `UploadRequest` provides the `InputStream` from its `Uploadable` value. This only occurs if + /// the `InputStream` does not wrap a `Data` value or file `URL`. + func request(_ request: UploadRequest, didProvideInputStream stream: InputStream) + + // MARK: DownloadRequest Events + + /// Event called when a `DownloadRequest`'s `URLSessionDownloadTask` finishes and the temporary file has been moved. + func request(_ request: DownloadRequest, didFinishDownloadingUsing task: URLSessionTask, with result: Result) + + /// Event called when a `DownloadRequest`'s `Destination` closure is called and creates the destination URL the + /// downloaded file will be moved to. + func request(_ request: DownloadRequest, didCreateDestinationURL url: URL) + + /// Event called when a `DownloadRequest` calls a `Validation`. + func request(_ request: DownloadRequest, + didValidateRequest urlRequest: URLRequest?, + response: HTTPURLResponse, + fileURL: URL?, + withResult result: Request.ValidationResult) + + /// Event called when a `DownloadRequest` creates a `DownloadResponse` without calling a `ResponseSerializer`. + func request(_ request: DownloadRequest, didParseResponse response: DownloadResponse) + + /// Event called when a `DownloadRequest` calls a `DownloadResponseSerializer` and creates a generic `DownloadResponse` + func request(_ request: DownloadRequest, didParseResponse response: DownloadResponse) +} + +extension EventMonitor { + /// The default queue on which `CompositeEventMonitor`s will call the `EventMonitor` methods. `.main` by default. + public var queue: DispatchQueue { .main } + + // MARK: Default Implementations + + public func urlSession(_ session: URLSession, didBecomeInvalidWithError error: Error?) {} + public func urlSession(_ session: URLSession, + task: URLSessionTask, + didReceive challenge: URLAuthenticationChallenge) {} + public func urlSession(_ session: URLSession, + task: URLSessionTask, + didSendBodyData bytesSent: Int64, + totalBytesSent: Int64, + totalBytesExpectedToSend: Int64) {} + public func urlSession(_ session: URLSession, taskNeedsNewBodyStream task: URLSessionTask) {} + public func urlSession(_ session: URLSession, + task: URLSessionTask, + willPerformHTTPRedirection response: HTTPURLResponse, + newRequest request: URLRequest) {} + public func urlSession(_ session: URLSession, + task: URLSessionTask, + didFinishCollecting metrics: URLSessionTaskMetrics) {} + public func urlSession(_ session: URLSession, task: URLSessionTask, didCompleteWithError error: Error?) {} + public func urlSession(_ session: URLSession, taskIsWaitingForConnectivity task: URLSessionTask) {} + public func urlSession(_ session: URLSession, dataTask: URLSessionDataTask, didReceive data: Data) {} + public func urlSession(_ session: URLSession, + dataTask: URLSessionDataTask, + willCacheResponse proposedResponse: CachedURLResponse) {} + public func urlSession(_ session: URLSession, + downloadTask: URLSessionDownloadTask, + didResumeAtOffset fileOffset: Int64, + expectedTotalBytes: Int64) {} + public func urlSession(_ session: URLSession, + downloadTask: URLSessionDownloadTask, + didWriteData bytesWritten: Int64, + totalBytesWritten: Int64, + totalBytesExpectedToWrite: Int64) {} + public func urlSession(_ session: URLSession, + downloadTask: URLSessionDownloadTask, + didFinishDownloadingTo location: URL) {} + public func request(_ request: Request, didCreateInitialURLRequest urlRequest: URLRequest) {} + public func request(_ request: Request, didFailToCreateURLRequestWithError error: AFError) {} + public func request(_ request: Request, + didAdaptInitialRequest initialRequest: URLRequest, + to adaptedRequest: URLRequest) {} + public func request(_ request: Request, + didFailToAdaptURLRequest initialRequest: URLRequest, + withError error: AFError) {} + public func request(_ request: Request, didCreateURLRequest urlRequest: URLRequest) {} + public func request(_ request: Request, didCreateTask task: URLSessionTask) {} + public func request(_ request: Request, didGatherMetrics metrics: URLSessionTaskMetrics) {} + public func request(_ request: Request, didFailTask task: URLSessionTask, earlyWithError error: AFError) {} + public func request(_ request: Request, didCompleteTask task: URLSessionTask, with error: AFError?) {} + public func requestIsRetrying(_ request: Request) {} + public func requestDidFinish(_ request: Request) {} + public func requestDidResume(_ request: Request) {} + public func request(_ request: Request, didResumeTask task: URLSessionTask) {} + public func requestDidSuspend(_ request: Request) {} + public func request(_ request: Request, didSuspendTask task: URLSessionTask) {} + public func requestDidCancel(_ request: Request) {} + public func request(_ request: Request, didCancelTask task: URLSessionTask) {} + public func request(_ request: DataRequest, + didValidateRequest urlRequest: URLRequest?, + response: HTTPURLResponse, + data: Data?, + withResult result: Request.ValidationResult) {} + public func request(_ request: DataRequest, didParseResponse response: DataResponse) {} + public func request(_ request: DataRequest, didParseResponse response: DataResponse) {} + public func request(_ request: DataStreamRequest, + didValidateRequest urlRequest: URLRequest?, + response: HTTPURLResponse, + withResult result: Request.ValidationResult) {} + public func request(_ request: DataStreamRequest, didParseStream result: Result) {} + public func request(_ request: UploadRequest, didCreateUploadable uploadable: UploadRequest.Uploadable) {} + public func request(_ request: UploadRequest, didFailToCreateUploadableWithError error: AFError) {} + public func request(_ request: UploadRequest, didProvideInputStream stream: InputStream) {} + public func request(_ request: DownloadRequest, didFinishDownloadingUsing task: URLSessionTask, with result: Result) {} + public func request(_ request: DownloadRequest, didCreateDestinationURL url: URL) {} + public func request(_ request: DownloadRequest, + didValidateRequest urlRequest: URLRequest?, + response: HTTPURLResponse, + fileURL: URL?, + withResult result: Request.ValidationResult) {} + public func request(_ request: DownloadRequest, didParseResponse response: DownloadResponse) {} + public func request(_ request: DownloadRequest, didParseResponse response: DownloadResponse) {} +} + +/// An `EventMonitor` which can contain multiple `EventMonitor`s and calls their methods on their queues. +public final class CompositeEventMonitor: EventMonitor { + public let queue = DispatchQueue(label: "org.alamofire.compositeEventMonitor", qos: .utility) + + let monitors: [EventMonitor] + + init(monitors: [EventMonitor]) { + self.monitors = monitors + } + + func performEvent(_ event: @escaping (EventMonitor) -> Void) { + queue.async { + for monitor in self.monitors { + monitor.queue.async { event(monitor) } + } + } + } + + public func urlSession(_ session: URLSession, didBecomeInvalidWithError error: Error?) { + performEvent { $0.urlSession(session, didBecomeInvalidWithError: error) } + } + + public func urlSession(_ session: URLSession, + task: URLSessionTask, + didReceive challenge: URLAuthenticationChallenge) { + performEvent { $0.urlSession(session, task: task, didReceive: challenge) } + } + + public func urlSession(_ session: URLSession, + task: URLSessionTask, + didSendBodyData bytesSent: Int64, + totalBytesSent: Int64, + totalBytesExpectedToSend: Int64) { + performEvent { + $0.urlSession(session, + task: task, + didSendBodyData: bytesSent, + totalBytesSent: totalBytesSent, + totalBytesExpectedToSend: totalBytesExpectedToSend) + } + } + + public func urlSession(_ session: URLSession, taskNeedsNewBodyStream task: URLSessionTask) { + performEvent { + $0.urlSession(session, taskNeedsNewBodyStream: task) + } + } + + public func urlSession(_ session: URLSession, + task: URLSessionTask, + willPerformHTTPRedirection response: HTTPURLResponse, + newRequest request: URLRequest) { + performEvent { + $0.urlSession(session, + task: task, + willPerformHTTPRedirection: response, + newRequest: request) + } + } + + public func urlSession(_ session: URLSession, task: URLSessionTask, didFinishCollecting metrics: URLSessionTaskMetrics) { + performEvent { $0.urlSession(session, task: task, didFinishCollecting: metrics) } + } + + public func urlSession(_ session: URLSession, task: URLSessionTask, didCompleteWithError error: Error?) { + performEvent { $0.urlSession(session, task: task, didCompleteWithError: error) } + } + + @available(macOS 10.13, iOS 11.0, tvOS 11.0, watchOS 4.0, *) + public func urlSession(_ session: URLSession, taskIsWaitingForConnectivity task: URLSessionTask) { + performEvent { $0.urlSession(session, taskIsWaitingForConnectivity: task) } + } + + public func urlSession(_ session: URLSession, dataTask: URLSessionDataTask, didReceive data: Data) { + performEvent { $0.urlSession(session, dataTask: dataTask, didReceive: data) } + } + + public func urlSession(_ session: URLSession, + dataTask: URLSessionDataTask, + willCacheResponse proposedResponse: CachedURLResponse) { + performEvent { $0.urlSession(session, dataTask: dataTask, willCacheResponse: proposedResponse) } + } + + public func urlSession(_ session: URLSession, + downloadTask: URLSessionDownloadTask, + didResumeAtOffset fileOffset: Int64, + expectedTotalBytes: Int64) { + performEvent { + $0.urlSession(session, + downloadTask: downloadTask, + didResumeAtOffset: fileOffset, + expectedTotalBytes: expectedTotalBytes) + } + } + + public func urlSession(_ session: URLSession, + downloadTask: URLSessionDownloadTask, + didWriteData bytesWritten: Int64, + totalBytesWritten: Int64, + totalBytesExpectedToWrite: Int64) { + performEvent { + $0.urlSession(session, + downloadTask: downloadTask, + didWriteData: bytesWritten, + totalBytesWritten: totalBytesWritten, + totalBytesExpectedToWrite: totalBytesExpectedToWrite) + } + } + + public func urlSession(_ session: URLSession, + downloadTask: URLSessionDownloadTask, + didFinishDownloadingTo location: URL) { + performEvent { $0.urlSession(session, downloadTask: downloadTask, didFinishDownloadingTo: location) } + } + + public func request(_ request: Request, didCreateInitialURLRequest urlRequest: URLRequest) { + performEvent { $0.request(request, didCreateInitialURLRequest: urlRequest) } + } + + public func request(_ request: Request, didFailToCreateURLRequestWithError error: AFError) { + performEvent { $0.request(request, didFailToCreateURLRequestWithError: error) } + } + + public func request(_ request: Request, didAdaptInitialRequest initialRequest: URLRequest, to adaptedRequest: URLRequest) { + performEvent { $0.request(request, didAdaptInitialRequest: initialRequest, to: adaptedRequest) } + } + + public func request(_ request: Request, didFailToAdaptURLRequest initialRequest: URLRequest, withError error: AFError) { + performEvent { $0.request(request, didFailToAdaptURLRequest: initialRequest, withError: error) } + } + + public func request(_ request: Request, didCreateURLRequest urlRequest: URLRequest) { + performEvent { $0.request(request, didCreateURLRequest: urlRequest) } + } + + public func request(_ request: Request, didCreateTask task: URLSessionTask) { + performEvent { $0.request(request, didCreateTask: task) } + } + + public func request(_ request: Request, didGatherMetrics metrics: URLSessionTaskMetrics) { + performEvent { $0.request(request, didGatherMetrics: metrics) } + } + + public func request(_ request: Request, didFailTask task: URLSessionTask, earlyWithError error: AFError) { + performEvent { $0.request(request, didFailTask: task, earlyWithError: error) } + } + + public func request(_ request: Request, didCompleteTask task: URLSessionTask, with error: AFError?) { + performEvent { $0.request(request, didCompleteTask: task, with: error) } + } + + public func requestIsRetrying(_ request: Request) { + performEvent { $0.requestIsRetrying(request) } + } + + public func requestDidFinish(_ request: Request) { + performEvent { $0.requestDidFinish(request) } + } + + public func requestDidResume(_ request: Request) { + performEvent { $0.requestDidResume(request) } + } + + public func request(_ request: Request, didResumeTask task: URLSessionTask) { + performEvent { $0.request(request, didResumeTask: task) } + } + + public func requestDidSuspend(_ request: Request) { + performEvent { $0.requestDidSuspend(request) } + } + + public func request(_ request: Request, didSuspendTask task: URLSessionTask) { + performEvent { $0.request(request, didSuspendTask: task) } + } + + public func requestDidCancel(_ request: Request) { + performEvent { $0.requestDidCancel(request) } + } + + public func request(_ request: Request, didCancelTask task: URLSessionTask) { + performEvent { $0.request(request, didCancelTask: task) } + } + + public func request(_ request: DataRequest, + didValidateRequest urlRequest: URLRequest?, + response: HTTPURLResponse, + data: Data?, + withResult result: Request.ValidationResult) { + performEvent { $0.request(request, + didValidateRequest: urlRequest, + response: response, + data: data, + withResult: result) + } + } + + public func request(_ request: DataRequest, didParseResponse response: DataResponse) { + performEvent { $0.request(request, didParseResponse: response) } + } + + public func request(_ request: DataRequest, didParseResponse response: DataResponse) { + performEvent { $0.request(request, didParseResponse: response) } + } + + public func request(_ request: DataStreamRequest, + didValidateRequest urlRequest: URLRequest?, + response: HTTPURLResponse, + withResult result: Request.ValidationResult) { + performEvent { $0.request(request, + didValidateRequest: urlRequest, + response: response, + withResult: result) + } + } + + public func request(_ request: DataStreamRequest, didParseStream result: Result) { + performEvent { $0.request(request, didParseStream: result) } + } + + public func request(_ request: UploadRequest, didCreateUploadable uploadable: UploadRequest.Uploadable) { + performEvent { $0.request(request, didCreateUploadable: uploadable) } + } + + public func request(_ request: UploadRequest, didFailToCreateUploadableWithError error: AFError) { + performEvent { $0.request(request, didFailToCreateUploadableWithError: error) } + } + + public func request(_ request: UploadRequest, didProvideInputStream stream: InputStream) { + performEvent { $0.request(request, didProvideInputStream: stream) } + } + + public func request(_ request: DownloadRequest, didFinishDownloadingUsing task: URLSessionTask, with result: Result) { + performEvent { $0.request(request, didFinishDownloadingUsing: task, with: result) } + } + + public func request(_ request: DownloadRequest, didCreateDestinationURL url: URL) { + performEvent { $0.request(request, didCreateDestinationURL: url) } + } + + public func request(_ request: DownloadRequest, + didValidateRequest urlRequest: URLRequest?, + response: HTTPURLResponse, + fileURL: URL?, + withResult result: Request.ValidationResult) { + performEvent { $0.request(request, + didValidateRequest: urlRequest, + response: response, + fileURL: fileURL, + withResult: result) } + } + + public func request(_ request: DownloadRequest, didParseResponse response: DownloadResponse) { + performEvent { $0.request(request, didParseResponse: response) } + } + + public func request(_ request: DownloadRequest, didParseResponse response: DownloadResponse) { + performEvent { $0.request(request, didParseResponse: response) } + } +} + +/// `EventMonitor` that allows optional closures to be set to receive events. +open class ClosureEventMonitor: EventMonitor { + /// Closure called on the `urlSession(_:didBecomeInvalidWithError:)` event. + open var sessionDidBecomeInvalidWithError: ((URLSession, Error?) -> Void)? + + /// Closure called on the `urlSession(_:task:didReceive:completionHandler:)`. + open var taskDidReceiveChallenge: ((URLSession, URLSessionTask, URLAuthenticationChallenge) -> Void)? + + /// Closure that receives `urlSession(_:task:didSendBodyData:totalBytesSent:totalBytesExpectedToSend:)` event. + open var taskDidSendBodyData: ((URLSession, URLSessionTask, Int64, Int64, Int64) -> Void)? + + /// Closure called on the `urlSession(_:task:needNewBodyStream:)` event. + open var taskNeedNewBodyStream: ((URLSession, URLSessionTask) -> Void)? + + /// Closure called on the `urlSession(_:task:willPerformHTTPRedirection:newRequest:completionHandler:)` event. + open var taskWillPerformHTTPRedirection: ((URLSession, URLSessionTask, HTTPURLResponse, URLRequest) -> Void)? + + /// Closure called on the `urlSession(_:task:didFinishCollecting:)` event. + open var taskDidFinishCollectingMetrics: ((URLSession, URLSessionTask, URLSessionTaskMetrics) -> Void)? + + /// Closure called on the `urlSession(_:task:didCompleteWithError:)` event. + open var taskDidComplete: ((URLSession, URLSessionTask, Error?) -> Void)? + + /// Closure called on the `urlSession(_:taskIsWaitingForConnectivity:)` event. + open var taskIsWaitingForConnectivity: ((URLSession, URLSessionTask) -> Void)? + + /// Closure that receives the `urlSession(_:dataTask:didReceive:)` event. + open var dataTaskDidReceiveData: ((URLSession, URLSessionDataTask, Data) -> Void)? + + /// Closure called on the `urlSession(_:dataTask:willCacheResponse:completionHandler:)` event. + open var dataTaskWillCacheResponse: ((URLSession, URLSessionDataTask, CachedURLResponse) -> Void)? + + /// Closure called on the `urlSession(_:downloadTask:didFinishDownloadingTo:)` event. + open var downloadTaskDidFinishDownloadingToURL: ((URLSession, URLSessionDownloadTask, URL) -> Void)? + + /// Closure called on the `urlSession(_:downloadTask:didWriteData:totalBytesWritten:totalBytesExpectedToWrite:)` + /// event. + open var downloadTaskDidWriteData: ((URLSession, URLSessionDownloadTask, Int64, Int64, Int64) -> Void)? + + /// Closure called on the `urlSession(_:downloadTask:didResumeAtOffset:expectedTotalBytes:)` event. + open var downloadTaskDidResumeAtOffset: ((URLSession, URLSessionDownloadTask, Int64, Int64) -> Void)? + + // MARK: - Request Events + + /// Closure called on the `request(_:didCreateInitialURLRequest:)` event. + open var requestDidCreateInitialURLRequest: ((Request, URLRequest) -> Void)? + + /// Closure called on the `request(_:didFailToCreateURLRequestWithError:)` event. + open var requestDidFailToCreateURLRequestWithError: ((Request, AFError) -> Void)? + + /// Closure called on the `request(_:didAdaptInitialRequest:to:)` event. + open var requestDidAdaptInitialRequestToAdaptedRequest: ((Request, URLRequest, URLRequest) -> Void)? + + /// Closure called on the `request(_:didFailToAdaptURLRequest:withError:)` event. + open var requestDidFailToAdaptURLRequestWithError: ((Request, URLRequest, AFError) -> Void)? + + /// Closure called on the `request(_:didCreateURLRequest:)` event. + open var requestDidCreateURLRequest: ((Request, URLRequest) -> Void)? + + /// Closure called on the `request(_:didCreateTask:)` event. + open var requestDidCreateTask: ((Request, URLSessionTask) -> Void)? + + /// Closure called on the `request(_:didGatherMetrics:)` event. + open var requestDidGatherMetrics: ((Request, URLSessionTaskMetrics) -> Void)? + + /// Closure called on the `request(_:didFailTask:earlyWithError:)` event. + open var requestDidFailTaskEarlyWithError: ((Request, URLSessionTask, AFError) -> Void)? + + /// Closure called on the `request(_:didCompleteTask:with:)` event. + open var requestDidCompleteTaskWithError: ((Request, URLSessionTask, AFError?) -> Void)? + + /// Closure called on the `requestIsRetrying(_:)` event. + open var requestIsRetrying: ((Request) -> Void)? + + /// Closure called on the `requestDidFinish(_:)` event. + open var requestDidFinish: ((Request) -> Void)? + + /// Closure called on the `requestDidResume(_:)` event. + open var requestDidResume: ((Request) -> Void)? + + /// Closure called on the `request(_:didResumeTask:)` event. + open var requestDidResumeTask: ((Request, URLSessionTask) -> Void)? + + /// Closure called on the `requestDidSuspend(_:)` event. + open var requestDidSuspend: ((Request) -> Void)? + + /// Closure called on the `request(_:didSuspendTask:)` event. + open var requestDidSuspendTask: ((Request, URLSessionTask) -> Void)? + + /// Closure called on the `requestDidCancel(_:)` event. + open var requestDidCancel: ((Request) -> Void)? + + /// Closure called on the `request(_:didCancelTask:)` event. + open var requestDidCancelTask: ((Request, URLSessionTask) -> Void)? + + /// Closure called on the `request(_:didValidateRequest:response:data:withResult:)` event. + open var requestDidValidateRequestResponseDataWithResult: ((DataRequest, URLRequest?, HTTPURLResponse, Data?, Request.ValidationResult) -> Void)? + + /// Closure called on the `request(_:didParseResponse:)` event. + open var requestDidParseResponse: ((DataRequest, DataResponse) -> Void)? + + /// Closure called on the `request(_:didValidateRequest:response:withResult:)` event. + open var requestDidValidateRequestResponseWithResult: ((DataStreamRequest, URLRequest?, HTTPURLResponse, Request.ValidationResult) -> Void)? + + /// Closure called on the `request(_:didCreateUploadable:)` event. + open var requestDidCreateUploadable: ((UploadRequest, UploadRequest.Uploadable) -> Void)? + + /// Closure called on the `request(_:didFailToCreateUploadableWithError:)` event. + open var requestDidFailToCreateUploadableWithError: ((UploadRequest, AFError) -> Void)? + + /// Closure called on the `request(_:didProvideInputStream:)` event. + open var requestDidProvideInputStream: ((UploadRequest, InputStream) -> Void)? + + /// Closure called on the `request(_:didFinishDownloadingUsing:with:)` event. + open var requestDidFinishDownloadingUsingTaskWithResult: ((DownloadRequest, URLSessionTask, Result) -> Void)? + + /// Closure called on the `request(_:didCreateDestinationURL:)` event. + open var requestDidCreateDestinationURL: ((DownloadRequest, URL) -> Void)? + + /// Closure called on the `request(_:didValidateRequest:response:temporaryURL:destinationURL:withResult:)` event. + open var requestDidValidateRequestResponseFileURLWithResult: ((DownloadRequest, URLRequest?, HTTPURLResponse, URL?, Request.ValidationResult) -> Void)? + + /// Closure called on the `request(_:didParseResponse:)` event. + open var requestDidParseDownloadResponse: ((DownloadRequest, DownloadResponse) -> Void)? + + public let queue: DispatchQueue + + /// Creates an instance using the provided queue. + /// + /// - Parameter queue: `DispatchQueue` on which events will fired. `.main` by default. + public init(queue: DispatchQueue = .main) { + self.queue = queue + } + + open func urlSession(_ session: URLSession, didBecomeInvalidWithError error: Error?) { + sessionDidBecomeInvalidWithError?(session, error) + } + + open func urlSession(_ session: URLSession, task: URLSessionTask, didReceive challenge: URLAuthenticationChallenge) { + taskDidReceiveChallenge?(session, task, challenge) + } + + open func urlSession(_ session: URLSession, + task: URLSessionTask, + didSendBodyData bytesSent: Int64, + totalBytesSent: Int64, + totalBytesExpectedToSend: Int64) { + taskDidSendBodyData?(session, task, bytesSent, totalBytesSent, totalBytesExpectedToSend) + } + + open func urlSession(_ session: URLSession, taskNeedsNewBodyStream task: URLSessionTask) { + taskNeedNewBodyStream?(session, task) + } + + open func urlSession(_ session: URLSession, + task: URLSessionTask, + willPerformHTTPRedirection response: HTTPURLResponse, + newRequest request: URLRequest) { + taskWillPerformHTTPRedirection?(session, task, response, request) + } + + open func urlSession(_ session: URLSession, task: URLSessionTask, didFinishCollecting metrics: URLSessionTaskMetrics) { + taskDidFinishCollectingMetrics?(session, task, metrics) + } + + open func urlSession(_ session: URLSession, task: URLSessionTask, didCompleteWithError error: Error?) { + taskDidComplete?(session, task, error) + } + + @available(macOS 10.13, iOS 11.0, tvOS 11.0, watchOS 4.0, *) + open func urlSession(_ session: URLSession, taskIsWaitingForConnectivity task: URLSessionTask) { + taskIsWaitingForConnectivity?(session, task) + } + + open func urlSession(_ session: URLSession, dataTask: URLSessionDataTask, didReceive data: Data) { + dataTaskDidReceiveData?(session, dataTask, data) + } + + open func urlSession(_ session: URLSession, dataTask: URLSessionDataTask, willCacheResponse proposedResponse: CachedURLResponse) { + dataTaskWillCacheResponse?(session, dataTask, proposedResponse) + } + + open func urlSession(_ session: URLSession, + downloadTask: URLSessionDownloadTask, + didResumeAtOffset fileOffset: Int64, + expectedTotalBytes: Int64) { + downloadTaskDidResumeAtOffset?(session, downloadTask, fileOffset, expectedTotalBytes) + } + + open func urlSession(_ session: URLSession, + downloadTask: URLSessionDownloadTask, + didWriteData bytesWritten: Int64, + totalBytesWritten: Int64, + totalBytesExpectedToWrite: Int64) { + downloadTaskDidWriteData?(session, downloadTask, bytesWritten, totalBytesWritten, totalBytesExpectedToWrite) + } + + open func urlSession(_ session: URLSession, downloadTask: URLSessionDownloadTask, didFinishDownloadingTo location: URL) { + downloadTaskDidFinishDownloadingToURL?(session, downloadTask, location) + } + + // MARK: Request Events + + open func request(_ request: Request, didCreateInitialURLRequest urlRequest: URLRequest) { + requestDidCreateInitialURLRequest?(request, urlRequest) + } + + open func request(_ request: Request, didFailToCreateURLRequestWithError error: AFError) { + requestDidFailToCreateURLRequestWithError?(request, error) + } + + open func request(_ request: Request, didAdaptInitialRequest initialRequest: URLRequest, to adaptedRequest: URLRequest) { + requestDidAdaptInitialRequestToAdaptedRequest?(request, initialRequest, adaptedRequest) + } + + open func request(_ request: Request, didFailToAdaptURLRequest initialRequest: URLRequest, withError error: AFError) { + requestDidFailToAdaptURLRequestWithError?(request, initialRequest, error) + } + + open func request(_ request: Request, didCreateURLRequest urlRequest: URLRequest) { + requestDidCreateURLRequest?(request, urlRequest) + } + + open func request(_ request: Request, didCreateTask task: URLSessionTask) { + requestDidCreateTask?(request, task) + } + + open func request(_ request: Request, didGatherMetrics metrics: URLSessionTaskMetrics) { + requestDidGatherMetrics?(request, metrics) + } + + open func request(_ request: Request, didFailTask task: URLSessionTask, earlyWithError error: AFError) { + requestDidFailTaskEarlyWithError?(request, task, error) + } + + open func request(_ request: Request, didCompleteTask task: URLSessionTask, with error: AFError?) { + requestDidCompleteTaskWithError?(request, task, error) + } + + open func requestIsRetrying(_ request: Request) { + requestIsRetrying?(request) + } + + open func requestDidFinish(_ request: Request) { + requestDidFinish?(request) + } + + open func requestDidResume(_ request: Request) { + requestDidResume?(request) + } + + public func request(_ request: Request, didResumeTask task: URLSessionTask) { + requestDidResumeTask?(request, task) + } + + open func requestDidSuspend(_ request: Request) { + requestDidSuspend?(request) + } + + public func request(_ request: Request, didSuspendTask task: URLSessionTask) { + requestDidSuspendTask?(request, task) + } + + open func requestDidCancel(_ request: Request) { + requestDidCancel?(request) + } + + public func request(_ request: Request, didCancelTask task: URLSessionTask) { + requestDidCancelTask?(request, task) + } + + open func request(_ request: DataRequest, + didValidateRequest urlRequest: URLRequest?, + response: HTTPURLResponse, + data: Data?, + withResult result: Request.ValidationResult) { + requestDidValidateRequestResponseDataWithResult?(request, urlRequest, response, data, result) + } + + open func request(_ request: DataRequest, didParseResponse response: DataResponse) { + requestDidParseResponse?(request, response) + } + + public func request(_ request: DataStreamRequest, didValidateRequest urlRequest: URLRequest?, response: HTTPURLResponse, withResult result: Request.ValidationResult) { + requestDidValidateRequestResponseWithResult?(request, urlRequest, response, result) + } + + open func request(_ request: UploadRequest, didCreateUploadable uploadable: UploadRequest.Uploadable) { + requestDidCreateUploadable?(request, uploadable) + } + + open func request(_ request: UploadRequest, didFailToCreateUploadableWithError error: AFError) { + requestDidFailToCreateUploadableWithError?(request, error) + } + + open func request(_ request: UploadRequest, didProvideInputStream stream: InputStream) { + requestDidProvideInputStream?(request, stream) + } + + open func request(_ request: DownloadRequest, didFinishDownloadingUsing task: URLSessionTask, with result: Result) { + requestDidFinishDownloadingUsingTaskWithResult?(request, task, result) + } + + open func request(_ request: DownloadRequest, didCreateDestinationURL url: URL) { + requestDidCreateDestinationURL?(request, url) + } + + open func request(_ request: DownloadRequest, + didValidateRequest urlRequest: URLRequest?, + response: HTTPURLResponse, + fileURL: URL?, + withResult result: Request.ValidationResult) { + requestDidValidateRequestResponseFileURLWithResult?(request, + urlRequest, + response, + fileURL, + result) + } + + open func request(_ request: DownloadRequest, didParseResponse response: DownloadResponse) { + requestDidParseDownloadResponse?(request, response) + } +} diff --git a/Pods/Alamofire/Source/HTTPHeaders.swift b/Pods/Alamofire/Source/HTTPHeaders.swift new file mode 100644 index 0000000..231f618 --- /dev/null +++ b/Pods/Alamofire/Source/HTTPHeaders.swift @@ -0,0 +1,456 @@ +// +// HTTPHeaders.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 + +/// An order-preserving and case-insensitive representation of HTTP headers. +public struct HTTPHeaders { + private var headers: [HTTPHeader] = [] + + /// Creates an empty instance. + public init() {} + + /// Creates an instance from an array of `HTTPHeader`s. Duplicate case-insensitive names are collapsed into the last + /// name and value encountered. + public init(_ headers: [HTTPHeader]) { + self.init() + + headers.forEach { update($0) } + } + + /// Creates an instance from a `[String: String]`. Duplicate case-insensitive names are collapsed into the last name + /// and value encountered. + public init(_ dictionary: [String: String]) { + self.init() + + dictionary.forEach { update(HTTPHeader(name: $0.key, value: $0.value)) } + } + + /// Case-insensitively updates or appends an `HTTPHeader` into the instance using the provided `name` and `value`. + /// + /// - Parameters: + /// - name: The `HTTPHeader` name. + /// - value: The `HTTPHeader value. + public mutating func add(name: String, value: String) { + update(HTTPHeader(name: name, value: value)) + } + + /// Case-insensitively updates or appends the provided `HTTPHeader` into the instance. + /// + /// - Parameter header: The `HTTPHeader` to update or append. + public mutating func add(_ header: HTTPHeader) { + update(header) + } + + /// Case-insensitively updates or appends an `HTTPHeader` into the instance using the provided `name` and `value`. + /// + /// - Parameters: + /// - name: The `HTTPHeader` name. + /// - value: The `HTTPHeader value. + public mutating func update(name: String, value: String) { + update(HTTPHeader(name: name, value: value)) + } + + /// Case-insensitively updates or appends the provided `HTTPHeader` into the instance. + /// + /// - Parameter header: The `HTTPHeader` to update or append. + public mutating func update(_ header: HTTPHeader) { + guard let index = headers.index(of: header.name) else { + headers.append(header) + return + } + + headers.replaceSubrange(index...index, with: [header]) + } + + /// Case-insensitively removes an `HTTPHeader`, if it exists, from the instance. + /// + /// - Parameter name: The name of the `HTTPHeader` to remove. + public mutating func remove(name: String) { + guard let index = headers.index(of: name) else { return } + + headers.remove(at: index) + } + + /// Sort the current instance by header name, case insensitively. + public mutating func sort() { + headers.sort { $0.name.lowercased() < $1.name.lowercased() } + } + + /// Returns an instance sorted by header name. + /// + /// - Returns: A copy of the current instance sorted by name. + public func sorted() -> HTTPHeaders { + var headers = self + headers.sort() + + return headers + } + + /// Case-insensitively find a header's value by name. + /// + /// - Parameter name: The name of the header to search for, case-insensitively. + /// + /// - Returns: The value of header, if it exists. + public func value(for name: String) -> String? { + guard let index = headers.index(of: name) else { return nil } + + return headers[index].value + } + + /// Case-insensitively access the header with the given name. + /// + /// - Parameter name: The name of the header. + public subscript(_ name: String) -> String? { + get { value(for: name) } + set { + if let value = newValue { + update(name: name, value: value) + } else { + remove(name: name) + } + } + } + + /// The dictionary representation of all headers. + /// + /// This representation does not preserve the current order of the instance. + public var dictionary: [String: String] { + let namesAndValues = headers.map { ($0.name, $0.value) } + + return Dictionary(namesAndValues, uniquingKeysWith: { _, last in last }) + } +} + +extension HTTPHeaders: ExpressibleByDictionaryLiteral { + public init(dictionaryLiteral elements: (String, String)...) { + self.init() + + elements.forEach { update(name: $0.0, value: $0.1) } + } +} + +extension HTTPHeaders: ExpressibleByArrayLiteral { + public init(arrayLiteral elements: HTTPHeader...) { + self.init(elements) + } +} + +extension HTTPHeaders: Sequence { + public func makeIterator() -> IndexingIterator<[HTTPHeader]> { + headers.makeIterator() + } +} + +extension HTTPHeaders: Collection { + public var startIndex: Int { + headers.startIndex + } + + public var endIndex: Int { + headers.endIndex + } + + public subscript(position: Int) -> HTTPHeader { + headers[position] + } + + public func index(after i: Int) -> Int { + headers.index(after: i) + } +} + +extension HTTPHeaders: CustomStringConvertible { + public var description: String { + headers.map(\.description) + .joined(separator: "\n") + } +} + +// MARK: - HTTPHeader + +/// A representation of a single HTTP header's name / value pair. +public struct HTTPHeader: Hashable { + /// Name of the header. + public let name: String + + /// Value of the header. + public let value: String + + /// Creates an instance from the given `name` and `value`. + /// + /// - Parameters: + /// - name: The name of the header. + /// - value: The value of the header. + public init(name: String, value: String) { + self.name = name + self.value = value + } +} + +extension HTTPHeader: CustomStringConvertible { + public var description: String { + "\(name): \(value)" + } +} + +extension HTTPHeader { + /// Returns an `Accept` header. + /// + /// - Parameter value: The `Accept` value. + /// - Returns: The header. + public static func accept(_ value: String) -> HTTPHeader { + HTTPHeader(name: "Accept", value: value) + } + + /// Returns an `Accept-Charset` header. + /// + /// - Parameter value: The `Accept-Charset` value. + /// - Returns: The header. + public static func acceptCharset(_ value: String) -> HTTPHeader { + HTTPHeader(name: "Accept-Charset", value: value) + } + + /// Returns an `Accept-Language` header. + /// + /// Alamofire offers a default Accept-Language header that accumulates and encodes the system's preferred languages. + /// Use `HTTPHeader.defaultAcceptLanguage`. + /// + /// - Parameter value: The `Accept-Language` value. + /// + /// - Returns: The header. + public static func acceptLanguage(_ value: String) -> HTTPHeader { + HTTPHeader(name: "Accept-Language", value: value) + } + + /// Returns an `Accept-Encoding` header. + /// + /// Alamofire offers a default accept encoding value that provides the most common values. Use + /// `HTTPHeader.defaultAcceptEncoding`. + /// + /// - Parameter value: The `Accept-Encoding` value. + /// + /// - Returns: The header + public static func acceptEncoding(_ value: String) -> HTTPHeader { + HTTPHeader(name: "Accept-Encoding", value: value) + } + + /// Returns a `Basic` `Authorization` header using the `username` and `password` provided. + /// + /// - Parameters: + /// - username: The username of the header. + /// - password: The password of the header. + /// + /// - Returns: The header. + public static func authorization(username: String, password: String) -> HTTPHeader { + let credential = Data("\(username):\(password)".utf8).base64EncodedString() + + return authorization("Basic \(credential)") + } + + /// Returns a `Bearer` `Authorization` header using the `bearerToken` provided + /// + /// - Parameter bearerToken: The bearer token. + /// + /// - Returns: The header. + public static func authorization(bearerToken: String) -> HTTPHeader { + authorization("Bearer \(bearerToken)") + } + + /// Returns an `Authorization` header. + /// + /// Alamofire provides built-in methods to produce `Authorization` headers. For a Basic `Authorization` header use + /// `HTTPHeader.authorization(username:password:)`. For a Bearer `Authorization` header, use + /// `HTTPHeader.authorization(bearerToken:)`. + /// + /// - Parameter value: The `Authorization` value. + /// + /// - Returns: The header. + public static func authorization(_ value: String) -> HTTPHeader { + HTTPHeader(name: "Authorization", value: value) + } + + /// Returns a `Content-Disposition` header. + /// + /// - Parameter value: The `Content-Disposition` value. + /// + /// - Returns: The header. + public static func contentDisposition(_ value: String) -> HTTPHeader { + HTTPHeader(name: "Content-Disposition", value: value) + } + + /// Returns a `Content-Encoding` header. + /// + /// - Parameter value: The `Content-Encoding`. + /// + /// - Returns: The header. + public static func contentEncoding(_ value: String) -> HTTPHeader { + HTTPHeader(name: "Content-Encoding", value: value) + } + + /// Returns a `Content-Type` header. + /// + /// All Alamofire `ParameterEncoding`s and `ParameterEncoder`s set the `Content-Type` of the request, so it may not + /// be necessary to manually set this value. + /// + /// - Parameter value: The `Content-Type` value. + /// + /// - Returns: The header. + public static func contentType(_ value: String) -> HTTPHeader { + HTTPHeader(name: "Content-Type", value: value) + } + + /// Returns a `User-Agent` header. + /// + /// - Parameter value: The `User-Agent` value. + /// + /// - Returns: The header. + public static func userAgent(_ value: String) -> HTTPHeader { + HTTPHeader(name: "User-Agent", value: value) + } +} + +extension Array where Element == HTTPHeader { + /// Case-insensitively finds the index of an `HTTPHeader` with the provided name, if it exists. + func index(of name: String) -> Int? { + let lowercasedName = name.lowercased() + return firstIndex { $0.name.lowercased() == lowercasedName } + } +} + +// MARK: - Defaults + +extension HTTPHeaders { + /// The default set of `HTTPHeaders` used by Alamofire. Includes `Accept-Encoding`, `Accept-Language`, and + /// `User-Agent`. + public static let `default`: HTTPHeaders = [.defaultAcceptEncoding, + .defaultAcceptLanguage, + .defaultUserAgent] +} + +extension HTTPHeader { + /// Returns Alamofire's default `Accept-Encoding` header, appropriate for the encodings supported by particular OS + /// versions. + /// + /// See the [Accept-Encoding HTTP header documentation](https://tools.ietf.org/html/rfc7230#section-4.2.3) . + public static let defaultAcceptEncoding: HTTPHeader = { + let encodings: [String] + if #available(iOS 11.0, macOS 10.13, tvOS 11.0, watchOS 4.0, *) { + encodings = ["br", "gzip", "deflate"] + } else { + encodings = ["gzip", "deflate"] + } + + return .acceptEncoding(encodings.qualityEncoded()) + }() + + /// Returns Alamofire's default `Accept-Language` header, generated by querying `Locale` for the user's + /// `preferredLanguages`. + /// + /// See the [Accept-Language HTTP header documentation](https://tools.ietf.org/html/rfc7231#section-5.3.5). + public static let defaultAcceptLanguage: HTTPHeader = .acceptLanguage(Locale.preferredLanguages.prefix(6).qualityEncoded()) + + /// Returns Alamofire's default `User-Agent` header. + /// + /// See the [User-Agent header documentation](https://tools.ietf.org/html/rfc7231#section-5.5.3). + /// + /// Example: `iOS Example/1.0 (org.alamofire.iOS-Example; build:1; iOS 13.0.0) Alamofire/5.0.0` + public static let defaultUserAgent: HTTPHeader = { + let info = Bundle.main.infoDictionary + let executable = (info?["CFBundleExecutable"] as? String) ?? + (ProcessInfo.processInfo.arguments.first?.split(separator: "/").last.map(String.init)) ?? + "Unknown" + let bundle = info?["CFBundleIdentifier"] as? String ?? "Unknown" + let appVersion = info?["CFBundleShortVersionString"] as? String ?? "Unknown" + let appBuild = info?["CFBundleVersion"] 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) + #if targetEnvironment(macCatalyst) + return "macOS(Catalyst)" + #else + return "iOS" + #endif + #elseif os(watchOS) + return "watchOS" + #elseif os(tvOS) + return "tvOS" + #elseif os(macOS) + return "macOS" + #elseif os(Linux) + return "Linux" + #elseif os(Windows) + return "Windows" + #else + return "Unknown" + #endif + }() + + return "\(osName) \(versionString)" + }() + + let alamofireVersion = "Alamofire/\(version)" + + let userAgent = "\(executable)/\(appVersion) (\(bundle); build:\(appBuild); \(osNameVersion)) \(alamofireVersion)" + + return .userAgent(userAgent) + }() +} + +extension Collection where Element == String { + func qualityEncoded() -> String { + enumerated().map { index, encoding in + let quality = 1.0 - (Double(index) * 0.1) + return "\(encoding);q=\(quality)" + }.joined(separator: ", ") + } +} + +// MARK: - System Type Extensions + +extension URLRequest { + /// Returns `allHTTPHeaderFields` as `HTTPHeaders`. + public var headers: HTTPHeaders { + get { allHTTPHeaderFields.map(HTTPHeaders.init) ?? HTTPHeaders() } + set { allHTTPHeaderFields = newValue.dictionary } + } +} + +extension HTTPURLResponse { + /// Returns `allHeaderFields` as `HTTPHeaders`. + public var headers: HTTPHeaders { + (allHeaderFields as? [String: String]).map(HTTPHeaders.init) ?? HTTPHeaders() + } +} + +extension URLSessionConfiguration { + /// Returns `httpAdditionalHeaders` as `HTTPHeaders`. + public var headers: HTTPHeaders { + get { (httpAdditionalHeaders as? [String: String]).map(HTTPHeaders.init) ?? HTTPHeaders() } + set { httpAdditionalHeaders = newValue.dictionary } + } +} diff --git a/Pods/Alamofire/Source/HTTPMethod.swift b/Pods/Alamofire/Source/HTTPMethod.swift new file mode 100644 index 0000000..539d214 --- /dev/null +++ b/Pods/Alamofire/Source/HTTPMethod.swift @@ -0,0 +1,56 @@ +// +// HTTPMethod.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. +// + +/// Type representing HTTP methods. Raw `String` value is stored and compared case-sensitively, so +/// `HTTPMethod.get != HTTPMethod(rawValue: "get")`. +/// +/// See https://tools.ietf.org/html/rfc7231#section-4.3 +public struct HTTPMethod: RawRepresentable, Equatable, Hashable { + /// `CONNECT` method. + public static let connect = HTTPMethod(rawValue: "CONNECT") + /// `DELETE` method. + public static let delete = HTTPMethod(rawValue: "DELETE") + /// `GET` method. + public static let get = HTTPMethod(rawValue: "GET") + /// `HEAD` method. + public static let head = HTTPMethod(rawValue: "HEAD") + /// `OPTIONS` method. + public static let options = HTTPMethod(rawValue: "OPTIONS") + /// `PATCH` method. + public static let patch = HTTPMethod(rawValue: "PATCH") + /// `POST` method. + public static let post = HTTPMethod(rawValue: "POST") + /// `PUT` method. + public static let put = HTTPMethod(rawValue: "PUT") + /// `QUERY` method. + public static let query = HTTPMethod(rawValue: "QUERY") + /// `TRACE` method. + public static let trace = HTTPMethod(rawValue: "TRACE") + + public let rawValue: String + + public init(rawValue: String) { + self.rawValue = rawValue + } +} diff --git a/Pods/Alamofire/Source/MultipartFormData.swift b/Pods/Alamofire/Source/MultipartFormData.swift new file mode 100644 index 0000000..364b614 --- /dev/null +++ b/Pods/Alamofire/Source/MultipartFormData.swift @@ -0,0 +1,584 @@ +// +// 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 + + enum EncodingCharacters { + static let crlf = "\r\n" + } + + enum BoundaryGenerator { + enum BoundaryType { + case initial, encapsulated, final + } + + static func randomBoundary() -> String { + let first = UInt32.random(in: UInt32.min...UInt32.max) + let second = UInt32.random(in: UInt32.min...UInt32.max) + + return String(format: "alamofire.boundary.%08x%08x", first, second) + } + + 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 Data(boundaryText.utf8) + } + } + + 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 + + /// Default memory threshold used when encoding `MultipartFormData`, in bytes. + public static let encodingMemoryThreshold: UInt64 = 10_000_000 + + /// 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 { bodyParts.reduce(0) { $0 + $1.bodyContentLength } } + + /// The boundary used to separate the body parts in the encoded form data. + public let boundary: String + + let fileManager: FileManager + + private var bodyParts: [BodyPart] + private var bodyPartError: AFError? + private let streamBufferSize: Int + + // MARK: - Lifecycle + + /// Creates an instance. + /// + /// - Parameters: + /// - fileManager: `FileManager` to use for file operations, if needed. + /// - boundary: Boundary `String` used to separate body parts. + public init(fileManager: FileManager = .default, boundary: String? = nil) { + self.fileManager = fileManager + self.boundary = boundary ?? BoundaryGenerator.randomBoundary() + 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 + // + streamBufferSize = 1024 + } + + // MARK: - Body Parts + + /// Creates a body part from the data and appends it to the instance. + /// + /// 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 + /// + /// - Parameters: + /// - data: `Data` to encoding into the instance. + /// - name: Name to associate with the `Data` in the `Content-Disposition` HTTP header. + /// - fileName: Filename to associate with the `Data` in the `Content-Disposition` HTTP header. + /// - mimeType: MIME type to associate with the data in the `Content-Type` HTTP header. + public func append(_ data: Data, withName name: String, fileName: String? = nil, mimeType: String? = nil) { + 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 instance. + /// + /// 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. + /// + /// - Parameters: + /// - fileURL: `URL` of the file whose content will be encoded into the instance. + /// - name: 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 instance. + /// + /// 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 + /// + /// - Parameters: + /// - fileURL: `URL` of the file whose content will be encoded into the instance. + /// - name: Name to associate with the file content in the `Content-Disposition` HTTP header. + /// - fileName: Filename to associate with the file content in the `Content-Disposition` HTTP header. + /// - mimeType: 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? + //============================================================ + + #if !(os(Linux) || os(Windows)) + do { + let isReachable = try fileURL.checkPromisedItemIsReachable() + guard isReachable else { + setBodyPartError(withReason: .bodyPartFileNotReachable(at: fileURL)) + return + } + } catch { + setBodyPartError(withReason: .bodyPartFileNotReachableWithError(atURL: fileURL, error: error)) + return + } + #endif + + //============================================================ + // Check 3 - is file URL a directory? + //============================================================ + + var isDirectory: ObjCBool = false + let path = fileURL.path + + guard fileManager.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.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 instance. + /// + /// 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 + /// + /// - Parameters: + /// - stream: `InputStream` to encode into the instance. + /// - length: Length, in bytes, of the stream. + /// - name: Name to associate with the stream content in the `Content-Disposition` HTTP header. + /// - fileName: Filename to associate with the stream content in the `Content-Disposition` HTTP header. + /// - mimeType: 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 stream, length, and headers and appends it to the instance. + /// + /// The body part data will be encoded using the following format: + /// + /// - HTTP headers + /// - Encoded stream data + /// - Multipart form boundary + /// + /// - Parameters: + /// - stream: `InputStream` to encode into the instance. + /// - length: Length, in bytes, of the stream. + /// - headers: `HTTPHeaders` 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 appended body parts into a single `Data` value. + /// + /// - Note: 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 `writeEncodedData(to:))` method. + /// + /// - Returns: The encoded `Data`, if encoding is successful. + /// - Throws: An `AFError` if encoding encounters an error. + 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 all appended body parts to 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: File `URL` to which to write the form data. + /// - Throws: An `AFError` if encoding encounters an error. + public func writeEncodedData(to fileURL: URL) throws { + if let bodyPartError = bodyPartError { + throw bodyPartError + } + + if fileManager.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() } + + bodyParts.first?.hasInitialBoundary = true + bodyParts.last?.hasFinalBoundary = true + + for bodyPart in 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 { + let headerText = bodyPart.headers.map { "\($0.name): \($0.value)\(EncodingCharacters.crlf)" } + .joined() + + EncodingCharacters.crlf + + return Data(headerText.utf8) + } + + 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 + } + } + + guard UInt64(encoded.count) == bodyPart.bodyContentLength else { + let error = AFError.UnexpectedInputStreamLength(bytesExpected: bodyPart.bodyContentLength, + bytesRead: UInt64(encoded.count)) + throw AFError.multipartEncodingFailed(reason: .inputStreamReadFailed(error: error)) + } + + 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.. HTTPHeaders { + var disposition = "form-data; name=\"\(name)\"" + if let fileName = fileName { disposition += "; filename=\"\(fileName)\"" } + + var headers: HTTPHeaders = [.contentDisposition(disposition)] + if let mimeType = mimeType { headers.add(.contentType(mimeType)) } + + return headers + } + + // MARK: - Private - Boundary Encoding + + private func initialBoundaryData() -> Data { + BoundaryGenerator.boundaryData(forBoundaryType: .initial, boundary: boundary) + } + + private func encapsulatedBoundaryData() -> Data { + BoundaryGenerator.boundaryData(forBoundaryType: .encapsulated, boundary: boundary) + } + + private func finalBoundaryData() -> Data { + 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) + } +} + +#if canImport(UniformTypeIdentifiers) +import UniformTypeIdentifiers + +extension MultipartFormData { + // MARK: - Private - Mime Type + + private func mimeType(forPathExtension pathExtension: String) -> String { + if #available(iOS 14, macOS 11, tvOS 14, watchOS 7, *) { + return UTType(filenameExtension: pathExtension)?.preferredMIMEType ?? "application/octet-stream" + } else { + if + let id = UTTypeCreatePreferredIdentifierForTag(kUTTagClassFilenameExtension, pathExtension as CFString, nil)?.takeRetainedValue(), + let contentType = UTTypeCopyPreferredTagWithClass(id, kUTTagClassMIMEType)?.takeRetainedValue() { + return contentType as String + } + + return "application/octet-stream" + } + } +} + +#else + +extension MultipartFormData { + // MARK: - Private - Mime Type + + private func mimeType(forPathExtension pathExtension: String) -> String { + #if !(os(Linux) || os(Windows)) + if + let id = UTTypeCreatePreferredIdentifierForTag(kUTTagClassFilenameExtension, pathExtension as CFString, nil)?.takeRetainedValue(), + let contentType = UTTypeCopyPreferredTagWithClass(id, kUTTagClassMIMEType)?.takeRetainedValue() { + return contentType as String + } + #endif + + return "application/octet-stream" + } +} + +#endif diff --git a/Pods/Alamofire/Source/MultipartUpload.swift b/Pods/Alamofire/Source/MultipartUpload.swift new file mode 100644 index 0000000..ceda21f --- /dev/null +++ b/Pods/Alamofire/Source/MultipartUpload.swift @@ -0,0 +1,89 @@ +// +// MultipartUpload.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 + +/// Internal type which encapsulates a `MultipartFormData` upload. +final class MultipartUpload { + lazy var result = Result { try build() } + + @Protected + private(set) var multipartFormData: MultipartFormData + let encodingMemoryThreshold: UInt64 + let request: URLRequestConvertible + let fileManager: FileManager + + init(encodingMemoryThreshold: UInt64, + request: URLRequestConvertible, + multipartFormData: MultipartFormData) { + self.encodingMemoryThreshold = encodingMemoryThreshold + self.request = request + fileManager = multipartFormData.fileManager + self.multipartFormData = multipartFormData + } + + func build() throws -> UploadRequest.Uploadable { + let uploadable: UploadRequest.Uploadable + if $multipartFormData.contentLength < encodingMemoryThreshold { + let data = try $multipartFormData.read { try $0.encode() } + + uploadable = .data(data) + } else { + let tempDirectoryURL = fileManager.temporaryDirectory + let directoryURL = tempDirectoryURL.appendingPathComponent("org.alamofire.manager/multipart.form.data") + let fileName = UUID().uuidString + let fileURL = directoryURL.appendingPathComponent(fileName) + + try fileManager.createDirectory(at: directoryURL, withIntermediateDirectories: true, attributes: nil) + + do { + try $multipartFormData.read { try $0.writeEncodedData(to: fileURL) } + } catch { + // Cleanup after attempted write if it fails. + try? fileManager.removeItem(at: fileURL) + throw error + } + + uploadable = .file(fileURL, shouldRemove: true) + } + + return uploadable + } +} + +extension MultipartUpload: UploadConvertible { + func asURLRequest() throws -> URLRequest { + var urlRequest = try request.asURLRequest() + + $multipartFormData.read { multipartFormData in + urlRequest.headers.add(.contentType(multipartFormData.contentType)) + } + + return urlRequest + } + + func createUploadable() throws -> UploadRequest.Uploadable { + try result.get() + } +} diff --git a/Pods/Alamofire/Source/NetworkReachabilityManager.swift b/Pods/Alamofire/Source/NetworkReachabilityManager.swift new file mode 100644 index 0000000..d724722 --- /dev/null +++ b/Pods/Alamofire/Source/NetworkReachabilityManager.swift @@ -0,0 +1,292 @@ +// +// 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) || os(Linux) || os(Windows)) + +import Foundation +import SystemConfiguration + +/// The `NetworkReachabilityManager` class listens for reachability changes of hosts and addresses for both cellular 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. + public enum NetworkReachabilityStatus { + /// It is unknown whether the network is reachable. + case unknown + /// The network is not reachable. + case notReachable + /// The network is reachable on the associated `ConnectionType`. + case reachable(ConnectionType) + + init(_ flags: SCNetworkReachabilityFlags) { + guard flags.isActuallyReachable else { self = .notReachable; return } + + var networkStatus: NetworkReachabilityStatus = .reachable(.ethernetOrWiFi) + + if flags.isCellular { networkStatus = .reachable(.cellular) } + + self = networkStatus + } + + /// Defines the various connection types detected by reachability flags. + public enum ConnectionType { + /// The connection type is either over Ethernet or WiFi. + case ethernetOrWiFi + /// The connection type is a cellular connection. + case cellular + } + } + + /// A closure executed when the network reachability status changes. The closure takes a single argument: the + /// network reachability status. + public typealias Listener = (NetworkReachabilityStatus) -> Void + + /// Default `NetworkReachabilityManager` for the zero address and a `listenerQueue` of `.main`. + public static let `default` = NetworkReachabilityManager() + + // MARK: - Properties + + /// Whether the network is currently reachable. + open var isReachable: Bool { isReachableOnCellular || isReachableOnEthernetOrWiFi } + + /// Whether the network is currently reachable over the cellular interface. + /// + /// - Note: Using this property to decide whether to make a high or low bandwidth request is not recommended. + /// Instead, set the `allowsCellularAccess` on any `URLRequest`s being issued. + /// + open var isReachableOnCellular: Bool { status == .reachable(.cellular) } + + /// Whether the network is currently reachable over Ethernet or WiFi interface. + open var isReachableOnEthernetOrWiFi: Bool { status == .reachable(.ethernetOrWiFi) } + + /// `DispatchQueue` on which reachability will update. + public let reachabilityQueue = DispatchQueue(label: "org.alamofire.reachabilityQueue") + + /// Flags of the current reachability type, if any. + open var flags: SCNetworkReachabilityFlags? { + var flags = SCNetworkReachabilityFlags() + + return SCNetworkReachabilityGetFlags(reachability, &flags) ? flags : nil + } + + /// The current network reachability status. + open var status: NetworkReachabilityStatus { + flags.map(NetworkReachabilityStatus.init) ?? .unknown + } + + /// Mutable state storage. + struct MutableState { + /// A closure executed when the network reachability status changes. + var listener: Listener? + /// `DispatchQueue` on which listeners will be called. + var listenerQueue: DispatchQueue? + /// Previously calculated status. + var previousStatus: NetworkReachabilityStatus? + } + + /// `SCNetworkReachability` instance providing notifications. + private let reachability: SCNetworkReachability + + /// Protected storage for mutable state. + @Protected + private var mutableState = MutableState() + + // MARK: - Initialization + + /// Creates an instance with the specified host. + /// + /// - Note: The `host` value must *not* contain a scheme, just the hostname. + /// + /// - Parameters: + /// - host: Host used to evaluate network reachability. Must *not* include the scheme (e.g. `https`). + public convenience init?(host: String) { + guard let reachability = SCNetworkReachabilityCreateWithName(nil, host) else { return nil } + + self.init(reachability: reachability) + } + + /// Creates an 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. + public convenience init?() { + var zero = sockaddr() + zero.sa_len = UInt8(MemoryLayout.size) + zero.sa_family = sa_family_t(AF_INET) + + guard let reachability = SCNetworkReachabilityCreateWithAddress(nil, &zero) else { return nil } + + self.init(reachability: reachability) + } + + private init(reachability: SCNetworkReachability) { + self.reachability = reachability + } + + deinit { + stopListening() + } + + // MARK: - Listening + + /// Starts listening for changes in network reachability status. + /// + /// - Note: Stops and removes any existing listener. + /// + /// - Parameters: + /// - queue: `DispatchQueue` on which to call the `listener` closure. `.main` by default. + /// - listener: `Listener` closure called when reachability changes. + /// + /// - Returns: `true` if listening was started successfully, `false` otherwise. + @discardableResult + open func startListening(onQueue queue: DispatchQueue = .main, + onUpdatePerforming listener: @escaping Listener) -> Bool { + stopListening() + + $mutableState.write { state in + state.listenerQueue = queue + state.listener = listener + } + + let weakManager = WeakManager(manager: self) + + var context = SCNetworkReachabilityContext( + version: 0, + info: Unmanaged.passUnretained(weakManager).toOpaque(), + retain: { info in + let unmanaged = Unmanaged.fromOpaque(info) + _ = unmanaged.retain() + + return UnsafeRawPointer(unmanaged.toOpaque()) + }, + release: { info in + let unmanaged = Unmanaged.fromOpaque(info) + unmanaged.release() + }, + copyDescription: { info in + let unmanaged = Unmanaged.fromOpaque(info) + let weakManager = unmanaged.takeUnretainedValue() + let description = weakManager.manager?.flags?.readableDescription ?? "nil" + + return Unmanaged.passRetained(description as CFString) + }) + let callback: SCNetworkReachabilityCallBack = { _, flags, info in + guard let info = info else { return } + + let weakManager = Unmanaged.fromOpaque(info).takeUnretainedValue() + weakManager.manager?.notifyListener(flags) + } + + let queueAdded = SCNetworkReachabilitySetDispatchQueue(reachability, reachabilityQueue) + let callbackAdded = SCNetworkReachabilitySetCallback(reachability, callback, &context) + + // Manually call listener to give initial state, since the framework may not. + if let currentFlags = flags { + reachabilityQueue.async { + self.notifyListener(currentFlags) + } + } + + return callbackAdded && queueAdded + } + + /// Stops listening for changes in network reachability status. + open func stopListening() { + SCNetworkReachabilitySetCallback(reachability, nil, nil) + SCNetworkReachabilitySetDispatchQueue(reachability, nil) + $mutableState.write { state in + state.listener = nil + state.listenerQueue = nil + state.previousStatus = nil + } + } + + // MARK: - Internal - Listener Notification + + /// Calls the `listener` closure of the `listenerQueue` if the computed status hasn't changed. + /// + /// - Note: Should only be called from the `reachabilityQueue`. + /// + /// - Parameter flags: `SCNetworkReachabilityFlags` to use to calculate the status. + func notifyListener(_ flags: SCNetworkReachabilityFlags) { + let newStatus = NetworkReachabilityStatus(flags) + + $mutableState.write { state in + guard state.previousStatus != newStatus else { return } + + state.previousStatus = newStatus + + let listener = state.listener + state.listenerQueue?.async { listener?(newStatus) } + } + } + + private final class WeakManager { + weak var manager: NetworkReachabilityManager? + + init(manager: NetworkReachabilityManager?) { + self.manager = manager + } + } +} + +// MARK: - + +extension NetworkReachabilityManager.NetworkReachabilityStatus: Equatable {} + +extension SCNetworkReachabilityFlags { + var isReachable: Bool { contains(.reachable) } + var isConnectionRequired: Bool { contains(.connectionRequired) } + var canConnectAutomatically: Bool { contains(.connectionOnDemand) || contains(.connectionOnTraffic) } + var canConnectWithoutUserInteraction: Bool { canConnectAutomatically && !contains(.interventionRequired) } + var isActuallyReachable: Bool { isReachable && (!isConnectionRequired || canConnectWithoutUserInteraction) } + var isCellular: Bool { + #if os(iOS) || os(tvOS) + return contains(.isWWAN) + #else + return false + #endif + } + + /// Human readable `String` for all states, to help with debugging. + var readableDescription: String { + let W = isCellular ? "W" : "-" + let R = isReachable ? "R" : "-" + let c = isConnectionRequired ? "c" : "-" + let t = contains(.transientConnection) ? "t" : "-" + let i = contains(.interventionRequired) ? "i" : "-" + let C = contains(.connectionOnTraffic) ? "C" : "-" + let D = contains(.connectionOnDemand) ? "D" : "-" + let l = contains(.isLocalAddress) ? "l" : "-" + let d = contains(.isDirect) ? "d" : "-" + let a = contains(.connectionAutomatic) ? "a" : "-" + + return "\(W)\(R) \(c)\(t)\(i)\(C)\(D)\(l)\(d)\(a)" + } +} +#endif diff --git a/Pods/Alamofire/Source/Notifications.swift b/Pods/Alamofire/Source/Notifications.swift new file mode 100644 index 0000000..66434b6 --- /dev/null +++ b/Pods/Alamofire/Source/Notifications.swift @@ -0,0 +1,115 @@ +// +// 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 Request { + /// Posted when a `Request` is resumed. The `Notification` contains the resumed `Request`. + public static let didResumeNotification = Notification.Name(rawValue: "org.alamofire.notification.name.request.didResume") + /// Posted when a `Request` is suspended. The `Notification` contains the suspended `Request`. + public static let didSuspendNotification = Notification.Name(rawValue: "org.alamofire.notification.name.request.didSuspend") + /// Posted when a `Request` is cancelled. The `Notification` contains the cancelled `Request`. + public static let didCancelNotification = Notification.Name(rawValue: "org.alamofire.notification.name.request.didCancel") + /// Posted when a `Request` is finished. The `Notification` contains the completed `Request`. + public static let didFinishNotification = Notification.Name(rawValue: "org.alamofire.notification.name.request.didFinish") + + /// Posted when a `URLSessionTask` is resumed. The `Notification` contains the `Request` associated with the `URLSessionTask`. + public static let didResumeTaskNotification = Notification.Name(rawValue: "org.alamofire.notification.name.request.didResumeTask") + /// Posted when a `URLSessionTask` is suspended. The `Notification` contains the `Request` associated with the `URLSessionTask`. + public static let didSuspendTaskNotification = Notification.Name(rawValue: "org.alamofire.notification.name.request.didSuspendTask") + /// Posted when a `URLSessionTask` is cancelled. The `Notification` contains the `Request` associated with the `URLSessionTask`. + public static let didCancelTaskNotification = Notification.Name(rawValue: "org.alamofire.notification.name.request.didCancelTask") + /// Posted when a `URLSessionTask` is completed. The `Notification` contains the `Request` associated with the `URLSessionTask`. + public static let didCompleteTaskNotification = Notification.Name(rawValue: "org.alamofire.notification.name.request.didCompleteTask") +} + +// MARK: - + +extension Notification { + /// The `Request` contained by the instance's `userInfo`, `nil` otherwise. + public var request: Request? { + userInfo?[String.requestKey] as? Request + } + + /// Convenience initializer for a `Notification` containing a `Request` payload. + /// + /// - Parameters: + /// - name: The name of the notification. + /// - request: The `Request` payload. + init(name: Notification.Name, request: Request) { + self.init(name: name, object: nil, userInfo: [String.requestKey: request]) + } +} + +extension NotificationCenter { + /// Convenience function for posting notifications with `Request` payloads. + /// + /// - Parameters: + /// - name: The name of the notification. + /// - request: The `Request` payload. + func postNotification(named name: Notification.Name, with request: Request) { + let notification = Notification(name: name, request: request) + post(notification) + } +} + +extension String { + /// User info dictionary key representing the `Request` associated with the notification. + fileprivate static let requestKey = "org.alamofire.notification.key.request" +} + +/// `EventMonitor` that provides Alamofire's notifications. +public final class AlamofireNotifications: EventMonitor { + public func requestDidResume(_ request: Request) { + NotificationCenter.default.postNotification(named: Request.didResumeNotification, with: request) + } + + public func requestDidSuspend(_ request: Request) { + NotificationCenter.default.postNotification(named: Request.didSuspendNotification, with: request) + } + + public func requestDidCancel(_ request: Request) { + NotificationCenter.default.postNotification(named: Request.didCancelNotification, with: request) + } + + public func requestDidFinish(_ request: Request) { + NotificationCenter.default.postNotification(named: Request.didFinishNotification, with: request) + } + + public func request(_ request: Request, didResumeTask task: URLSessionTask) { + NotificationCenter.default.postNotification(named: Request.didResumeTaskNotification, with: request) + } + + public func request(_ request: Request, didSuspendTask task: URLSessionTask) { + NotificationCenter.default.postNotification(named: Request.didSuspendTaskNotification, with: request) + } + + public func request(_ request: Request, didCancelTask task: URLSessionTask) { + NotificationCenter.default.postNotification(named: Request.didCancelTaskNotification, with: request) + } + + public func request(_ request: Request, didCompleteTask task: URLSessionTask, with error: AFError?) { + NotificationCenter.default.postNotification(named: Request.didCompleteTaskNotification, with: request) + } +} diff --git a/Pods/Alamofire/Source/OperationQueue+Alamofire.swift b/Pods/Alamofire/Source/OperationQueue+Alamofire.swift new file mode 100644 index 0000000..b06a0cc --- /dev/null +++ b/Pods/Alamofire/Source/OperationQueue+Alamofire.swift @@ -0,0 +1,49 @@ +// +// OperationQueue+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 + +extension OperationQueue { + /// Creates an instance using the provided parameters. + /// + /// - Parameters: + /// - qualityOfService: `QualityOfService` to be applied to the queue. `.default` by default. + /// - maxConcurrentOperationCount: Maximum concurrent operations. + /// `OperationQueue.defaultMaxConcurrentOperationCount` by default. + /// - underlyingQueue: Underlying `DispatchQueue`. `nil` by default. + /// - name: Name for the queue. `nil` by default. + /// - startSuspended: Whether the queue starts suspended. `false` by default. + convenience init(qualityOfService: QualityOfService = .default, + maxConcurrentOperationCount: Int = OperationQueue.defaultMaxConcurrentOperationCount, + underlyingQueue: DispatchQueue? = nil, + name: String? = nil, + startSuspended: Bool = false) { + self.init() + self.qualityOfService = qualityOfService + self.maxConcurrentOperationCount = maxConcurrentOperationCount + self.underlyingQueue = underlyingQueue + self.name = name + isSuspended = startSuspended + } +} diff --git a/Pods/Alamofire/Source/ParameterEncoder.swift b/Pods/Alamofire/Source/ParameterEncoder.swift new file mode 100644 index 0000000..8916978 --- /dev/null +++ b/Pods/Alamofire/Source/ParameterEncoder.swift @@ -0,0 +1,213 @@ +// +// ParameterEncoder.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 encode any `Encodable` type into a `URLRequest`. +public protocol ParameterEncoder { + /// Encode the provided `Encodable` parameters into `request`. + /// + /// - Parameters: + /// - parameters: The `Encodable` parameter value. + /// - request: The `URLRequest` into which to encode the parameters. + /// + /// - Returns: A `URLRequest` with the result of the encoding. + /// - Throws: An `Error` when encoding fails. For Alamofire provided encoders, this will be an instance of + /// `AFError.parameterEncoderFailed` with an associated `ParameterEncoderFailureReason`. + func encode(_ parameters: Parameters?, into request: URLRequest) throws -> URLRequest +} + +/// A `ParameterEncoder` that encodes types as JSON body data. +/// +/// If no `Content-Type` header is already set on the provided `URLRequest`s, it's set to `application/json`. +open class JSONParameterEncoder: ParameterEncoder { + /// Returns an encoder with default parameters. + public static var `default`: JSONParameterEncoder { JSONParameterEncoder() } + + /// Returns an encoder with `JSONEncoder.outputFormatting` set to `.prettyPrinted`. + public static var prettyPrinted: JSONParameterEncoder { + let encoder = JSONEncoder() + encoder.outputFormatting = .prettyPrinted + + return JSONParameterEncoder(encoder: encoder) + } + + /// Returns an encoder with `JSONEncoder.outputFormatting` set to `.sortedKeys`. + @available(macOS 10.13, iOS 11.0, tvOS 11.0, watchOS 4.0, *) + public static var sortedKeys: JSONParameterEncoder { + let encoder = JSONEncoder() + encoder.outputFormatting = .sortedKeys + + return JSONParameterEncoder(encoder: encoder) + } + + /// `JSONEncoder` used to encode parameters. + public let encoder: JSONEncoder + + /// Creates an instance with the provided `JSONEncoder`. + /// + /// - Parameter encoder: The `JSONEncoder`. `JSONEncoder()` by default. + public init(encoder: JSONEncoder = JSONEncoder()) { + self.encoder = encoder + } + + open func encode(_ parameters: Parameters?, + into request: URLRequest) throws -> URLRequest { + guard let parameters = parameters else { return request } + + var request = request + + do { + let data = try encoder.encode(parameters) + request.httpBody = data + if request.headers["Content-Type"] == nil { + request.headers.update(.contentType("application/json")) + } + } catch { + throw AFError.parameterEncodingFailed(reason: .jsonEncodingFailed(error: error)) + } + + return request + } +} + +extension ParameterEncoder where Self == JSONParameterEncoder { + /// Provides a default `JSONParameterEncoder` instance. + public static var json: JSONParameterEncoder { JSONParameterEncoder() } + + /// Creates a `JSONParameterEncoder` using the provided `JSONEncoder`. + /// + /// - Parameter encoder: `JSONEncoder` used to encode parameters. `JSONEncoder()` by default. + /// - Returns: The `JSONParameterEncoder`. + public static func json(encoder: JSONEncoder = JSONEncoder()) -> JSONParameterEncoder { + JSONParameterEncoder(encoder: encoder) + } +} + +/// A `ParameterEncoder` that encodes types as URL-encoded query strings to be set on the URL or as body data, depending +/// on the `Destination` set. +/// +/// If no `Content-Type` header is already set on the provided `URLRequest`s, it will be set to +/// `application/x-www-form-urlencoded; charset=utf-8`. +/// +/// Encoding behavior can be customized by passing an instance of `URLEncodedFormEncoder` to the initializer. +open class URLEncodedFormParameterEncoder: ParameterEncoder { + /// Defines where the URL-encoded string should be set for each `URLRequest`. + public enum Destination { + /// Applies the encoded query string to any existing query string for `.get`, `.head`, and `.delete` request. + /// Sets it to the `httpBody` for all other methods. + case methodDependent + /// Applies the encoded query string to any existing query string from the `URLRequest`. + case queryString + /// Applies the encoded query string to the `httpBody` of the `URLRequest`. + case httpBody + + /// Determines whether the URL-encoded string should be applied to the `URLRequest`'s `url`. + /// + /// - Parameter method: The `HTTPMethod`. + /// + /// - Returns: Whether the URL-encoded string should be applied to a `URL`. + func encodesParametersInURL(for method: HTTPMethod) -> Bool { + switch self { + case .methodDependent: return [.get, .head, .delete].contains(method) + case .queryString: return true + case .httpBody: return false + } + } + } + + /// Returns an encoder with default parameters. + public static var `default`: URLEncodedFormParameterEncoder { URLEncodedFormParameterEncoder() } + + /// The `URLEncodedFormEncoder` to use. + public let encoder: URLEncodedFormEncoder + + /// The `Destination` for the URL-encoded string. + public let destination: Destination + + /// Creates an instance with the provided `URLEncodedFormEncoder` instance and `Destination` value. + /// + /// - Parameters: + /// - encoder: The `URLEncodedFormEncoder`. `URLEncodedFormEncoder()` by default. + /// - destination: The `Destination`. `.methodDependent` by default. + public init(encoder: URLEncodedFormEncoder = URLEncodedFormEncoder(), destination: Destination = .methodDependent) { + self.encoder = encoder + self.destination = destination + } + + open func encode(_ parameters: Parameters?, + into request: URLRequest) throws -> URLRequest { + guard let parameters = parameters else { return request } + + var request = request + + guard let url = request.url else { + throw AFError.parameterEncoderFailed(reason: .missingRequiredComponent(.url)) + } + + guard let method = request.method else { + let rawValue = request.method?.rawValue ?? "nil" + throw AFError.parameterEncoderFailed(reason: .missingRequiredComponent(.httpMethod(rawValue: rawValue))) + } + + if destination.encodesParametersInURL(for: method), + var components = URLComponents(url: url, resolvingAgainstBaseURL: false) { + let query: String = try Result { try encoder.encode(parameters) } + .mapError { AFError.parameterEncoderFailed(reason: .encoderFailed(error: $0)) }.get() + let newQueryString = [components.percentEncodedQuery, query].compactMap { $0 }.joinedWithAmpersands() + components.percentEncodedQuery = newQueryString.isEmpty ? nil : newQueryString + + guard let newURL = components.url else { + throw AFError.parameterEncoderFailed(reason: .missingRequiredComponent(.url)) + } + + request.url = newURL + } else { + if request.headers["Content-Type"] == nil { + request.headers.update(.contentType("application/x-www-form-urlencoded; charset=utf-8")) + } + + request.httpBody = try Result { try encoder.encode(parameters) } + .mapError { AFError.parameterEncoderFailed(reason: .encoderFailed(error: $0)) }.get() + } + + return request + } +} + +extension ParameterEncoder where Self == URLEncodedFormParameterEncoder { + /// Provides a default `URLEncodedFormParameterEncoder` instance. + public static var urlEncodedForm: URLEncodedFormParameterEncoder { URLEncodedFormParameterEncoder() } + + /// Creates a `URLEncodedFormParameterEncoder` with the provided encoder and destination. + /// + /// - Parameters: + /// - encoder: `URLEncodedFormEncoder` used to encode the parameters. `URLEncodedFormEncoder()` by default. + /// - destination: `Destination` to which to encode the parameters. `.methodDependent` by default. + /// - Returns: The `URLEncodedFormParameterEncoder`. + public static func urlEncodedForm(encoder: URLEncodedFormEncoder = URLEncodedFormEncoder(), + destination: URLEncodedFormParameterEncoder.Destination = .methodDependent) -> URLEncodedFormParameterEncoder { + URLEncodedFormParameterEncoder(encoder: encoder, destination: destination) + } +} diff --git a/Pods/Alamofire/Source/ParameterEncoding.swift b/Pods/Alamofire/Source/ParameterEncoding.swift new file mode 100644 index 0000000..ea61256 --- /dev/null +++ b/Pods/Alamofire/Source/ParameterEncoding.swift @@ -0,0 +1,346 @@ +// +// 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 + +/// 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 `URLRequest` by encoding parameters and applying them on the passed request. + /// + /// - Parameters: + /// - urlRequest: `URLRequestConvertible` value onto which parameters will be encoded. + /// - parameters: `Parameters` to encode onto the request. + /// + /// - Returns: The encoded `URLRequest`. + /// - Throws: Any `Error` produced during parameter encoding. + 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. + public enum Destination { + /// 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. + case methodDependent + /// Sets or appends encoded query string result to existing query string. + case queryString + /// Sets encoded query string result as the HTTP body of the URL request. + case httpBody + + func encodesParametersInURL(for method: HTTPMethod) -> Bool { + switch self { + case .methodDependent: return [.get, .head, .delete].contains(method) + case .queryString: return true + case .httpBody: return false + } + } + } + + /// Configures how `Array` parameters are encoded. + public enum ArrayEncoding { + /// An empty set of square brackets is appended to the key for every value. This is the default behavior. + case brackets + /// No brackets are appended. The key is encoded as is. + case noBrackets + /// Brackets containing the item index are appended. This matches the jQuery and Node.js behavior. + case indexInBrackets + /// Provide a custom array key encoding with the given closure. + case custom((_ key: String, _ index: Int) -> String) + + func encode(key: String, atIndex index: Int) -> String { + switch self { + case .brackets: + return "\(key)[]" + case .noBrackets: + return key + case .indexInBrackets: + return "\(key)[\(index)]" + case let .custom(encoding): + return encoding(key, index) + } + } + } + + /// Configures how `Bool` parameters are encoded. + public enum BoolEncoding { + /// Encode `true` as `1` and `false` as `0`. This is the default behavior. + case numeric + /// Encode `true` and `false` as string literals. + case 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 with a `.methodDependent` destination. + public static var `default`: URLEncoding { URLEncoding() } + + /// Returns a `URLEncoding` instance with a `.queryString` destination. + public static var queryString: URLEncoding { URLEncoding(destination: .queryString) } + + /// Returns a `URLEncoding` instance with an `.httpBody` destination. + public static var httpBody: URLEncoding { 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 an instance using the specified parameters. + /// + /// - Parameters: + /// - destination: `Destination` defining where the encoded query string will be applied. `.methodDependent` by + /// default. + /// - arrayEncoding: `ArrayEncoding` to use. `.brackets` by default. + /// - boolEncoding: `BoolEncoding` to use. `.numeric` by default. + public init(destination: Destination = .methodDependent, + arrayEncoding: ArrayEncoding = .brackets, + boolEncoding: BoolEncoding = .numeric) { + self.destination = destination + self.arrayEncoding = arrayEncoding + self.boolEncoding = boolEncoding + } + + // MARK: Encoding + + 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 = urlRequest.method, destination.encodesParametersInURL(for: 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.headers["Content-Type"] == nil { + urlRequest.headers.update(.contentType("application/x-www-form-urlencoded; charset=utf-8")) + } + + urlRequest.httpBody = Data(query(parameters).utf8) + } + + return urlRequest + } + + /// Creates a percent-escaped, URL encoded query string components from the given key-value pair recursively. + /// + /// - Parameters: + /// - key: Key of the query component. + /// - value: 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)] = [] + switch value { + case let dictionary as [String: Any]: + for (nestedKey, value) in dictionary { + components += queryComponents(fromKey: "\(key)[\(nestedKey)]", value: value) + } + case let array as [Any]: + for (index, value) in array.enumerated() { + components += queryComponents(fromKey: arrayEncoding.encode(key: key, atIndex: index), value: value) + } + case let number as NSNumber: + if number.isBool { + components.append((escape(key), escape(boolEncoding.encode(value: number.boolValue)))) + } else { + components.append((escape(key), escape("\(number)"))) + } + case let bool as Bool: + components.append((escape(key), escape(boolEncoding.encode(value: bool)))) + default: + components.append((escape(key), escape("\(value)"))) + } + return components + } + + /// Creates a percent-escaped string following RFC 3986 for a query string key or value. + /// + /// - Parameter string: `String` to be percent-escaped. + /// + /// - Returns: The percent-escaped `String`. + public func escape(_ string: String) -> String { + string.addingPercentEncoding(withAllowedCharacters: .afURLQueryAllowed) ?? string + } + + private func query(_ parameters: [String: Any]) -> 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: "&") + } +} + +// 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 { + public enum Error: Swift.Error { + case invalidJSONObject + } + + // MARK: Properties + + /// Returns a `JSONEncoding` instance with default writing options. + public static var `default`: JSONEncoding { JSONEncoding() } + + /// Returns a `JSONEncoding` instance with `.prettyPrinted` writing options. + public static var prettyPrinted: JSONEncoding { JSONEncoding(options: .prettyPrinted) } + + /// The options for writing the parameters as JSON data. + public let options: JSONSerialization.WritingOptions + + // MARK: Initialization + + /// Creates an instance using the specified `WritingOptions`. + /// + /// - Parameter options: `JSONSerialization.WritingOptions` to use. + public init(options: JSONSerialization.WritingOptions = []) { + self.options = options + } + + // MARK: Encoding + + public func encode(_ urlRequest: URLRequestConvertible, with parameters: Parameters?) throws -> URLRequest { + var urlRequest = try urlRequest.asURLRequest() + + guard let parameters = parameters else { return urlRequest } + + guard JSONSerialization.isValidJSONObject(parameters) else { + throw AFError.parameterEncodingFailed(reason: .jsonEncodingFailed(error: Error.invalidJSONObject)) + } + + do { + let data = try JSONSerialization.data(withJSONObject: parameters, options: options) + + if urlRequest.headers["Content-Type"] == nil { + urlRequest.headers.update(.contentType("application/json")) + } + + urlRequest.httpBody = data + } catch { + throw AFError.parameterEncodingFailed(reason: .jsonEncodingFailed(error: error)) + } + + return urlRequest + } + + /// Encodes any JSON compatible object into a `URLRequest`. + /// + /// - Parameters: + /// - urlRequest: `URLRequestConvertible` value into which the object will be encoded. + /// - jsonObject: `Any` value (must be JSON compatible` to be encoded into the `URLRequest`. `nil` by default. + /// + /// - Returns: The encoded `URLRequest`. + /// - Throws: Any `Error` produced during encoding. + public func encode(_ urlRequest: URLRequestConvertible, withJSONObject jsonObject: Any? = nil) throws -> URLRequest { + var urlRequest = try urlRequest.asURLRequest() + + guard let jsonObject = jsonObject else { return urlRequest } + + guard JSONSerialization.isValidJSONObject(jsonObject) else { + throw AFError.parameterEncodingFailed(reason: .jsonEncodingFailed(error: Error.invalidJSONObject)) + } + + do { + let data = try JSONSerialization.data(withJSONObject: jsonObject, options: options) + + if urlRequest.headers["Content-Type"] == nil { + urlRequest.headers.update(.contentType("application/json")) + } + + urlRequest.httpBody = data + } catch { + throw AFError.parameterEncodingFailed(reason: .jsonEncodingFailed(error: error)) + } + + return urlRequest + } +} + +extension JSONEncoding.Error { + public var localizedDescription: String { + """ + Invalid JSON object provided for parameter or object encoding. \ + This is most likely due to a value which can't be represented in Objective-C. + """ + } +} + +// MARK: - + +extension NSNumber { + fileprivate var isBool: Bool { + // Use Obj-C type encoding to check whether the underlying type is a `Bool`, as it's guaranteed as part of + // swift-corelibs-foundation, per [this discussion on the Swift forums](https://forums.swift.org/t/alamofire-on-linux-possible-but-not-release-ready/34553/22). + String(cString: objCType) == "c" + } +} diff --git a/Pods/Alamofire/Source/Protected.swift b/Pods/Alamofire/Source/Protected.swift new file mode 100644 index 0000000..2c056fa --- /dev/null +++ b/Pods/Alamofire/Source/Protected.swift @@ -0,0 +1,161 @@ +// +// Protected.swift +// +// Copyright (c) 2014-2020 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 + +private protocol Lock { + func lock() + func unlock() +} + +extension Lock { + /// Executes a closure returning a value while acquiring the lock. + /// + /// - Parameter closure: The closure to run. + /// + /// - Returns: The value the closure generated. + func around(_ closure: () throws -> T) rethrows -> T { + lock(); defer { unlock() } + return try closure() + } + + /// Execute a closure while acquiring the lock. + /// + /// - Parameter closure: The closure to run. + func around(_ closure: () throws -> Void) rethrows { + lock(); defer { unlock() } + try closure() + } +} + +#if os(Linux) || os(Windows) + +extension NSLock: Lock {} + +#endif + +#if os(macOS) || os(iOS) || os(watchOS) || os(tvOS) +/// An `os_unfair_lock` wrapper. +final class UnfairLock: Lock { + private let unfairLock: os_unfair_lock_t + + init() { + unfairLock = .allocate(capacity: 1) + unfairLock.initialize(to: os_unfair_lock()) + } + + deinit { + unfairLock.deinitialize(count: 1) + unfairLock.deallocate() + } + + fileprivate func lock() { + os_unfair_lock_lock(unfairLock) + } + + fileprivate func unlock() { + os_unfair_lock_unlock(unfairLock) + } +} +#endif + +/// A thread-safe wrapper around a value. +@propertyWrapper +@dynamicMemberLookup +final class Protected { + #if os(macOS) || os(iOS) || os(watchOS) || os(tvOS) + private let lock = UnfairLock() + #elseif os(Linux) || os(Windows) + private let lock = NSLock() + #endif + private var value: T + + init(_ value: T) { + self.value = value + } + + /// The contained value. Unsafe for anything more than direct read or write. + var wrappedValue: T { + get { lock.around { value } } + set { lock.around { value = newValue } } + } + + var projectedValue: Protected { self } + + init(wrappedValue: T) { + value = wrappedValue + } + + /// Synchronously read or transform the contained value. + /// + /// - Parameter closure: The closure to execute. + /// + /// - Returns: The return value of the closure passed. + func read(_ closure: (T) throws -> U) rethrows -> U { + try lock.around { try closure(self.value) } + } + + /// Synchronously modify the protected value. + /// + /// - Parameter closure: The closure to execute. + /// + /// - Returns: The modified value. + @discardableResult + func write(_ closure: (inout T) throws -> U) rethrows -> U { + try lock.around { try closure(&self.value) } + } + + subscript(dynamicMember keyPath: WritableKeyPath) -> Property { + get { lock.around { value[keyPath: keyPath] } } + set { lock.around { value[keyPath: keyPath] = newValue } } + } + + subscript(dynamicMember keyPath: KeyPath) -> Property { + lock.around { value[keyPath: keyPath] } + } +} + +extension Protected where T == Request.MutableState { + /// Attempts to transition to the passed `State`. + /// + /// - Parameter state: The `State` to attempt transition to. + /// + /// - Returns: Whether the transition occurred. + func attemptToTransitionTo(_ state: Request.State) -> Bool { + lock.around { + guard value.state.canTransitionTo(state) else { return false } + + value.state = state + + return true + } + } + + /// Perform a closure while locked with the provided `Request.State`. + /// + /// - Parameter perform: The closure to perform while locked. + func withState(perform: (Request.State) -> Void) { + lock.around { perform(value.state) } + } +} diff --git a/Pods/Alamofire/Source/RedirectHandler.swift b/Pods/Alamofire/Source/RedirectHandler.swift new file mode 100644 index 0000000..cf88abf --- /dev/null +++ b/Pods/Alamofire/Source/RedirectHandler.swift @@ -0,0 +1,111 @@ +// +// RedirectHandler.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 handles how an HTTP redirect response from a remote server should be redirected to the new request. +public protocol RedirectHandler { + /// Determines how the HTTP redirect response should be redirected to the new request. + /// + /// The `completion` closure should be passed one of three possible options: + /// + /// 1. The new request specified by the redirect (this is the most common use case). + /// 2. A modified version of the new request (you may want to route it somewhere else). + /// 3. A `nil` value to deny the redirect request and return the body of the redirect response. + /// + /// - Parameters: + /// - task: The `URLSessionTask` whose request resulted in a redirect. + /// - request: The `URLRequest` to the new location specified by the redirect response. + /// - response: The `HTTPURLResponse` containing the server's response to the original request. + /// - completion: The closure to execute containing the new `URLRequest`, a modified `URLRequest`, or `nil`. + func task(_ task: URLSessionTask, + willBeRedirectedTo request: URLRequest, + for response: HTTPURLResponse, + completion: @escaping (URLRequest?) -> Void) +} + +// MARK: - + +/// `Redirector` is a convenience `RedirectHandler` making it easy to follow, not follow, or modify a redirect. +public struct Redirector { + /// Defines the behavior of the `Redirector` type. + public enum Behavior { + /// Follow the redirect as defined in the response. + case follow + /// Do not follow the redirect defined in the response. + case doNotFollow + /// Modify the redirect request defined in the response. + case modify((URLSessionTask, URLRequest, HTTPURLResponse) -> URLRequest?) + } + + /// Returns a `Redirector` with a `.follow` `Behavior`. + public static let follow = Redirector(behavior: .follow) + /// Returns a `Redirector` with a `.doNotFollow` `Behavior`. + public static let doNotFollow = Redirector(behavior: .doNotFollow) + + /// The `Behavior` of the `Redirector`. + public let behavior: Behavior + + /// Creates a `Redirector` instance from the `Behavior`. + /// + /// - Parameter behavior: The `Behavior`. + public init(behavior: Behavior) { + self.behavior = behavior + } +} + +// MARK: - + +extension Redirector: RedirectHandler { + public func task(_ task: URLSessionTask, + willBeRedirectedTo request: URLRequest, + for response: HTTPURLResponse, + completion: @escaping (URLRequest?) -> Void) { + switch behavior { + case .follow: + completion(request) + case .doNotFollow: + completion(nil) + case let .modify(closure): + let request = closure(task, request, response) + completion(request) + } + } +} + +extension RedirectHandler where Self == Redirector { + /// Provides a `Redirector` which follows redirects. Equivalent to `Redirector.follow`. + public static var follow: Redirector { .follow } + + /// Provides a `Redirector` which does not follow redirects. Equivalent to `Redirector.doNotFollow`. + public static var doNotFollow: Redirector { .doNotFollow } + + /// Creates a `Redirector` which modifies the redirected `URLRequest` using the provided closure. + /// + /// - Parameter closure: Closure used to modify the redirect. + /// - Returns: The `Redirector`. + public static func modify(using closure: @escaping (URLSessionTask, URLRequest, HTTPURLResponse) -> URLRequest?) -> Redirector { + Redirector(behavior: .modify(closure)) + } +} diff --git a/Pods/Alamofire/Source/Request.swift b/Pods/Alamofire/Source/Request.swift new file mode 100644 index 0000000..a707933 --- /dev/null +++ b/Pods/Alamofire/Source/Request.swift @@ -0,0 +1,1912 @@ +// +// Request.swift +// +// Copyright (c) 2014-2020 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 + +/// `Request` is the common superclass of all Alamofire request types and provides common state, delegate, and callback +/// handling. +public class Request { + /// State of the `Request`, with managed transitions between states set when calling `resume()`, `suspend()`, or + /// `cancel()` on the `Request`. + public enum State { + /// Initial state of the `Request`. + case initialized + /// `State` set when `resume()` is called. Any tasks created for the `Request` will have `resume()` called on + /// them in this state. + case resumed + /// `State` set when `suspend()` is called. Any tasks created for the `Request` will have `suspend()` called on + /// them in this state. + case suspended + /// `State` set when `cancel()` is called. Any tasks created for the `Request` will have `cancel()` called on + /// them. Unlike `resumed` or `suspended`, once in the `cancelled` state, the `Request` can no longer transition + /// to any other state. + case cancelled + /// `State` set when all response serialization completion closures have been cleared on the `Request` and + /// enqueued on their respective queues. + case finished + + /// Determines whether `self` can be transitioned to the provided `State`. + func canTransitionTo(_ state: State) -> Bool { + switch (self, state) { + case (.initialized, _): + return true + case (_, .initialized), (.cancelled, _), (.finished, _): + return false + case (.resumed, .cancelled), (.suspended, .cancelled), (.resumed, .suspended), (.suspended, .resumed): + return true + case (.suspended, .suspended), (.resumed, .resumed): + return false + case (_, .finished): + return true + } + } + } + + // MARK: - Initial State + + /// `UUID` providing a unique identifier for the `Request`, used in the `Hashable` and `Equatable` conformances. + public let id: UUID + /// The serial queue for all internal async actions. + public let underlyingQueue: DispatchQueue + /// The queue used for all serialization actions. By default it's a serial queue that targets `underlyingQueue`. + public let serializationQueue: DispatchQueue + /// `EventMonitor` used for event callbacks. + public let eventMonitor: EventMonitor? + /// The `Request`'s interceptor. + public let interceptor: RequestInterceptor? + /// The `Request`'s delegate. + public private(set) weak var delegate: RequestDelegate? + + // MARK: - Mutable State + + /// Type encapsulating all mutable state that may need to be accessed from anything other than the `underlyingQueue`. + struct MutableState { + /// State of the `Request`. + var state: State = .initialized + /// `ProgressHandler` and `DispatchQueue` provided for upload progress callbacks. + var uploadProgressHandler: (handler: ProgressHandler, queue: DispatchQueue)? + /// `ProgressHandler` and `DispatchQueue` provided for download progress callbacks. + var downloadProgressHandler: (handler: ProgressHandler, queue: DispatchQueue)? + /// `RedirectHandler` provided for to handle request redirection. + var redirectHandler: RedirectHandler? + /// `CachedResponseHandler` provided to handle response caching. + var cachedResponseHandler: CachedResponseHandler? + /// Queue and closure called when the `Request` is able to create a cURL description of itself. + var cURLHandler: (queue: DispatchQueue, handler: (String) -> Void)? + /// Queue and closure called when the `Request` creates a `URLRequest`. + var urlRequestHandler: (queue: DispatchQueue, handler: (URLRequest) -> Void)? + /// Queue and closure called when the `Request` creates a `URLSessionTask`. + var urlSessionTaskHandler: (queue: DispatchQueue, handler: (URLSessionTask) -> Void)? + /// Response serialization closures that handle response parsing. + var responseSerializers: [() -> Void] = [] + /// Response serialization completion closures executed once all response serializers are complete. + var responseSerializerCompletions: [() -> Void] = [] + /// Whether response serializer processing is finished. + var responseSerializerProcessingFinished = false + /// `URLCredential` used for authentication challenges. + var credential: URLCredential? + /// All `URLRequest`s created by Alamofire on behalf of the `Request`. + var requests: [URLRequest] = [] + /// All `URLSessionTask`s created by Alamofire on behalf of the `Request`. + var tasks: [URLSessionTask] = [] + /// All `URLSessionTaskMetrics` values gathered by Alamofire on behalf of the `Request`. Should correspond + /// exactly the the `tasks` created. + var metrics: [URLSessionTaskMetrics] = [] + /// Number of times any retriers provided retried the `Request`. + var retryCount = 0 + /// Final `AFError` for the `Request`, whether from various internal Alamofire calls or as a result of a `task`. + var error: AFError? + /// Whether the instance has had `finish()` called and is running the serializers. Should be replaced with a + /// representation in the state machine in the future. + var isFinishing = false + /// Actions to run when requests are finished. Use for concurrency support. + var finishHandlers: [() -> Void] = [] + } + + /// Protected `MutableState` value that provides thread-safe access to state values. + @Protected + fileprivate var mutableState = MutableState() + + /// `State` of the `Request`. + public var state: State { $mutableState.state } + /// Returns whether `state` is `.initialized`. + public var isInitialized: Bool { state == .initialized } + /// Returns whether `state is `.resumed`. + public var isResumed: Bool { state == .resumed } + /// Returns whether `state` is `.suspended`. + public var isSuspended: Bool { state == .suspended } + /// Returns whether `state` is `.cancelled`. + public var isCancelled: Bool { state == .cancelled } + /// Returns whether `state` is `.finished`. + public var isFinished: Bool { state == .finished } + + // MARK: Progress + + /// Closure type executed when monitoring the upload or download progress of a request. + public typealias ProgressHandler = (Progress) -> Void + + /// `Progress` of the upload of the body of the executed `URLRequest`. Reset to `0` if the `Request` is retried. + public let uploadProgress = Progress(totalUnitCount: 0) + /// `Progress` of the download of any response data. Reset to `0` if the `Request` is retried. + public let downloadProgress = Progress(totalUnitCount: 0) + /// `ProgressHandler` called when `uploadProgress` is updated, on the provided `DispatchQueue`. + private var uploadProgressHandler: (handler: ProgressHandler, queue: DispatchQueue)? { + get { $mutableState.uploadProgressHandler } + set { $mutableState.uploadProgressHandler = newValue } + } + + /// `ProgressHandler` called when `downloadProgress` is updated, on the provided `DispatchQueue`. + fileprivate var downloadProgressHandler: (handler: ProgressHandler, queue: DispatchQueue)? { + get { $mutableState.downloadProgressHandler } + set { $mutableState.downloadProgressHandler = newValue } + } + + // MARK: Redirect Handling + + /// `RedirectHandler` set on the instance. + public private(set) var redirectHandler: RedirectHandler? { + get { $mutableState.redirectHandler } + set { $mutableState.redirectHandler = newValue } + } + + // MARK: Cached Response Handling + + /// `CachedResponseHandler` set on the instance. + public private(set) var cachedResponseHandler: CachedResponseHandler? { + get { $mutableState.cachedResponseHandler } + set { $mutableState.cachedResponseHandler = newValue } + } + + // MARK: URLCredential + + /// `URLCredential` used for authentication challenges. Created by calling one of the `authenticate` methods. + public private(set) var credential: URLCredential? { + get { $mutableState.credential } + set { $mutableState.credential = newValue } + } + + // MARK: Validators + + /// `Validator` callback closures that store the validation calls enqueued. + @Protected + fileprivate var validators: [() -> Void] = [] + + // MARK: URLRequests + + /// All `URLRequests` created on behalf of the `Request`, including original and adapted requests. + public var requests: [URLRequest] { $mutableState.requests } + /// First `URLRequest` created on behalf of the `Request`. May not be the first one actually executed. + public var firstRequest: URLRequest? { requests.first } + /// Last `URLRequest` created on behalf of the `Request`. + public var lastRequest: URLRequest? { requests.last } + /// Current `URLRequest` created on behalf of the `Request`. + public var request: URLRequest? { lastRequest } + + /// `URLRequest`s from all of the `URLSessionTask`s executed on behalf of the `Request`. May be different from + /// `requests` due to `URLSession` manipulation. + public var performedRequests: [URLRequest] { $mutableState.read { $0.tasks.compactMap(\.currentRequest) } } + + // MARK: HTTPURLResponse + + /// `HTTPURLResponse` received from the server, if any. If the `Request` was retried, this is the response of the + /// last `URLSessionTask`. + public var response: HTTPURLResponse? { lastTask?.response as? HTTPURLResponse } + + // MARK: Tasks + + /// All `URLSessionTask`s created on behalf of the `Request`. + public var tasks: [URLSessionTask] { $mutableState.tasks } + /// First `URLSessionTask` created on behalf of the `Request`. + public var firstTask: URLSessionTask? { tasks.first } + /// Last `URLSessionTask` created on behalf of the `Request`. + public var lastTask: URLSessionTask? { tasks.last } + /// Current `URLSessionTask` created on behalf of the `Request`. + public var task: URLSessionTask? { lastTask } + + // MARK: Metrics + + /// All `URLSessionTaskMetrics` gathered on behalf of the `Request`. Should correspond to the `tasks` created. + public var allMetrics: [URLSessionTaskMetrics] { $mutableState.metrics } + /// First `URLSessionTaskMetrics` gathered on behalf of the `Request`. + public var firstMetrics: URLSessionTaskMetrics? { allMetrics.first } + /// Last `URLSessionTaskMetrics` gathered on behalf of the `Request`. + public var lastMetrics: URLSessionTaskMetrics? { allMetrics.last } + /// Current `URLSessionTaskMetrics` gathered on behalf of the `Request`. + public var metrics: URLSessionTaskMetrics? { lastMetrics } + + // MARK: Retry Count + + /// Number of times the `Request` has been retried. + public var retryCount: Int { $mutableState.retryCount } + + // MARK: Error + + /// `Error` returned from Alamofire internally, from the network request directly, or any validators executed. + public fileprivate(set) var error: AFError? { + get { $mutableState.error } + set { $mutableState.error = newValue } + } + + /// Default initializer for the `Request` superclass. + /// + /// - Parameters: + /// - id: `UUID` used for the `Hashable` and `Equatable` implementations. `UUID()` by default. + /// - underlyingQueue: `DispatchQueue` on which all internal `Request` work is performed. + /// - serializationQueue: `DispatchQueue` on which all serialization work is performed. By default targets + /// `underlyingQueue`, but can be passed another queue from a `Session`. + /// - eventMonitor: `EventMonitor` called for event callbacks from internal `Request` actions. + /// - interceptor: `RequestInterceptor` used throughout the request lifecycle. + /// - delegate: `RequestDelegate` that provides an interface to actions not performed by the `Request`. + init(id: UUID = UUID(), + underlyingQueue: DispatchQueue, + serializationQueue: DispatchQueue, + eventMonitor: EventMonitor?, + interceptor: RequestInterceptor?, + delegate: RequestDelegate) { + self.id = id + self.underlyingQueue = underlyingQueue + self.serializationQueue = serializationQueue + self.eventMonitor = eventMonitor + self.interceptor = interceptor + self.delegate = delegate + } + + // MARK: - Internal Event API + + // All API must be called from underlyingQueue. + + /// Called when an initial `URLRequest` has been created on behalf of the instance. If a `RequestAdapter` is active, + /// the `URLRequest` will be adapted before being issued. + /// + /// - Parameter request: The `URLRequest` created. + func didCreateInitialURLRequest(_ request: URLRequest) { + dispatchPrecondition(condition: .onQueue(underlyingQueue)) + + $mutableState.write { $0.requests.append(request) } + + eventMonitor?.request(self, didCreateInitialURLRequest: request) + } + + /// Called when initial `URLRequest` creation has failed, typically through a `URLRequestConvertible`. + /// + /// - Note: Triggers retry. + /// + /// - Parameter error: `AFError` thrown from the failed creation. + func didFailToCreateURLRequest(with error: AFError) { + dispatchPrecondition(condition: .onQueue(underlyingQueue)) + + self.error = error + + eventMonitor?.request(self, didFailToCreateURLRequestWithError: error) + + callCURLHandlerIfNecessary() + + retryOrFinish(error: error) + } + + /// Called when a `RequestAdapter` has successfully adapted a `URLRequest`. + /// + /// - Parameters: + /// - initialRequest: The `URLRequest` that was adapted. + /// - adaptedRequest: The `URLRequest` returned by the `RequestAdapter`. + func didAdaptInitialRequest(_ initialRequest: URLRequest, to adaptedRequest: URLRequest) { + dispatchPrecondition(condition: .onQueue(underlyingQueue)) + + $mutableState.write { $0.requests.append(adaptedRequest) } + + eventMonitor?.request(self, didAdaptInitialRequest: initialRequest, to: adaptedRequest) + } + + /// Called when a `RequestAdapter` fails to adapt a `URLRequest`. + /// + /// - Note: Triggers retry. + /// + /// - Parameters: + /// - request: The `URLRequest` the adapter was called with. + /// - error: The `AFError` returned by the `RequestAdapter`. + func didFailToAdaptURLRequest(_ request: URLRequest, withError error: AFError) { + dispatchPrecondition(condition: .onQueue(underlyingQueue)) + + self.error = error + + eventMonitor?.request(self, didFailToAdaptURLRequest: request, withError: error) + + callCURLHandlerIfNecessary() + + retryOrFinish(error: error) + } + + /// Final `URLRequest` has been created for the instance. + /// + /// - Parameter request: The `URLRequest` created. + func didCreateURLRequest(_ request: URLRequest) { + dispatchPrecondition(condition: .onQueue(underlyingQueue)) + + $mutableState.read { state in + state.urlRequestHandler?.queue.async { state.urlRequestHandler?.handler(request) } + } + + eventMonitor?.request(self, didCreateURLRequest: request) + + callCURLHandlerIfNecessary() + } + + /// Asynchronously calls any stored `cURLHandler` and then removes it from `mutableState`. + private func callCURLHandlerIfNecessary() { + $mutableState.write { mutableState in + guard let cURLHandler = mutableState.cURLHandler else { return } + + cURLHandler.queue.async { cURLHandler.handler(self.cURLDescription()) } + + mutableState.cURLHandler = nil + } + } + + /// Called when a `URLSessionTask` is created on behalf of the instance. + /// + /// - Parameter task: The `URLSessionTask` created. + func didCreateTask(_ task: URLSessionTask) { + dispatchPrecondition(condition: .onQueue(underlyingQueue)) + + $mutableState.write { state in + state.tasks.append(task) + + guard let urlSessionTaskHandler = state.urlSessionTaskHandler else { return } + + urlSessionTaskHandler.queue.async { urlSessionTaskHandler.handler(task) } + } + + eventMonitor?.request(self, didCreateTask: task) + } + + /// Called when resumption is completed. + func didResume() { + dispatchPrecondition(condition: .onQueue(underlyingQueue)) + + eventMonitor?.requestDidResume(self) + } + + /// Called when a `URLSessionTask` is resumed on behalf of the instance. + /// + /// - Parameter task: The `URLSessionTask` resumed. + func didResumeTask(_ task: URLSessionTask) { + dispatchPrecondition(condition: .onQueue(underlyingQueue)) + + eventMonitor?.request(self, didResumeTask: task) + } + + /// Called when suspension is completed. + func didSuspend() { + dispatchPrecondition(condition: .onQueue(underlyingQueue)) + + eventMonitor?.requestDidSuspend(self) + } + + /// Called when a `URLSessionTask` is suspended on behalf of the instance. + /// + /// - Parameter task: The `URLSessionTask` suspended. + func didSuspendTask(_ task: URLSessionTask) { + dispatchPrecondition(condition: .onQueue(underlyingQueue)) + + eventMonitor?.request(self, didSuspendTask: task) + } + + /// Called when cancellation is completed, sets `error` to `AFError.explicitlyCancelled`. + func didCancel() { + dispatchPrecondition(condition: .onQueue(underlyingQueue)) + + error = error ?? AFError.explicitlyCancelled + + eventMonitor?.requestDidCancel(self) + } + + /// Called when a `URLSessionTask` is cancelled on behalf of the instance. + /// + /// - Parameter task: The `URLSessionTask` cancelled. + func didCancelTask(_ task: URLSessionTask) { + dispatchPrecondition(condition: .onQueue(underlyingQueue)) + + eventMonitor?.request(self, didCancelTask: task) + } + + /// Called when a `URLSessionTaskMetrics` value is gathered on behalf of the instance. + /// + /// - Parameter metrics: The `URLSessionTaskMetrics` gathered. + func didGatherMetrics(_ metrics: URLSessionTaskMetrics) { + dispatchPrecondition(condition: .onQueue(underlyingQueue)) + + $mutableState.write { $0.metrics.append(metrics) } + + eventMonitor?.request(self, didGatherMetrics: metrics) + } + + /// Called when a `URLSessionTask` fails before it is finished, typically during certificate pinning. + /// + /// - Parameters: + /// - task: The `URLSessionTask` which failed. + /// - error: The early failure `AFError`. + func didFailTask(_ task: URLSessionTask, earlyWithError error: AFError) { + dispatchPrecondition(condition: .onQueue(underlyingQueue)) + + self.error = error + + // Task will still complete, so didCompleteTask(_:with:) will handle retry. + eventMonitor?.request(self, didFailTask: task, earlyWithError: error) + } + + /// Called when a `URLSessionTask` completes. All tasks will eventually call this method. + /// + /// - Note: Response validation is synchronously triggered in this step. + /// + /// - Parameters: + /// - task: The `URLSessionTask` which completed. + /// - error: The `AFError` `task` may have completed with. If `error` has already been set on the instance, this + /// value is ignored. + func didCompleteTask(_ task: URLSessionTask, with error: AFError?) { + dispatchPrecondition(condition: .onQueue(underlyingQueue)) + + self.error = self.error ?? error + + validators.forEach { $0() } + + eventMonitor?.request(self, didCompleteTask: task, with: error) + + retryOrFinish(error: self.error) + } + + /// Called when the `RequestDelegate` is going to retry this `Request`. Calls `reset()`. + func prepareForRetry() { + dispatchPrecondition(condition: .onQueue(underlyingQueue)) + + $mutableState.write { $0.retryCount += 1 } + + reset() + + eventMonitor?.requestIsRetrying(self) + } + + /// Called to determine whether retry will be triggered for the particular error, or whether the instance should + /// call `finish()`. + /// + /// - Parameter error: The possible `AFError` which may trigger retry. + func retryOrFinish(error: AFError?) { + dispatchPrecondition(condition: .onQueue(underlyingQueue)) + + guard !isCancelled, let error = error, let delegate = delegate else { finish(); return } + + delegate.retryResult(for: self, dueTo: error) { retryResult in + switch retryResult { + case .doNotRetry: + self.finish() + case let .doNotRetryWithError(retryError): + self.finish(error: retryError.asAFError(orFailWith: "Received retryError was not already AFError")) + case .retry, .retryWithDelay: + delegate.retryRequest(self, withDelay: retryResult.delay) + } + } + } + + /// Finishes this `Request` and starts the response serializers. + /// + /// - Parameter error: The possible `Error` with which the instance will finish. + func finish(error: AFError? = nil) { + dispatchPrecondition(condition: .onQueue(underlyingQueue)) + + guard !$mutableState.isFinishing else { return } + + $mutableState.isFinishing = true + + if let error = error { self.error = error } + + // Start response handlers + processNextResponseSerializer() + + eventMonitor?.requestDidFinish(self) + } + + /// Appends the response serialization closure to the instance. + /// + /// - Note: This method will also `resume` the instance if `delegate.startImmediately` returns `true`. + /// + /// - Parameter closure: The closure containing the response serialization call. + func appendResponseSerializer(_ closure: @escaping () -> Void) { + $mutableState.write { mutableState in + mutableState.responseSerializers.append(closure) + + if mutableState.state == .finished { + mutableState.state = .resumed + } + + if mutableState.responseSerializerProcessingFinished { + underlyingQueue.async { self.processNextResponseSerializer() } + } + + if mutableState.state.canTransitionTo(.resumed) { + underlyingQueue.async { if self.delegate?.startImmediately == true { self.resume() } } + } + } + } + + /// Returns the next response serializer closure to execute if there's one left. + /// + /// - Returns: The next response serialization closure, if there is one. + func nextResponseSerializer() -> (() -> Void)? { + var responseSerializer: (() -> Void)? + + $mutableState.write { mutableState in + let responseSerializerIndex = mutableState.responseSerializerCompletions.count + + if responseSerializerIndex < mutableState.responseSerializers.count { + responseSerializer = mutableState.responseSerializers[responseSerializerIndex] + } + } + + return responseSerializer + } + + /// Processes the next response serializer and calls all completions if response serialization is complete. + func processNextResponseSerializer() { + guard let responseSerializer = nextResponseSerializer() else { + // Execute all response serializer completions and clear them + var completions: [() -> Void] = [] + + $mutableState.write { mutableState in + completions = mutableState.responseSerializerCompletions + + // Clear out all response serializers and response serializer completions in mutable state since the + // request is complete. It's important to do this prior to calling the completion closures in case + // the completions call back into the request triggering a re-processing of the response serializers. + // An example of how this can happen is by calling cancel inside a response completion closure. + mutableState.responseSerializers.removeAll() + mutableState.responseSerializerCompletions.removeAll() + + if mutableState.state.canTransitionTo(.finished) { + mutableState.state = .finished + } + + mutableState.responseSerializerProcessingFinished = true + mutableState.isFinishing = false + } + + completions.forEach { $0() } + + // Cleanup the request + cleanup() + + return + } + + serializationQueue.async { responseSerializer() } + } + + /// Notifies the `Request` that the response serializer is complete. + /// + /// - Parameter completion: The completion handler provided with the response serializer, called when all serializers + /// are complete. + func responseSerializerDidComplete(completion: @escaping () -> Void) { + $mutableState.write { $0.responseSerializerCompletions.append(completion) } + processNextResponseSerializer() + } + + /// Resets all task and response serializer related state for retry. + func reset() { + error = nil + + uploadProgress.totalUnitCount = 0 + uploadProgress.completedUnitCount = 0 + downloadProgress.totalUnitCount = 0 + downloadProgress.completedUnitCount = 0 + + $mutableState.write { state in + state.isFinishing = false + state.responseSerializerCompletions = [] + } + } + + /// Called when updating the upload progress. + /// + /// - Parameters: + /// - totalBytesSent: Total bytes sent so far. + /// - totalBytesExpectedToSend: Total bytes expected to send. + func updateUploadProgress(totalBytesSent: Int64, totalBytesExpectedToSend: Int64) { + uploadProgress.totalUnitCount = totalBytesExpectedToSend + uploadProgress.completedUnitCount = totalBytesSent + + uploadProgressHandler?.queue.async { self.uploadProgressHandler?.handler(self.uploadProgress) } + } + + /// Perform a closure on the current `state` while locked. + /// + /// - Parameter perform: The closure to perform. + func withState(perform: (State) -> Void) { + $mutableState.withState(perform: perform) + } + + // MARK: Task Creation + + /// Called when creating a `URLSessionTask` for this `Request`. Subclasses must override. + /// + /// - Parameters: + /// - request: `URLRequest` to use to create the `URLSessionTask`. + /// - session: `URLSession` which creates the `URLSessionTask`. + /// + /// - Returns: The `URLSessionTask` created. + func task(for request: URLRequest, using session: URLSession) -> URLSessionTask { + fatalError("Subclasses must override.") + } + + // MARK: - Public API + + // These APIs are callable from any queue. + + // MARK: State + + /// Cancels the instance. Once cancelled, a `Request` can no longer be resumed or suspended. + /// + /// - Returns: The instance. + @discardableResult + public func cancel() -> Self { + $mutableState.write { mutableState in + guard mutableState.state.canTransitionTo(.cancelled) else { return } + + mutableState.state = .cancelled + + underlyingQueue.async { self.didCancel() } + + guard let task = mutableState.tasks.last, task.state != .completed else { + underlyingQueue.async { self.finish() } + return + } + + // Resume to ensure metrics are gathered. + task.resume() + task.cancel() + underlyingQueue.async { self.didCancelTask(task) } + } + + return self + } + + /// Suspends the instance. + /// + /// - Returns: The instance. + @discardableResult + public func suspend() -> Self { + $mutableState.write { mutableState in + guard mutableState.state.canTransitionTo(.suspended) else { return } + + mutableState.state = .suspended + + underlyingQueue.async { self.didSuspend() } + + guard let task = mutableState.tasks.last, task.state != .completed else { return } + + task.suspend() + underlyingQueue.async { self.didSuspendTask(task) } + } + + return self + } + + /// Resumes the instance. + /// + /// - Returns: The instance. + @discardableResult + public func resume() -> Self { + $mutableState.write { mutableState in + guard mutableState.state.canTransitionTo(.resumed) else { return } + + mutableState.state = .resumed + + underlyingQueue.async { self.didResume() } + + guard let task = mutableState.tasks.last, task.state != .completed else { return } + + task.resume() + underlyingQueue.async { self.didResumeTask(task) } + } + + return self + } + + // MARK: - Closure API + + /// Associates a credential using the provided values with the instance. + /// + /// - Parameters: + /// - username: The username. + /// - password: The password. + /// - persistence: The `URLCredential.Persistence` for the created `URLCredential`. `.forSession` by default. + /// + /// - Returns: The instance. + @discardableResult + public func authenticate(username: String, password: String, persistence: URLCredential.Persistence = .forSession) -> Self { + let credential = URLCredential(user: username, password: password, persistence: persistence) + + return authenticate(with: credential) + } + + /// Associates the provided credential with the instance. + /// + /// - Parameter credential: The `URLCredential`. + /// + /// - Returns: The instance. + @discardableResult + public func authenticate(with credential: URLCredential) -> Self { + $mutableState.credential = credential + + return self + } + + /// Sets a closure to be called periodically during the lifecycle of the instance as data is read from the server. + /// + /// - Note: Only the last closure provided is used. + /// + /// - Parameters: + /// - queue: The `DispatchQueue` to execute the closure on. `.main` by default. + /// - closure: The closure to be executed periodically as data is read from the server. + /// + /// - Returns: The instance. + @discardableResult + public func downloadProgress(queue: DispatchQueue = .main, closure: @escaping ProgressHandler) -> Self { + $mutableState.downloadProgressHandler = (handler: closure, queue: queue) + + return self + } + + /// Sets a closure to be called periodically during the lifecycle of the instance as data is sent to the server. + /// + /// - Note: Only the last closure provided is used. + /// + /// - Parameters: + /// - queue: The `DispatchQueue` to execute the closure on. `.main` by default. + /// - closure: The closure to be executed periodically as data is sent to the server. + /// + /// - Returns: The instance. + @discardableResult + public func uploadProgress(queue: DispatchQueue = .main, closure: @escaping ProgressHandler) -> Self { + $mutableState.uploadProgressHandler = (handler: closure, queue: queue) + + return self + } + + // MARK: Redirects + + /// Sets the redirect handler for the instance which will be used if a redirect response is encountered. + /// + /// - Note: Attempting to set the redirect handler more than once is a logic error and will crash. + /// + /// - Parameter handler: The `RedirectHandler`. + /// + /// - Returns: The instance. + @discardableResult + public func redirect(using handler: RedirectHandler) -> Self { + $mutableState.write { mutableState in + precondition(mutableState.redirectHandler == nil, "Redirect handler has already been set.") + mutableState.redirectHandler = handler + } + + return self + } + + // MARK: Cached Responses + + /// Sets the cached response handler for the `Request` which will be used when attempting to cache a response. + /// + /// - Note: Attempting to set the cache handler more than once is a logic error and will crash. + /// + /// - Parameter handler: The `CachedResponseHandler`. + /// + /// - Returns: The instance. + @discardableResult + public func cacheResponse(using handler: CachedResponseHandler) -> Self { + $mutableState.write { mutableState in + precondition(mutableState.cachedResponseHandler == nil, "Cached response handler has already been set.") + mutableState.cachedResponseHandler = handler + } + + return self + } + + // MARK: - Lifetime APIs + + /// Sets a handler to be called when the cURL description of the request is available. + /// + /// - Note: When waiting for a `Request`'s `URLRequest` to be created, only the last `handler` will be called. + /// + /// - Parameters: + /// - queue: `DispatchQueue` on which `handler` will be called. + /// - handler: Closure to be called when the cURL description is available. + /// + /// - Returns: The instance. + @discardableResult + public func cURLDescription(on queue: DispatchQueue, calling handler: @escaping (String) -> Void) -> Self { + $mutableState.write { mutableState in + if mutableState.requests.last != nil { + queue.async { handler(self.cURLDescription()) } + } else { + mutableState.cURLHandler = (queue, handler) + } + } + + return self + } + + /// Sets a handler to be called when the cURL description of the request is available. + /// + /// - Note: When waiting for a `Request`'s `URLRequest` to be created, only the last `handler` will be called. + /// + /// - Parameter handler: Closure to be called when the cURL description is available. Called on the instance's + /// `underlyingQueue` by default. + /// + /// - Returns: The instance. + @discardableResult + public func cURLDescription(calling handler: @escaping (String) -> Void) -> Self { + $mutableState.write { mutableState in + if mutableState.requests.last != nil { + underlyingQueue.async { handler(self.cURLDescription()) } + } else { + mutableState.cURLHandler = (underlyingQueue, handler) + } + } + + return self + } + + /// Sets a closure to called whenever Alamofire creates a `URLRequest` for this instance. + /// + /// - Note: This closure will be called multiple times if the instance adapts incoming `URLRequest`s or is retried. + /// + /// - Parameters: + /// - queue: `DispatchQueue` on which `handler` will be called. `.main` by default. + /// - handler: Closure to be called when a `URLRequest` is available. + /// + /// - Returns: The instance. + @discardableResult + public func onURLRequestCreation(on queue: DispatchQueue = .main, perform handler: @escaping (URLRequest) -> Void) -> Self { + $mutableState.write { state in + if let request = state.requests.last { + queue.async { handler(request) } + } + + state.urlRequestHandler = (queue, handler) + } + + return self + } + + /// Sets a closure to be called whenever the instance creates a `URLSessionTask`. + /// + /// - Note: This API should only be used to provide `URLSessionTask`s to existing API, like `NSFileProvider`. It + /// **SHOULD NOT** be used to interact with tasks directly, as that may be break Alamofire features. + /// Additionally, this closure may be called multiple times if the instance is retried. + /// + /// - Parameters: + /// - queue: `DispatchQueue` on which `handler` will be called. `.main` by default. + /// - handler: Closure to be called when the `URLSessionTask` is available. + /// + /// - Returns: The instance. + @discardableResult + public func onURLSessionTaskCreation(on queue: DispatchQueue = .main, perform handler: @escaping (URLSessionTask) -> Void) -> Self { + $mutableState.write { state in + if let task = state.tasks.last { + queue.async { handler(task) } + } + + state.urlSessionTaskHandler = (queue, handler) + } + + return self + } + + // MARK: Cleanup + + /// Adds a `finishHandler` closure to be called when the request completes. + /// + /// - Parameter closure: Closure to be called when the request finishes. + func onFinish(perform finishHandler: @escaping () -> Void) { + guard !isFinished else { finishHandler(); return } + + $mutableState.write { state in + state.finishHandlers.append(finishHandler) + } + } + + /// Final cleanup step executed when the instance finishes response serialization. + func cleanup() { + delegate?.cleanup(after: self) + let handlers = $mutableState.finishHandlers + handlers.forEach { $0() } + $mutableState.write { state in + state.finishHandlers.removeAll() + } + } +} + +// MARK: - Protocol Conformances + +extension Request: Equatable { + public static func ==(lhs: Request, rhs: Request) -> Bool { + lhs.id == rhs.id + } +} + +extension Request: Hashable { + public func hash(into hasher: inout Hasher) { + hasher.combine(id) + } +} + +extension Request: CustomStringConvertible { + /// A textual representation of this instance, including the `HTTPMethod` and `URL` if the `URLRequest` has been + /// created, as well as the response status code, if a response has been received. + public var description: String { + guard let request = performedRequests.last ?? lastRequest, + let url = request.url, + let method = request.httpMethod else { return "No request created yet." } + + let requestDescription = "\(method) \(url.absoluteString)" + + return response.map { "\(requestDescription) (\($0.statusCode))" } ?? requestDescription + } +} + +extension Request { + /// cURL representation of the instance. + /// + /// - Returns: The cURL equivalent of the instance. + public func cURLDescription() -> String { + guard + let request = lastRequest, + let url = request.url, + let host = url.host, + let method = request.httpMethod else { return "$ curl command could not be created" } + + var components = ["$ curl -v"] + + components.append("-X \(method)") + + if let credentialStorage = delegate?.sessionConfiguration.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 = credential, let user = credential.user, let password = credential.password { + components.append("-u \(user):\(password)") + } + } + } + + if let configuration = delegate?.sessionConfiguration, configuration.httpShouldSetCookies { + if + let cookieStorage = configuration.httpCookieStorage, + let cookies = cookieStorage.cookies(for: url), !cookies.isEmpty { + let allCookies = cookies.map { "\($0.name)=\($0.value)" }.joined(separator: ";") + + components.append("-b \"\(allCookies)\"") + } + } + + var headers = HTTPHeaders() + + if let sessionHeaders = delegate?.sessionConfiguration.headers { + for header in sessionHeaders where header.name != "Cookie" { + headers[header.name] = header.value + } + } + + for header in request.headers where header.name != "Cookie" { + headers[header.name] = header.value + } + + for header in headers { + let escapedValue = header.value.replacingOccurrences(of: "\"", with: "\\\"") + components.append("-H \"\(header.name): \(escapedValue)\"") + } + + if let httpBodyData = request.httpBody { + let httpBody = String(decoding: httpBodyData, as: UTF8.self) + var escapedBody = httpBody.replacingOccurrences(of: "\\\"", with: "\\\\\"") + escapedBody = escapedBody.replacingOccurrences(of: "\"", with: "\\\"") + + components.append("-d \"\(escapedBody)\"") + } + + components.append("\"\(url.absoluteString)\"") + + return components.joined(separator: " \\\n\t") + } +} + +/// Protocol abstraction for `Request`'s communication back to the `SessionDelegate`. +public protocol RequestDelegate: AnyObject { + /// `URLSessionConfiguration` used to create the underlying `URLSessionTask`s. + var sessionConfiguration: URLSessionConfiguration { get } + + /// Determines whether the `Request` should automatically call `resume()` when adding the first response handler. + var startImmediately: Bool { get } + + /// Notifies the delegate the `Request` has reached a point where it needs cleanup. + /// + /// - Parameter request: The `Request` to cleanup after. + func cleanup(after request: Request) + + /// Asynchronously ask the delegate whether a `Request` will be retried. + /// + /// - Parameters: + /// - request: `Request` which failed. + /// - error: `Error` which produced the failure. + /// - completion: Closure taking the `RetryResult` for evaluation. + func retryResult(for request: Request, dueTo error: AFError, completion: @escaping (RetryResult) -> Void) + + /// Asynchronously retry the `Request`. + /// + /// - Parameters: + /// - request: `Request` which will be retried. + /// - timeDelay: `TimeInterval` after which the retry will be triggered. + func retryRequest(_ request: Request, withDelay timeDelay: TimeInterval?) +} + +// MARK: - Subclasses + +// MARK: - DataRequest + +/// `Request` subclass which handles in-memory `Data` download using `URLSessionDataTask`. +public class DataRequest: Request { + /// `URLRequestConvertible` value used to create `URLRequest`s for this instance. + public let convertible: URLRequestConvertible + /// `Data` read from the server so far. + public var data: Data? { mutableData } + + /// Protected storage for the `Data` read by the instance. + @Protected + private var mutableData: Data? = nil + + /// Creates a `DataRequest` using the provided parameters. + /// + /// - Parameters: + /// - id: `UUID` used for the `Hashable` and `Equatable` implementations. `UUID()` by default. + /// - convertible: `URLRequestConvertible` value used to create `URLRequest`s for this instance. + /// - underlyingQueue: `DispatchQueue` on which all internal `Request` work is performed. + /// - serializationQueue: `DispatchQueue` on which all serialization work is performed. By default targets + /// `underlyingQueue`, but can be passed another queue from a `Session`. + /// - eventMonitor: `EventMonitor` called for event callbacks from internal `Request` actions. + /// - interceptor: `RequestInterceptor` used throughout the request lifecycle. + /// - delegate: `RequestDelegate` that provides an interface to actions not performed by the `Request`. + init(id: UUID = UUID(), + convertible: URLRequestConvertible, + underlyingQueue: DispatchQueue, + serializationQueue: DispatchQueue, + eventMonitor: EventMonitor?, + interceptor: RequestInterceptor?, + delegate: RequestDelegate) { + self.convertible = convertible + + super.init(id: id, + underlyingQueue: underlyingQueue, + serializationQueue: serializationQueue, + eventMonitor: eventMonitor, + interceptor: interceptor, + delegate: delegate) + } + + override func reset() { + super.reset() + + mutableData = nil + } + + /// Called when `Data` is received by this instance. + /// + /// - Note: Also calls `updateDownloadProgress`. + /// + /// - Parameter data: The `Data` received. + func didReceive(data: Data) { + if self.data == nil { + mutableData = data + } else { + $mutableData.write { $0?.append(data) } + } + + updateDownloadProgress() + } + + override func task(for request: URLRequest, using session: URLSession) -> URLSessionTask { + let copiedRequest = request + return session.dataTask(with: copiedRequest) + } + + /// Called to update the `downloadProgress` of the instance. + func updateDownloadProgress() { + let totalBytesReceived = Int64(data?.count ?? 0) + let totalBytesExpected = task?.response?.expectedContentLength ?? NSURLSessionTransferSizeUnknown + + downloadProgress.totalUnitCount = totalBytesExpected + downloadProgress.completedUnitCount = totalBytesReceived + + downloadProgressHandler?.queue.async { self.downloadProgressHandler?.handler(self.downloadProgress) } + } + + /// Validates the request, using the specified closure. + /// + /// - Note: If validation fails, subsequent calls to response handlers will have an associated error. + /// + /// - Parameter validation: `Validation` closure used to validate the response. + /// + /// - Returns: The instance. + @discardableResult + public func validate(_ validation: @escaping Validation) -> Self { + let validator: () -> Void = { [unowned self] in + guard error == nil, let response = response else { return } + + let result = validation(request, response, data) + + if case let .failure(error) = result { self.error = error.asAFError(or: .responseValidationFailed(reason: .customValidationFailed(error: error))) } + + eventMonitor?.request(self, + didValidateRequest: request, + response: response, + data: data, + withResult: result) + } + + $validators.write { $0.append(validator) } + + return self + } +} + +// MARK: - DataStreamRequest + +/// `Request` subclass which streams HTTP response `Data` through a `Handler` closure. +public final class DataStreamRequest: Request { + /// Closure type handling `DataStreamRequest.Stream` values. + public typealias Handler = (Stream) throws -> Void + + /// Type encapsulating an `Event` as it flows through the stream, as well as a `CancellationToken` which can be used + /// to stop the stream at any time. + public struct Stream { + /// Latest `Event` from the stream. + public let event: Event + /// Token used to cancel the stream. + public let token: CancellationToken + + /// Cancel the ongoing stream by canceling the underlying `DataStreamRequest`. + public func cancel() { + token.cancel() + } + } + + /// Type representing an event flowing through the stream. Contains either the `Result` of processing streamed + /// `Data` or the completion of the stream. + public enum Event { + /// Output produced every time the instance receives additional `Data`. The associated value contains the + /// `Result` of processing the incoming `Data`. + case stream(Result) + /// Output produced when the instance has completed, whether due to stream end, cancellation, or an error. + /// Associated `Completion` value contains the final state. + case complete(Completion) + } + + /// Value containing the state of a `DataStreamRequest` when the stream was completed. + public struct Completion { + /// Last `URLRequest` issued by the instance. + public let request: URLRequest? + /// Last `HTTPURLResponse` received by the instance. + public let response: HTTPURLResponse? + /// Last `URLSessionTaskMetrics` produced for the instance. + public let metrics: URLSessionTaskMetrics? + /// `AFError` produced for the instance, if any. + public let error: AFError? + } + + /// Type used to cancel an ongoing stream. + public struct CancellationToken { + weak var request: DataStreamRequest? + + init(_ request: DataStreamRequest) { + self.request = request + } + + /// Cancel the ongoing stream by canceling the underlying `DataStreamRequest`. + public func cancel() { + request?.cancel() + } + } + + /// `URLRequestConvertible` value used to create `URLRequest`s for this instance. + public let convertible: URLRequestConvertible + /// Whether or not the instance will be cancelled if stream parsing encounters an error. + public let automaticallyCancelOnStreamError: Bool + + /// Internal mutable state specific to this type. + struct StreamMutableState { + /// `OutputStream` bound to the `InputStream` produced by `asInputStream`, if it has been called. + var outputStream: OutputStream? + /// Stream closures called as `Data` is received. + var streams: [(_ data: Data) -> Void] = [] + /// Number of currently executing streams. Used to ensure completions are only fired after all streams are + /// enqueued. + var numberOfExecutingStreams = 0 + /// Completion calls enqueued while streams are still executing. + var enqueuedCompletionEvents: [() -> Void] = [] + } + + @Protected + var streamMutableState = StreamMutableState() + + /// Creates a `DataStreamRequest` using the provided parameters. + /// + /// - Parameters: + /// - id: `UUID` used for the `Hashable` and `Equatable` implementations. `UUID()` + /// by default. + /// - convertible: `URLRequestConvertible` value used to create `URLRequest`s for this + /// instance. + /// - automaticallyCancelOnStreamError: `Bool` indicating whether the instance will be cancelled when an `Error` + /// is thrown while serializing stream `Data`. + /// - underlyingQueue: `DispatchQueue` on which all internal `Request` work is performed. + /// - serializationQueue: `DispatchQueue` on which all serialization work is performed. By default + /// targets + /// `underlyingQueue`, but can be passed another queue from a `Session`. + /// - eventMonitor: `EventMonitor` called for event callbacks from internal `Request` actions. + /// - interceptor: `RequestInterceptor` used throughout the request lifecycle. + /// - delegate: `RequestDelegate` that provides an interface to actions not performed by + /// the `Request`. + init(id: UUID = UUID(), + convertible: URLRequestConvertible, + automaticallyCancelOnStreamError: Bool, + underlyingQueue: DispatchQueue, + serializationQueue: DispatchQueue, + eventMonitor: EventMonitor?, + interceptor: RequestInterceptor?, + delegate: RequestDelegate) { + self.convertible = convertible + self.automaticallyCancelOnStreamError = automaticallyCancelOnStreamError + + super.init(id: id, + underlyingQueue: underlyingQueue, + serializationQueue: serializationQueue, + eventMonitor: eventMonitor, + interceptor: interceptor, + delegate: delegate) + } + + override func task(for request: URLRequest, using session: URLSession) -> URLSessionTask { + let copiedRequest = request + return session.dataTask(with: copiedRequest) + } + + override func finish(error: AFError? = nil) { + $streamMutableState.write { state in + state.outputStream?.close() + } + + super.finish(error: error) + } + + func didReceive(data: Data) { + $streamMutableState.write { state in + #if !(os(Linux) || os(Windows)) + if let stream = state.outputStream { + underlyingQueue.async { + var bytes = Array(data) + stream.write(&bytes, maxLength: bytes.count) + } + } + #endif + state.numberOfExecutingStreams += state.streams.count + let localState = state + underlyingQueue.async { localState.streams.forEach { $0(data) } } + } + } + + /// Validates the `URLRequest` and `HTTPURLResponse` received for the instance using the provided `Validation` closure. + /// + /// - Parameter validation: `Validation` closure used to validate the request and response. + /// + /// - Returns: The `DataStreamRequest`. + @discardableResult + public func validate(_ validation: @escaping Validation) -> Self { + let validator: () -> Void = { [unowned self] in + guard error == nil, let response = response else { return } + + let result = validation(request, response) + + if case let .failure(error) = result { + self.error = error.asAFError(or: .responseValidationFailed(reason: .customValidationFailed(error: error))) + } + + eventMonitor?.request(self, + didValidateRequest: request, + response: response, + withResult: result) + } + + $validators.write { $0.append(validator) } + + return self + } + + #if !(os(Linux) || os(Windows)) + /// Produces an `InputStream` that receives the `Data` received by the instance. + /// + /// - Note: The `InputStream` produced by this method must have `open()` called before being able to read `Data`. + /// Additionally, this method will automatically call `resume()` on the instance, regardless of whether or + /// not the creating session has `startRequestsImmediately` set to `true`. + /// + /// - Parameter bufferSize: Size, in bytes, of the buffer between the `OutputStream` and `InputStream`. + /// + /// - Returns: The `InputStream` bound to the internal `OutboundStream`. + public func asInputStream(bufferSize: Int = 1024) -> InputStream? { + defer { resume() } + + var inputStream: InputStream? + $streamMutableState.write { state in + Foundation.Stream.getBoundStreams(withBufferSize: bufferSize, + inputStream: &inputStream, + outputStream: &state.outputStream) + state.outputStream?.open() + } + + return inputStream + } + #endif + + func capturingError(from closure: () throws -> Void) { + do { + try closure() + } catch { + self.error = error.asAFError(or: .responseSerializationFailed(reason: .customSerializationFailed(error: error))) + cancel() + } + } + + func appendStreamCompletion(on queue: DispatchQueue, + stream: @escaping Handler) { + appendResponseSerializer { + self.underlyingQueue.async { + self.responseSerializerDidComplete { + self.$streamMutableState.write { state in + guard state.numberOfExecutingStreams == 0 else { + state.enqueuedCompletionEvents.append { + self.enqueueCompletion(on: queue, stream: stream) + } + + return + } + + self.enqueueCompletion(on: queue, stream: stream) + } + } + } + } + } + + func enqueueCompletion(on queue: DispatchQueue, + stream: @escaping Handler) { + queue.async { + do { + let completion = Completion(request: self.request, + response: self.response, + metrics: self.metrics, + error: self.error) + try stream(.init(event: .complete(completion), token: .init(self))) + } catch { + // Ignore error, as errors on Completion can't be handled anyway. + } + } + } +} + +extension DataStreamRequest.Stream { + /// Incoming `Result` values from `Event.stream`. + public var result: Result? { + guard case let .stream(result) = event else { return nil } + + return result + } + + /// `Success` value of the instance, if any. + public var value: Success? { + guard case let .success(value) = result else { return nil } + + return value + } + + /// `Failure` value of the instance, if any. + public var error: Failure? { + guard case let .failure(error) = result else { return nil } + + return error + } + + /// `Completion` value of the instance, if any. + public var completion: DataStreamRequest.Completion? { + guard case let .complete(completion) = event else { return nil } + + return completion + } +} + +// MARK: - DownloadRequest + +/// `Request` subclass which downloads `Data` to a file on disk using `URLSessionDownloadTask`. +public class DownloadRequest: Request { + /// A set of options to be executed prior to moving a downloaded file from the temporary `URL` to the destination + /// `URL`. + public struct Options: OptionSet { + /// Specifies that intermediate directories for the destination URL should be created. + public static let createIntermediateDirectories = Options(rawValue: 1 << 0) + /// Specifies that any previous file at the destination `URL` should be removed. + public static let removePreviousFile = Options(rawValue: 1 << 1) + + public let rawValue: Int + + public init(rawValue: Int) { + self.rawValue = rawValue + } + } + + // MARK: Destination + + /// A closure executed once a `DownloadRequest` 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 `HTTPURLResponse`, and returns two values: the file URL where the temporary file should be moved and + /// the options defining how the file should be moved. + /// + /// - Note: Downloads from a local `file://` `URL`s do not use the `Destination` closure, as those downloads do not + /// return an `HTTPURLResponse`. Instead the file is merely moved within the temporary directory. + public typealias Destination = (_ temporaryURL: URL, + _ response: HTTPURLResponse) -> (destinationURL: URL, options: Options) + + /// 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. + /// + /// - Parameters: + /// - directory: The search path directory. `.documentDirectory` by default. + /// - domain: The search path domain mask. `.userDomainMask` by default. + /// - options: `DownloadRequest.Options` used when moving the downloaded file to its destination. None by + /// default. + /// - Returns: The `Destination` closure. + public class func suggestedDownloadDestination(for directory: FileManager.SearchPathDirectory = .documentDirectory, + in domain: FileManager.SearchPathDomainMask = .userDomainMask, + options: Options = []) -> Destination { + { temporaryURL, response in + let directoryURLs = FileManager.default.urls(for: directory, in: domain) + let url = directoryURLs.first?.appendingPathComponent(response.suggestedFilename!) ?? temporaryURL + + return (url, options) + } + } + + /// Default `Destination` used by Alamofire to ensure all downloads persist. This `Destination` prepends + /// `Alamofire_` to the automatically generated download name and moves it within the temporary directory. Files + /// with this destination must be additionally moved if they should survive the system reclamation of temporary + /// space. + static let defaultDestination: Destination = { url, _ in + (defaultDestinationURL(url), []) + } + + /// Default `URL` creation closure. Creates a `URL` in the temporary directory with `Alamofire_` prepended to the + /// provided file name. + static let defaultDestinationURL: (URL) -> URL = { url in + let filename = "Alamofire_\(url.lastPathComponent)" + let destination = url.deletingLastPathComponent().appendingPathComponent(filename) + + return destination + } + + // MARK: Downloadable + + /// Type describing the source used to create the underlying `URLSessionDownloadTask`. + public enum Downloadable { + /// Download should be started from the `URLRequest` produced by the associated `URLRequestConvertible` value. + case request(URLRequestConvertible) + /// Download should be started from the associated resume `Data` value. + case resumeData(Data) + } + + // MARK: Mutable State + + /// Type containing all mutable state for `DownloadRequest` instances. + private struct DownloadRequestMutableState { + /// Possible resume `Data` produced when cancelling the instance. + var resumeData: Data? + /// `URL` to which `Data` is being downloaded. + var fileURL: URL? + } + + /// Protected mutable state specific to `DownloadRequest`. + @Protected + private var mutableDownloadState = DownloadRequestMutableState() + + /// If the download is resumable and is eventually cancelled or fails, this value may be used to resume the download + /// using the `download(resumingWith data:)` API. + /// + /// - Note: For more information about `resumeData`, see [Apple's documentation](https://developer.apple.com/documentation/foundation/urlsessiondownloadtask/1411634-cancel). + public var resumeData: Data? { + #if !(os(Linux) || os(Windows)) + return $mutableDownloadState.resumeData ?? error?.downloadResumeData + #else + return $mutableDownloadState.resumeData + #endif + } + + /// If the download is successful, the `URL` where the file was downloaded. + public var fileURL: URL? { $mutableDownloadState.fileURL } + + // MARK: Initial State + + /// `Downloadable` value used for this instance. + public let downloadable: Downloadable + /// The `Destination` to which the downloaded file is moved. + let destination: Destination + + /// Creates a `DownloadRequest` using the provided parameters. + /// + /// - Parameters: + /// - id: `UUID` used for the `Hashable` and `Equatable` implementations. `UUID()` by default. + /// - downloadable: `Downloadable` value used to create `URLSessionDownloadTasks` for the instance. + /// - underlyingQueue: `DispatchQueue` on which all internal `Request` work is performed. + /// - serializationQueue: `DispatchQueue` on which all serialization work is performed. By default targets + /// `underlyingQueue`, but can be passed another queue from a `Session`. + /// - eventMonitor: `EventMonitor` called for event callbacks from internal `Request` actions. + /// - interceptor: `RequestInterceptor` used throughout the request lifecycle. + /// - delegate: `RequestDelegate` that provides an interface to actions not performed by the `Request` + /// - destination: `Destination` closure used to move the downloaded file to its final location. + init(id: UUID = UUID(), + downloadable: Downloadable, + underlyingQueue: DispatchQueue, + serializationQueue: DispatchQueue, + eventMonitor: EventMonitor?, + interceptor: RequestInterceptor?, + delegate: RequestDelegate, + destination: @escaping Destination) { + self.downloadable = downloadable + self.destination = destination + + super.init(id: id, + underlyingQueue: underlyingQueue, + serializationQueue: serializationQueue, + eventMonitor: eventMonitor, + interceptor: interceptor, + delegate: delegate) + } + + override func reset() { + super.reset() + + $mutableDownloadState.write { + $0.resumeData = nil + $0.fileURL = nil + } + } + + /// Called when a download has finished. + /// + /// - Parameters: + /// - task: `URLSessionTask` that finished the download. + /// - result: `Result` of the automatic move to `destination`. + func didFinishDownloading(using task: URLSessionTask, with result: Result) { + eventMonitor?.request(self, didFinishDownloadingUsing: task, with: result) + + switch result { + case let .success(url): $mutableDownloadState.fileURL = url + case let .failure(error): self.error = error + } + } + + /// Updates the `downloadProgress` using the provided values. + /// + /// - Parameters: + /// - bytesWritten: Total bytes written so far. + /// - totalBytesExpectedToWrite: Total bytes expected to write. + func updateDownloadProgress(bytesWritten: Int64, totalBytesExpectedToWrite: Int64) { + downloadProgress.totalUnitCount = totalBytesExpectedToWrite + downloadProgress.completedUnitCount += bytesWritten + + downloadProgressHandler?.queue.async { self.downloadProgressHandler?.handler(self.downloadProgress) } + } + + override func task(for request: URLRequest, using session: URLSession) -> URLSessionTask { + session.downloadTask(with: request) + } + + /// Creates a `URLSessionTask` from the provided resume data. + /// + /// - Parameters: + /// - data: `Data` used to resume the download. + /// - session: `URLSession` used to create the `URLSessionTask`. + /// + /// - Returns: The `URLSessionTask` created. + public func task(forResumeData data: Data, using session: URLSession) -> URLSessionTask { + session.downloadTask(withResumeData: data) + } + + /// Cancels the instance. Once cancelled, a `DownloadRequest` can no longer be resumed or suspended. + /// + /// - Note: This method will NOT produce resume data. If you wish to cancel and produce resume data, use + /// `cancel(producingResumeData:)` or `cancel(byProducingResumeData:)`. + /// + /// - Returns: The instance. + @discardableResult + override public func cancel() -> Self { + cancel(producingResumeData: false) + } + + /// Cancels the instance, optionally producing resume data. Once cancelled, a `DownloadRequest` can no longer be + /// resumed or suspended. + /// + /// - Note: If `producingResumeData` is `true`, the `resumeData` property will be populated with any resume data, if + /// available. + /// + /// - Returns: The instance. + @discardableResult + public func cancel(producingResumeData shouldProduceResumeData: Bool) -> Self { + cancel(optionallyProducingResumeData: shouldProduceResumeData ? { _ in } : nil) + } + + /// Cancels the instance while producing resume data. Once cancelled, a `DownloadRequest` can no longer be resumed + /// or suspended. + /// + /// - Note: The resume data passed to the completion handler will also be available on the instance's `resumeData` + /// property. + /// + /// - Parameter completionHandler: The completion handler that is called when the download has been successfully + /// cancelled. It is not guaranteed to be called on a particular queue, so you may + /// want use an appropriate queue to perform your work. + /// + /// - Returns: The instance. + @discardableResult + public func cancel(byProducingResumeData completionHandler: @escaping (_ data: Data?) -> Void) -> Self { + cancel(optionallyProducingResumeData: completionHandler) + } + + /// Internal implementation of cancellation that optionally takes a resume data handler. If no handler is passed, + /// cancellation is performed without producing resume data. + /// + /// - Parameter completionHandler: Optional resume data handler. + /// + /// - Returns: The instance. + private func cancel(optionallyProducingResumeData completionHandler: ((_ resumeData: Data?) -> Void)?) -> Self { + $mutableState.write { mutableState in + guard mutableState.state.canTransitionTo(.cancelled) else { return } + + mutableState.state = .cancelled + + underlyingQueue.async { self.didCancel() } + + guard let task = mutableState.tasks.last as? URLSessionDownloadTask, task.state != .completed else { + underlyingQueue.async { self.finish() } + return + } + + if let completionHandler = completionHandler { + // Resume to ensure metrics are gathered. + task.resume() + task.cancel { resumeData in + self.$mutableDownloadState.resumeData = resumeData + self.underlyingQueue.async { self.didCancelTask(task) } + completionHandler(resumeData) + } + } else { + // Resume to ensure metrics are gathered. + task.resume() + task.cancel() + self.underlyingQueue.async { self.didCancelTask(task) } + } + } + + return self + } + + /// Validates the request, using the specified closure. + /// + /// - Note: If validation fails, subsequent calls to response handlers will have an associated error. + /// + /// - Parameter validation: `Validation` closure to validate the response. + /// + /// - Returns: The instance. + @discardableResult + public func validate(_ validation: @escaping Validation) -> Self { + let validator: () -> Void = { [unowned self] in + guard error == nil, let response = response else { return } + + let result = validation(request, response, fileURL) + + if case let .failure(error) = result { + self.error = error.asAFError(or: .responseValidationFailed(reason: .customValidationFailed(error: error))) + } + + eventMonitor?.request(self, + didValidateRequest: request, + response: response, + fileURL: fileURL, + withResult: result) + } + + $validators.write { $0.append(validator) } + + return self + } +} + +// MARK: - UploadRequest + +/// `DataRequest` subclass which handles `Data` upload from memory, file, or stream using `URLSessionUploadTask`. +public class UploadRequest: DataRequest { + /// Type describing the origin of the upload, whether `Data`, file, or stream. + public enum Uploadable { + /// Upload from the provided `Data` value. + case data(Data) + /// Upload from the provided file `URL`, as well as a `Bool` determining whether the source file should be + /// automatically removed once uploaded. + case file(URL, shouldRemove: Bool) + /// Upload from the provided `InputStream`. + case stream(InputStream) + } + + // MARK: Initial State + + /// The `UploadableConvertible` value used to produce the `Uploadable` value for this instance. + public let upload: UploadableConvertible + + /// `FileManager` used to perform cleanup tasks, including the removal of multipart form encoded payloads written + /// to disk. + public let fileManager: FileManager + + // MARK: Mutable State + + /// `Uploadable` value used by the instance. + public var uploadable: Uploadable? + + /// Creates an `UploadRequest` using the provided parameters. + /// + /// - Parameters: + /// - id: `UUID` used for the `Hashable` and `Equatable` implementations. `UUID()` by default. + /// - convertible: `UploadConvertible` value used to determine the type of upload to be performed. + /// - underlyingQueue: `DispatchQueue` on which all internal `Request` work is performed. + /// - serializationQueue: `DispatchQueue` on which all serialization work is performed. By default targets + /// `underlyingQueue`, but can be passed another queue from a `Session`. + /// - eventMonitor: `EventMonitor` called for event callbacks from internal `Request` actions. + /// - interceptor: `RequestInterceptor` used throughout the request lifecycle. + /// - fileManager: `FileManager` used to perform cleanup tasks, including the removal of multipart form + /// encoded payloads written to disk. + /// - delegate: `RequestDelegate` that provides an interface to actions not performed by the `Request`. + init(id: UUID = UUID(), + convertible: UploadConvertible, + underlyingQueue: DispatchQueue, + serializationQueue: DispatchQueue, + eventMonitor: EventMonitor?, + interceptor: RequestInterceptor?, + fileManager: FileManager, + delegate: RequestDelegate) { + upload = convertible + self.fileManager = fileManager + + super.init(id: id, + convertible: convertible, + underlyingQueue: underlyingQueue, + serializationQueue: serializationQueue, + eventMonitor: eventMonitor, + interceptor: interceptor, + delegate: delegate) + } + + /// Called when the `Uploadable` value has been created from the `UploadConvertible`. + /// + /// - Parameter uploadable: The `Uploadable` that was created. + func didCreateUploadable(_ uploadable: Uploadable) { + self.uploadable = uploadable + + eventMonitor?.request(self, didCreateUploadable: uploadable) + } + + /// Called when the `Uploadable` value could not be created. + /// + /// - Parameter error: `AFError` produced by the failure. + func didFailToCreateUploadable(with error: AFError) { + self.error = error + + eventMonitor?.request(self, didFailToCreateUploadableWithError: error) + + retryOrFinish(error: error) + } + + override func task(for request: URLRequest, using session: URLSession) -> URLSessionTask { + guard let uploadable = uploadable else { + fatalError("Attempting to create a URLSessionUploadTask when Uploadable value doesn't exist.") + } + + switch uploadable { + case let .data(data): return session.uploadTask(with: request, from: data) + case let .file(url, _): return session.uploadTask(with: request, fromFile: url) + case .stream: return session.uploadTask(withStreamedRequest: request) + } + } + + override func reset() { + // Uploadable must be recreated on every retry. + uploadable = nil + + super.reset() + } + + /// Produces the `InputStream` from `uploadable`, if it can. + /// + /// - Note: Calling this method with a non-`.stream` `Uploadable` is a logic error and will crash. + /// + /// - Returns: The `InputStream`. + func inputStream() -> InputStream { + guard let uploadable = uploadable else { + fatalError("Attempting to access the input stream but the uploadable doesn't exist.") + } + + guard case let .stream(stream) = uploadable else { + fatalError("Attempted to access the stream of an UploadRequest that wasn't created with one.") + } + + eventMonitor?.request(self, didProvideInputStream: stream) + + return stream + } + + override public func cleanup() { + defer { super.cleanup() } + + guard + let uploadable = uploadable, + case let .file(url, shouldRemove) = uploadable, + shouldRemove + else { return } + + try? fileManager.removeItem(at: url) + } +} + +/// A type that can produce an `UploadRequest.Uploadable` value. +public protocol UploadableConvertible { + /// Produces an `UploadRequest.Uploadable` value from the instance. + /// + /// - Returns: The `UploadRequest.Uploadable`. + /// - Throws: Any `Error` produced during creation. + func createUploadable() throws -> UploadRequest.Uploadable +} + +extension UploadRequest.Uploadable: UploadableConvertible { + public func createUploadable() throws -> UploadRequest.Uploadable { + self + } +} + +/// A type that can be converted to an upload, whether from an `UploadRequest.Uploadable` or `URLRequestConvertible`. +public protocol UploadConvertible: UploadableConvertible & URLRequestConvertible {} diff --git a/Pods/Alamofire/Source/RequestCompression.swift b/Pods/Alamofire/Source/RequestCompression.swift new file mode 100644 index 0000000..c543e06 --- /dev/null +++ b/Pods/Alamofire/Source/RequestCompression.swift @@ -0,0 +1,153 @@ +// +// RequestCompression.swift +// +// Copyright (c) 2023 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 canImport(zlib) +import Foundation +import zlib + +/// `RequestAdapter` which compresses outgoing `URLRequest` bodies using the `deflate` `Content-Encoding` and adds the +/// appropriate header. +/// +/// - Note: Most requests to most APIs are small and so would only be slowed down by applying this adapter. Measure the +/// size of your request bodies and the performance impact of using this adapter before use. Using this adapter +/// with already compressed data, such as images, will, at best, have no effect. Additionally, body compression +/// is a synchronous operation, so measuring the performance impact may be important to determine whether you +/// want to use a dedicated `requestQueue` in your `Session` instance. Finally, not all servers support request +/// compression, so test with all of your server configurations before deploying. +@available(macOS 10.15, iOS 13, tvOS 13, watchOS 6, *) +public struct DeflateRequestCompressor: RequestInterceptor { + /// Type that determines the action taken when the `URLRequest` already has a `Content-Encoding` header. + public enum DuplicateHeaderBehavior { + /// Throws a `DuplicateHeaderError`. The default. + case error + /// Replaces the existing header value with `deflate`. + case replace + /// Silently skips compression when the header exists. + case skip + } + + /// `Error` produced when the outgoing `URLRequest` already has a `Content-Encoding` header, when the instance has + /// been configured to produce an error. + public struct DuplicateHeaderError: Error {} + + /// Behavior to use when the outgoing `URLRequest` already has a `Content-Encoding` header. + public let duplicateHeaderBehavior: DuplicateHeaderBehavior + /// Closure which determines whether the outgoing body data should be compressed. + public let shouldCompressBodyData: (_ bodyData: Data) -> Bool + + /// Creates an instance with the provided parameters. + /// + /// - Parameters: + /// - duplicateHeaderBehavior: `DuplicateHeaderBehavior` to use. `.error` by default. + /// - shouldCompressBodyData: Closure which determines whether the outgoing body data should be compressed. `true` by default. + public init(duplicateHeaderBehavior: DuplicateHeaderBehavior = .error, + shouldCompressBodyData: @escaping (_ bodyData: Data) -> Bool = { _ in true }) { + self.duplicateHeaderBehavior = duplicateHeaderBehavior + self.shouldCompressBodyData = shouldCompressBodyData + } + + public func adapt(_ urlRequest: URLRequest, for session: Session, completion: @escaping (Result) -> Void) { + // No need to compress unless we have body data. No support for compressing streams. + guard let bodyData = urlRequest.httpBody else { + completion(.success(urlRequest)) + return + } + + guard shouldCompressBodyData(bodyData) else { + completion(.success(urlRequest)) + return + } + + if urlRequest.headers.value(for: "Content-Encoding") != nil { + switch duplicateHeaderBehavior { + case .error: + completion(.failure(DuplicateHeaderError())) + return + case .replace: + // Header will be replaced once the body data is compressed. + break + case .skip: + completion(.success(urlRequest)) + return + } + } + + var compressedRequest = urlRequest + + do { + compressedRequest.httpBody = try deflate(bodyData) + compressedRequest.headers.update(.contentEncoding("deflate")) + completion(.success(compressedRequest)) + } catch { + completion(.failure(error)) + } + } + + func deflate(_ data: Data) throws -> Data { + var output = Data([0x78, 0x5E]) // Header + try output.append((data as NSData).compressed(using: .zlib) as Data) + var checksum = adler32Checksum(of: data).bigEndian + output.append(Data(bytes: &checksum, count: MemoryLayout.size)) + + return output + } + + func adler32Checksum(of data: Data) -> UInt32 { + #if swift(>=5.6) + data.withUnsafeBytes { buffer in + UInt32(adler32(1, buffer.baseAddress, UInt32(buffer.count))) + } + #else + data.withUnsafeBytes { buffer in + let buffer = buffer.bindMemory(to: UInt8.self) + return UInt32(adler32(1, buffer.baseAddress, UInt32(buffer.count))) + } + #endif + } +} + +@available(macOS 10.15, iOS 13, tvOS 13, watchOS 6, *) +extension RequestInterceptor where Self == DeflateRequestCompressor { + /// Create a `DeflateRequestCompressor` with default `duplicateHeaderBehavior` and `shouldCompressBodyData` values. + public static var deflateCompressor: DeflateRequestCompressor { + DeflateRequestCompressor() + } + + /// Creates a `DeflateRequestCompressor` with the provided `DuplicateHeaderBehavior` and `shouldCompressBodyData` + /// closure. + /// + /// - Parameters: + /// - duplicateHeaderBehavior: `DuplicateHeaderBehavior` to use. + /// - shouldCompressBodyData: Closure which determines whether the outgoing body data should be compressed. `true` by default. + /// + /// - Returns: The `DeflateRequestCompressor`. + public static func deflateCompressor( + duplicateHeaderBehavior: DeflateRequestCompressor.DuplicateHeaderBehavior = .error, + shouldCompressBodyData: @escaping (_ bodyData: Data) -> Bool = { _ in true } + ) -> DeflateRequestCompressor { + DeflateRequestCompressor(duplicateHeaderBehavior: duplicateHeaderBehavior, + shouldCompressBodyData: shouldCompressBodyData) + } +} +#endif diff --git a/Pods/Alamofire/Source/RequestInterceptor.swift b/Pods/Alamofire/Source/RequestInterceptor.swift new file mode 100644 index 0000000..9acd986 --- /dev/null +++ b/Pods/Alamofire/Source/RequestInterceptor.swift @@ -0,0 +1,351 @@ +// +// RequestInterceptor.swift +// +// Copyright (c) 2019 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 + +/// Stores all state associated with a `URLRequest` being adapted. +public struct RequestAdapterState { + /// The `UUID` of the `Request` associated with the `URLRequest` to adapt. + public let requestID: UUID + + /// The `Session` associated with the `URLRequest` to adapt. + public let session: Session +} + +// MARK: - + +/// 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 and calls the completion handler with the Result. + /// + /// - Parameters: + /// - urlRequest: The `URLRequest` to adapt. + /// - session: The `Session` that will execute the `URLRequest`. + /// - completion: The completion handler that must be called when adaptation is complete. + func adapt(_ urlRequest: URLRequest, for session: Session, completion: @escaping (Result) -> Void) + + /// Inspects and adapts the specified `URLRequest` in some manner and calls the completion handler with the Result. + /// + /// - Parameters: + /// - urlRequest: The `URLRequest` to adapt. + /// - state: The `RequestAdapterState` associated with the `URLRequest`. + /// - completion: The completion handler that must be called when adaptation is complete. + func adapt(_ urlRequest: URLRequest, using state: RequestAdapterState, completion: @escaping (Result) -> Void) +} + +extension RequestAdapter { + public func adapt(_ urlRequest: URLRequest, using state: RequestAdapterState, completion: @escaping (Result) -> Void) { + adapt(urlRequest, for: state.session, completion: completion) + } +} + +// MARK: - + +/// Outcome of determination whether retry is necessary. +public enum RetryResult { + /// Retry should be attempted immediately. + case retry + /// Retry should be attempted after the associated `TimeInterval`. + case retryWithDelay(TimeInterval) + /// Do not retry. + case doNotRetry + /// Do not retry due to the associated `Error`. + case doNotRetryWithError(Error) +} + +extension RetryResult { + var retryRequired: Bool { + switch self { + case .retry, .retryWithDelay: return true + default: return false + } + } + + var delay: TimeInterval? { + switch self { + case let .retryWithDelay(delay): return delay + default: return nil + } + } + + var error: Error? { + guard case let .doNotRetryWithError(error) = self else { return nil } + return error + } +} + +/// 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. + /// + /// - Parameters: + /// - request: `Request` that failed due to the provided `Error`. + /// - session: `Session` that produced the `Request`. + /// - error: `Error` encountered while executing the `Request`. + /// - completion: Completion closure to be executed when a retry decision has been determined. + func retry(_ request: Request, for session: Session, dueTo error: Error, completion: @escaping (RetryResult) -> Void) +} + +// MARK: - + +/// Type that provides both `RequestAdapter` and `RequestRetrier` functionality. +public protocol RequestInterceptor: RequestAdapter, RequestRetrier {} + +extension RequestInterceptor { + public func adapt(_ urlRequest: URLRequest, for session: Session, completion: @escaping (Result) -> Void) { + completion(.success(urlRequest)) + } + + public func retry(_ request: Request, + for session: Session, + dueTo error: Error, + completion: @escaping (RetryResult) -> Void) { + completion(.doNotRetry) + } +} + +/// `RequestAdapter` closure definition. +public typealias AdaptHandler = (URLRequest, Session, _ completion: @escaping (Result) -> Void) -> Void +/// `RequestRetrier` closure definition. +public typealias RetryHandler = (Request, Session, Error, _ completion: @escaping (RetryResult) -> Void) -> Void + +// MARK: - + +/// Closure-based `RequestAdapter`. +open class Adapter: RequestInterceptor { + private let adaptHandler: AdaptHandler + + /// Creates an instance using the provided closure. + /// + /// - Parameter adaptHandler: `AdaptHandler` closure to be executed when handling request adaptation. + public init(_ adaptHandler: @escaping AdaptHandler) { + self.adaptHandler = adaptHandler + } + + open func adapt(_ urlRequest: URLRequest, for session: Session, completion: @escaping (Result) -> Void) { + adaptHandler(urlRequest, session, completion) + } + + open func adapt(_ urlRequest: URLRequest, using state: RequestAdapterState, completion: @escaping (Result) -> Void) { + adaptHandler(urlRequest, state.session, completion) + } +} + +extension RequestAdapter where Self == Adapter { + /// Creates an `Adapter` using the provided `AdaptHandler` closure. + /// + /// - Parameter closure: `AdaptHandler` to use to adapt the request. + /// - Returns: The `Adapter`. + public static func adapter(using closure: @escaping AdaptHandler) -> Adapter { + Adapter(closure) + } +} + +// MARK: - + +/// Closure-based `RequestRetrier`. +open class Retrier: RequestInterceptor { + private let retryHandler: RetryHandler + + /// Creates an instance using the provided closure. + /// + /// - Parameter retryHandler: `RetryHandler` closure to be executed when handling request retry. + public init(_ retryHandler: @escaping RetryHandler) { + self.retryHandler = retryHandler + } + + open func retry(_ request: Request, + for session: Session, + dueTo error: Error, + completion: @escaping (RetryResult) -> Void) { + retryHandler(request, session, error, completion) + } +} + +extension RequestRetrier where Self == Retrier { + /// Creates a `Retrier` using the provided `RetryHandler` closure. + /// + /// - Parameter closure: `RetryHandler` to use to retry the request. + /// - Returns: The `Retrier`. + public static func retrier(using closure: @escaping RetryHandler) -> Retrier { + Retrier(closure) + } +} + +// MARK: - + +/// `RequestInterceptor` which can use multiple `RequestAdapter` and `RequestRetrier` values. +open class Interceptor: RequestInterceptor { + /// All `RequestAdapter`s associated with the instance. These adapters will be run until one fails. + public let adapters: [RequestAdapter] + /// All `RequestRetrier`s associated with the instance. These retriers will be run one at a time until one triggers retry. + public let retriers: [RequestRetrier] + + /// Creates an instance from `AdaptHandler` and `RetryHandler` closures. + /// + /// - Parameters: + /// - adaptHandler: `AdaptHandler` closure to be used. + /// - retryHandler: `RetryHandler` closure to be used. + public init(adaptHandler: @escaping AdaptHandler, retryHandler: @escaping RetryHandler) { + adapters = [Adapter(adaptHandler)] + retriers = [Retrier(retryHandler)] + } + + /// Creates an instance from `RequestAdapter` and `RequestRetrier` values. + /// + /// - Parameters: + /// - adapter: `RequestAdapter` value to be used. + /// - retrier: `RequestRetrier` value to be used. + public init(adapter: RequestAdapter, retrier: RequestRetrier) { + adapters = [adapter] + retriers = [retrier] + } + + /// Creates an instance from the arrays of `RequestAdapter` and `RequestRetrier` values. + /// + /// - Parameters: + /// - adapters: `RequestAdapter` values to be used. + /// - retriers: `RequestRetrier` values to be used. + /// - interceptors: `RequestInterceptor`s to be used. + public init(adapters: [RequestAdapter] = [], retriers: [RequestRetrier] = [], interceptors: [RequestInterceptor] = []) { + self.adapters = adapters + interceptors + self.retriers = retriers + interceptors + } + + open func adapt(_ urlRequest: URLRequest, for session: Session, completion: @escaping (Result) -> Void) { + adapt(urlRequest, for: session, using: adapters, completion: completion) + } + + private func adapt(_ urlRequest: URLRequest, + for session: Session, + using adapters: [RequestAdapter], + completion: @escaping (Result) -> Void) { + var pendingAdapters = adapters + + guard !pendingAdapters.isEmpty else { completion(.success(urlRequest)); return } + + let adapter = pendingAdapters.removeFirst() + + adapter.adapt(urlRequest, for: session) { result in + switch result { + case let .success(urlRequest): + self.adapt(urlRequest, for: session, using: pendingAdapters, completion: completion) + case .failure: + completion(result) + } + } + } + + open func adapt(_ urlRequest: URLRequest, using state: RequestAdapterState, completion: @escaping (Result) -> Void) { + adapt(urlRequest, using: state, adapters: adapters, completion: completion) + } + + private func adapt(_ urlRequest: URLRequest, + using state: RequestAdapterState, + adapters: [RequestAdapter], + completion: @escaping (Result) -> Void) { + var pendingAdapters = adapters + + guard !pendingAdapters.isEmpty else { completion(.success(urlRequest)); return } + + let adapter = pendingAdapters.removeFirst() + + adapter.adapt(urlRequest, using: state) { result in + switch result { + case let .success(urlRequest): + self.adapt(urlRequest, using: state, adapters: pendingAdapters, completion: completion) + case .failure: + completion(result) + } + } + } + + open func retry(_ request: Request, + for session: Session, + dueTo error: Error, + completion: @escaping (RetryResult) -> Void) { + retry(request, for: session, dueTo: error, using: retriers, completion: completion) + } + + private func retry(_ request: Request, + for session: Session, + dueTo error: Error, + using retriers: [RequestRetrier], + completion: @escaping (RetryResult) -> Void) { + var pendingRetriers = retriers + + guard !pendingRetriers.isEmpty else { completion(.doNotRetry); return } + + let retrier = pendingRetriers.removeFirst() + + retrier.retry(request, for: session, dueTo: error) { result in + switch result { + case .retry, .retryWithDelay, .doNotRetryWithError: + completion(result) + case .doNotRetry: + // Only continue to the next retrier if retry was not triggered and no error was encountered + self.retry(request, for: session, dueTo: error, using: pendingRetriers, completion: completion) + } + } + } +} + +extension RequestInterceptor where Self == Interceptor { + /// Creates an `Interceptor` using the provided `AdaptHandler` and `RetryHandler` closures. + /// + /// - Parameters: + /// - adapter: `AdapterHandler`to use to adapt the request. + /// - retrier: `RetryHandler` to use to retry the request. + /// - Returns: The `Interceptor`. + public static func interceptor(adapter: @escaping AdaptHandler, retrier: @escaping RetryHandler) -> Interceptor { + Interceptor(adaptHandler: adapter, retryHandler: retrier) + } + + /// Creates an `Interceptor` using the provided `RequestAdapter` and `RequestRetrier` instances. + /// - Parameters: + /// - adapter: `RequestAdapter` to use to adapt the request + /// - retrier: `RequestRetrier` to use to retry the request. + /// - Returns: The `Interceptor`. + public static func interceptor(adapter: RequestAdapter, retrier: RequestRetrier) -> Interceptor { + Interceptor(adapter: adapter, retrier: retrier) + } + + /// Creates an `Interceptor` using the provided `RequestAdapter`s, `RequestRetrier`s, and `RequestInterceptor`s. + /// - Parameters: + /// - adapters: `RequestAdapter`s to use to adapt the request. These adapters will be run until one fails. + /// - retriers: `RequestRetrier`s to use to retry the request. These retriers will be run one at a time until + /// a retry is triggered. + /// - interceptors: `RequestInterceptor`s to use to intercept the request. + /// - Returns: The `Interceptor`. + public static func interceptor(adapters: [RequestAdapter] = [], + retriers: [RequestRetrier] = [], + interceptors: [RequestInterceptor] = []) -> Interceptor { + Interceptor(adapters: adapters, retriers: retriers, interceptors: interceptors) + } +} diff --git a/Pods/Alamofire/Source/RequestTaskMap.swift b/Pods/Alamofire/Source/RequestTaskMap.swift new file mode 100644 index 0000000..85b58f3 --- /dev/null +++ b/Pods/Alamofire/Source/RequestTaskMap.swift @@ -0,0 +1,149 @@ +// +// RequestTaskMap.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 maintains a two way, one to one map of `URLSessionTask`s to `Request`s. +struct RequestTaskMap { + private typealias Events = (completed: Bool, metricsGathered: Bool) + + private var tasksToRequests: [URLSessionTask: Request] + private var requestsToTasks: [Request: URLSessionTask] + private var taskEvents: [URLSessionTask: Events] + + var requests: [Request] { + Array(tasksToRequests.values) + } + + init(tasksToRequests: [URLSessionTask: Request] = [:], + requestsToTasks: [Request: URLSessionTask] = [:], + taskEvents: [URLSessionTask: (completed: Bool, metricsGathered: Bool)] = [:]) { + self.tasksToRequests = tasksToRequests + self.requestsToTasks = requestsToTasks + self.taskEvents = taskEvents + } + + subscript(_ request: Request) -> URLSessionTask? { + get { requestsToTasks[request] } + set { + guard let newValue = newValue else { + guard let task = requestsToTasks[request] else { + fatalError("RequestTaskMap consistency error: no task corresponding to request found.") + } + + requestsToTasks.removeValue(forKey: request) + tasksToRequests.removeValue(forKey: task) + taskEvents.removeValue(forKey: task) + + return + } + + requestsToTasks[request] = newValue + tasksToRequests[newValue] = request + taskEvents[newValue] = (completed: false, metricsGathered: false) + } + } + + subscript(_ task: URLSessionTask) -> Request? { + get { tasksToRequests[task] } + set { + guard let newValue = newValue else { + guard let request = tasksToRequests[task] else { + fatalError("RequestTaskMap consistency error: no request corresponding to task found.") + } + + tasksToRequests.removeValue(forKey: task) + requestsToTasks.removeValue(forKey: request) + taskEvents.removeValue(forKey: task) + + return + } + + tasksToRequests[task] = newValue + requestsToTasks[newValue] = task + taskEvents[task] = (completed: false, metricsGathered: false) + } + } + + var count: Int { + precondition(tasksToRequests.count == requestsToTasks.count, + "RequestTaskMap.count invalid, requests.count: \(tasksToRequests.count) != tasks.count: \(requestsToTasks.count)") + + return tasksToRequests.count + } + + var eventCount: Int { + precondition(taskEvents.count == count, "RequestTaskMap.eventCount invalid, count: \(count) != taskEvents.count: \(taskEvents.count)") + + return taskEvents.count + } + + var isEmpty: Bool { + precondition(tasksToRequests.isEmpty == requestsToTasks.isEmpty, + "RequestTaskMap.isEmpty invalid, requests.isEmpty: \(tasksToRequests.isEmpty) != tasks.isEmpty: \(requestsToTasks.isEmpty)") + + return tasksToRequests.isEmpty + } + + var isEventsEmpty: Bool { + precondition(taskEvents.isEmpty == isEmpty, "RequestTaskMap.isEventsEmpty invalid, isEmpty: \(isEmpty) != taskEvents.isEmpty: \(taskEvents.isEmpty)") + + return taskEvents.isEmpty + } + + mutating func disassociateIfNecessaryAfterGatheringMetricsForTask(_ task: URLSessionTask) -> Bool { + guard let events = taskEvents[task] else { + fatalError("RequestTaskMap consistency error: no events corresponding to task found.") + } + + switch (events.completed, events.metricsGathered) { + case (_, true): fatalError("RequestTaskMap consistency error: duplicate metricsGatheredForTask call.") + case (false, false): taskEvents[task] = (completed: false, metricsGathered: true); return false + case (true, false): self[task] = nil; return true + } + } + + mutating func disassociateIfNecessaryAfterCompletingTask(_ task: URLSessionTask) -> Bool { + guard let events = taskEvents[task] else { + fatalError("RequestTaskMap consistency error: no events corresponding to task found.") + } + + switch (events.completed, events.metricsGathered) { + case (true, _): fatalError("RequestTaskMap consistency error: duplicate completionReceivedForTask call.") + #if os(Linux) // Linux doesn't gather metrics, so unconditionally remove the reference and return true. + default: self[task] = nil; return true + #else + case (false, false): + if #available(macOS 10.12, iOS 10, watchOS 7, tvOS 10, *) { + taskEvents[task] = (completed: true, metricsGathered: false); return false + } else { + // watchOS < 7 doesn't gather metrics, so unconditionally remove the reference and return true. + self[task] = nil; return true + } + case (false, true): + self[task] = nil; return true + #endif + } + } +} diff --git a/Pods/Alamofire/Source/Response.swift b/Pods/Alamofire/Source/Response.swift new file mode 100644 index 0000000..d9ae9d8 --- /dev/null +++ b/Pods/Alamofire/Source/Response.swift @@ -0,0 +1,453 @@ +// +// 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 + +/// Default type of `DataResponse` returned by Alamofire, with an `AFError` `Failure` type. +public typealias AFDataResponse = DataResponse +/// Default type of `DownloadResponse` returned by Alamofire, with an `AFError` `Failure` type. +public typealias AFDownloadResponse = DownloadResponse + +/// Type used to store all values associated with a serialized response of a `DataRequest` or `UploadRequest`. +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 final metrics of the response. + /// + /// - Note: Due to `FB7624529`, collection of `URLSessionTaskMetrics` on watchOS is currently disabled.` + /// + public let metrics: URLSessionTaskMetrics? + + /// The time taken to serialize the response. + public let serializationDuration: TimeInterval + + /// The result of response serialization. + public let result: Result + + /// Returns the associated value of the result if it is a success, `nil` otherwise. + public var value: Success? { result.success } + + /// Returns the associated error value if the result if it is a failure, `nil` otherwise. + public var error: Failure? { result.failure } + + /// Creates a `DataResponse` instance with the specified parameters derived from the response serialization. + /// + /// - Parameters: + /// - request: The `URLRequest` sent to the server. + /// - response: The `HTTPURLResponse` from the server. + /// - data: The `Data` returned by the server. + /// - metrics: The `URLSessionTaskMetrics` of the `DataRequest` or `UploadRequest`. + /// - serializationDuration: The duration taken by serialization. + /// - result: The `Result` of response serialization. + public init(request: URLRequest?, + response: HTTPURLResponse?, + data: Data?, + metrics: URLSessionTaskMetrics?, + serializationDuration: TimeInterval, + result: Result) { + self.request = request + self.response = response + self.data = data + self.metrics = metrics + self.serializationDuration = serializationDuration + self.result = result + } +} + +// 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 { + "\(result)" + } + + /// The debug textual representation used when written to an output stream, which includes (if available) a summary + /// of the `URLRequest`, the request's headers and body (if decodable as a `String` below 100KB); the + /// `HTTPURLResponse`'s status code, headers, and body; the duration of the network and serialization actions; and + /// the `Result` of serialization. + public var debugDescription: String { + guard let urlRequest = request else { return "[Request]: None\n[Result]: \(result)" } + + let requestDescription = DebugDescription.description(of: urlRequest) + + let responseDescription = response.map { response in + let responseBodyDescription = DebugDescription.description(for: data, headers: response.headers) + + return """ + \(DebugDescription.description(of: response)) + \(responseBodyDescription.indentingNewlines()) + """ + } ?? "[Response]: None" + + let networkDuration = metrics.map { "\($0.taskInterval.duration)s" } ?? "None" + + return """ + \(requestDescription) + \(responseDescription) + [Network Duration]: \(networkDuration) + [Serialization Duration]: \(serializationDuration)s + [Result]: \(result) + """ + } +} + +// 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: (Success) -> NewSuccess) -> DataResponse { + DataResponse(request: request, + response: response, + data: data, + metrics: metrics, + serializationDuration: serializationDuration, + result: result.map(transform)) + } + + /// Evaluates the given closure when the result of this `DataResponse` is a success, passing the unwrapped result + /// value as a parameter. + /// + /// Use the `tryMap` method with a closure that may throw an error. For example: + /// + /// let possibleData: DataResponse = ... + /// let possibleObject = possibleData.tryMap { + /// 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 tryMap(_ transform: (Success) throws -> NewSuccess) -> DataResponse { + DataResponse(request: request, + response: response, + data: data, + metrics: metrics, + serializationDuration: serializationDuration, + result: result.tryMap(transform)) + } + + /// 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: (Failure) -> NewFailure) -> DataResponse { + DataResponse(request: request, + response: response, + data: data, + metrics: metrics, + serializationDuration: serializationDuration, + result: result.mapError(transform)) + } + + /// Evaluates the specified closure when the `DataResponse` is a failure, passing the unwrapped error as a parameter. + /// + /// Use the `tryMapError` function with a closure that may throw an error. For example: + /// + /// let possibleData: DataResponse = ... + /// let possibleObject = possibleData.tryMapError { + /// 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 tryMapError(_ transform: (Failure) throws -> NewFailure) -> DataResponse { + DataResponse(request: request, + response: response, + data: data, + metrics: metrics, + serializationDuration: serializationDuration, + result: result.tryMapError(transform)) + } +} + +// 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 final destination URL of the data returned from the server after it is moved. + public let fileURL: URL? + + /// The resume data generated if the request was cancelled. + public let resumeData: Data? + + /// The final metrics of the response. + /// + /// - Note: Due to `FB7624529`, collection of `URLSessionTaskMetrics` on watchOS is currently disabled.` + /// + public let metrics: URLSessionTaskMetrics? + + /// The time taken to serialize the response. + public let serializationDuration: TimeInterval + + /// The result of response serialization. + public let result: Result + + /// Returns the associated value of the result if it is a success, `nil` otherwise. + public var value: Success? { result.success } + + /// Returns the associated error value if the result if it is a failure, `nil` otherwise. + public var error: Failure? { result.failure } + + /// Creates a `DownloadResponse` instance with the specified parameters derived from response serialization. + /// + /// - Parameters: + /// - request: The `URLRequest` sent to the server. + /// - response: The `HTTPURLResponse` from the server. + /// - fileURL: The final destination URL of the data returned from the server after it is moved. + /// - resumeData: The resume `Data` generated if the request was cancelled. + /// - metrics: The `URLSessionTaskMetrics` of the `DownloadRequest`. + /// - serializationDuration: The duration taken by serialization. + /// - result: The `Result` of response serialization. + public init(request: URLRequest?, + response: HTTPURLResponse?, + fileURL: URL?, + resumeData: Data?, + metrics: URLSessionTaskMetrics?, + serializationDuration: TimeInterval, + result: Result) { + self.request = request + self.response = response + self.fileURL = fileURL + self.resumeData = resumeData + self.metrics = metrics + self.serializationDuration = serializationDuration + self.result = result + } +} + +// 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 { + "\(result)" + } + + /// 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 durations of the network and serialization + /// actions, and the response serialization result. + public var debugDescription: String { + guard let urlRequest = request else { return "[Request]: None\n[Result]: \(result)" } + + let requestDescription = DebugDescription.description(of: urlRequest) + let responseDescription = response.map(DebugDescription.description(of:)) ?? "[Response]: None" + let networkDuration = metrics.map { "\($0.taskInterval.duration)s" } ?? "None" + let resumeDataDescription = resumeData.map { "\($0)" } ?? "None" + + return """ + \(requestDescription) + \(responseDescription) + [File URL]: \(fileURL?.path ?? "None") + [Resume Data]: \(resumeDataDescription) + [Network Duration]: \(networkDuration) + [Serialization Duration]: \(serializationDuration)s + [Result]: \(result) + """ + } +} + +// 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: (Success) -> NewSuccess) -> DownloadResponse { + DownloadResponse(request: request, + response: response, + fileURL: fileURL, + resumeData: resumeData, + metrics: metrics, + serializationDuration: serializationDuration, + result: result.map(transform)) + } + + /// Evaluates the given closure when the result of this `DownloadResponse` is a success, passing the unwrapped + /// result value as a parameter. + /// + /// Use the `tryMap` method with a closure that may throw an error. For example: + /// + /// let possibleData: DownloadResponse = ... + /// let possibleObject = possibleData.tryMap { + /// 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 tryMap(_ transform: (Success) throws -> NewSuccess) -> DownloadResponse { + DownloadResponse(request: request, + response: response, + fileURL: fileURL, + resumeData: resumeData, + metrics: metrics, + serializationDuration: serializationDuration, + result: result.tryMap(transform)) + } + + /// 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: (Failure) -> NewFailure) -> DownloadResponse { + DownloadResponse(request: request, + response: response, + fileURL: fileURL, + resumeData: resumeData, + metrics: metrics, + serializationDuration: serializationDuration, + result: result.mapError(transform)) + } + + /// Evaluates the specified closure when the `DownloadResponse` is a failure, passing the unwrapped error as a parameter. + /// + /// Use the `tryMapError` function with a closure that may throw an error. For example: + /// + /// let possibleData: DownloadResponse = ... + /// let possibleObject = possibleData.tryMapError { + /// 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 tryMapError(_ transform: (Failure) throws -> NewFailure) -> DownloadResponse { + DownloadResponse(request: request, + response: response, + fileURL: fileURL, + resumeData: resumeData, + metrics: metrics, + serializationDuration: serializationDuration, + result: result.tryMapError(transform)) + } +} + +private enum DebugDescription { + static func description(of request: URLRequest) -> String { + let requestSummary = "\(request.httpMethod!) \(request)" + let requestHeadersDescription = DebugDescription.description(for: request.headers) + let requestBodyDescription = DebugDescription.description(for: request.httpBody, headers: request.headers) + + return """ + [Request]: \(requestSummary) + \(requestHeadersDescription.indentingNewlines()) + \(requestBodyDescription.indentingNewlines()) + """ + } + + static func description(of response: HTTPURLResponse) -> String { + """ + [Response]: + [Status Code]: \(response.statusCode) + \(DebugDescription.description(for: response.headers).indentingNewlines()) + """ + } + + static func description(for headers: HTTPHeaders) -> String { + guard !headers.isEmpty else { return "[Headers]: None" } + + let headerDescription = "\(headers.sorted())".indentingNewlines() + return """ + [Headers]: + \(headerDescription) + """ + } + + static func description(for data: Data?, + headers: HTTPHeaders, + allowingPrintableTypes printableTypes: [String] = ["json", "xml", "text"], + maximumLength: Int = 100_000) -> String { + guard let data = data, !data.isEmpty else { return "[Body]: None" } + + guard + data.count <= maximumLength, + printableTypes.compactMap({ headers["Content-Type"]?.contains($0) }).contains(true) + else { return "[Body]: \(data.count) bytes" } + + return """ + [Body]: + \(String(decoding: data, as: UTF8.self) + .trimmingCharacters(in: .whitespacesAndNewlines) + .indentingNewlines()) + """ + } +} + +extension String { + fileprivate func indentingNewlines(by spaceCount: Int = 4) -> String { + let spaces = String(repeating: " ", count: spaceCount) + return replacingOccurrences(of: "\n", with: "\n\(spaces)") + } +} diff --git a/Pods/Alamofire/Source/ResponseSerialization.swift b/Pods/Alamofire/Source/ResponseSerialization.swift new file mode 100644 index 0000000..0e718bd --- /dev/null +++ b/Pods/Alamofire/Source/ResponseSerialization.swift @@ -0,0 +1,1270 @@ +// +// 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 + +// MARK: Protocols + +/// The type to which all data response serializers must conform in order to serialize a response. +public protocol DataResponseSerializerProtocol { + /// The type of serialized object to be created. + associatedtype SerializedObject + + /// Serialize the response `Data` into the provided type.. + /// + /// - Parameters: + /// - request: `URLRequest` which was used to perform the request, if any. + /// - response: `HTTPURLResponse` received from the server, if any. + /// - data: `Data` returned from the server, if any. + /// - error: `Error` produced by Alamofire or the underlying `URLSession` during the request. + /// + /// - Returns: The `SerializedObject`. + /// - Throws: Any `Error` produced during serialization. + func serialize(request: URLRequest?, response: HTTPURLResponse?, data: Data?, error: Error?) throws -> SerializedObject +} + +/// The type to which all download response serializers must conform in order to serialize a response. +public protocol DownloadResponseSerializerProtocol { + /// The type of serialized object to be created. + associatedtype SerializedObject + + /// Serialize the downloaded response `Data` from disk into the provided type.. + /// + /// - Parameters: + /// - request: `URLRequest` which was used to perform the request, if any. + /// - response: `HTTPURLResponse` received from the server, if any. + /// - fileURL: File `URL` to which the response data was downloaded. + /// - error: `Error` produced by Alamofire or the underlying `URLSession` during the request. + /// + /// - Returns: The `SerializedObject`. + /// - Throws: Any `Error` produced during serialization. + func serializeDownload(request: URLRequest?, response: HTTPURLResponse?, fileURL: URL?, error: Error?) throws -> SerializedObject +} + +/// A serializer that can handle both data and download responses. +public protocol ResponseSerializer: DataResponseSerializerProtocol & DownloadResponseSerializerProtocol { + /// `DataPreprocessor` used to prepare incoming `Data` for serialization. + var dataPreprocessor: DataPreprocessor { get } + /// `HTTPMethod`s for which empty response bodies are considered appropriate. + var emptyRequestMethods: Set { get } + /// HTTP response codes for which empty response bodies are considered appropriate. + var emptyResponseCodes: Set { get } +} + +/// Type used to preprocess `Data` before it handled by a serializer. +public protocol DataPreprocessor { + /// Process `Data` before it's handled by a serializer. + /// - Parameter data: The raw `Data` to process. + func preprocess(_ data: Data) throws -> Data +} + +/// `DataPreprocessor` that returns passed `Data` without any transform. +public struct PassthroughPreprocessor: DataPreprocessor { + public init() {} + + public func preprocess(_ data: Data) throws -> Data { data } +} + +/// `DataPreprocessor` that trims Google's typical `)]}',\n` XSSI JSON header. +public struct GoogleXSSIPreprocessor: DataPreprocessor { + public init() {} + + public func preprocess(_ data: Data) throws -> Data { + (data.prefix(6) == Data(")]}',\n".utf8)) ? data.dropFirst(6) : data + } +} + +extension DataPreprocessor where Self == PassthroughPreprocessor { + /// Provides a `PassthroughPreprocessor` instance. + public static var passthrough: PassthroughPreprocessor { PassthroughPreprocessor() } +} + +extension DataPreprocessor where Self == GoogleXSSIPreprocessor { + /// Provides a `GoogleXSSIPreprocessor` instance. + public static var googleXSSI: GoogleXSSIPreprocessor { GoogleXSSIPreprocessor() } +} + +extension ResponseSerializer { + /// Default `DataPreprocessor`. `PassthroughPreprocessor` by default. + public static var defaultDataPreprocessor: DataPreprocessor { PassthroughPreprocessor() } + /// Default `HTTPMethod`s for which empty response bodies are considered appropriate. `[.head]` by default. + public static var defaultEmptyRequestMethods: Set { [.head] } + /// HTTP response codes for which empty response bodies are considered appropriate. `[204, 205]` by default. + public static var defaultEmptyResponseCodes: Set { [204, 205] } + + public var dataPreprocessor: DataPreprocessor { Self.defaultDataPreprocessor } + public var emptyRequestMethods: Set { Self.defaultEmptyRequestMethods } + public var emptyResponseCodes: Set { Self.defaultEmptyResponseCodes } + + /// Determines whether the `request` allows empty response bodies, if `request` exists. + /// + /// - Parameter request: `URLRequest` to evaluate. + /// + /// - Returns: `Bool` representing the outcome of the evaluation, or `nil` if `request` was `nil`. + public func requestAllowsEmptyResponseData(_ request: URLRequest?) -> Bool? { + request.flatMap(\.httpMethod) + .flatMap(HTTPMethod.init) + .map { emptyRequestMethods.contains($0) } + } + + /// Determines whether the `response` allows empty response bodies, if `response` exists`. + /// + /// - Parameter response: `HTTPURLResponse` to evaluate. + /// + /// - Returns: `Bool` representing the outcome of the evaluation, or `nil` if `response` was `nil`. + public func responseAllowsEmptyResponseData(_ response: HTTPURLResponse?) -> Bool? { + response.map(\.statusCode) + .map { emptyResponseCodes.contains($0) } + } + + /// Determines whether `request` and `response` allow empty response bodies. + /// + /// - Parameters: + /// - request: `URLRequest` to evaluate. + /// - response: `HTTPURLResponse` to evaluate. + /// + /// - Returns: `true` if `request` or `response` allow empty bodies, `false` otherwise. + public func emptyResponseAllowed(forRequest request: URLRequest?, response: HTTPURLResponse?) -> Bool { + (requestAllowsEmptyResponseData(request) == true) || (responseAllowsEmptyResponseData(response) == true) + } +} + +/// By default, any serializer declared to conform to both types will get file serialization for free, as it just feeds +/// the data read from disk into the data response serializer. +extension DownloadResponseSerializerProtocol where Self: DataResponseSerializerProtocol { + public func serializeDownload(request: URLRequest?, response: HTTPURLResponse?, fileURL: URL?, error: Error?) throws -> Self.SerializedObject { + guard error == nil else { throw error! } + + guard let fileURL = fileURL else { + throw AFError.responseSerializationFailed(reason: .inputFileNil) + } + + let data: Data + do { + data = try Data(contentsOf: fileURL) + } catch { + throw AFError.responseSerializationFailed(reason: .inputFileReadFailed(at: fileURL)) + } + + do { + return try serialize(request: request, response: response, data: data, error: error) + } catch { + throw error + } + } +} + +// MARK: - Default + +extension DataRequest { + /// Adds a handler to be called once the request has finished. + /// + /// - Parameters: + /// - queue: The queue on which the completion handler is dispatched. `.main` by default. + /// - completionHandler: The code to be executed once the request has finished. + /// + /// - Returns: The request. + @discardableResult + public func response(queue: DispatchQueue = .main, completionHandler: @escaping (AFDataResponse) -> Void) -> Self { + appendResponseSerializer { + // Start work that should be on the serialization queue. + let result = AFResult(value: self.data, error: self.error) + // End work that should be on the serialization queue. + + self.underlyingQueue.async { + let response = DataResponse(request: self.request, + response: self.response, + data: self.data, + metrics: self.metrics, + serializationDuration: 0, + result: result) + + self.eventMonitor?.request(self, didParseResponse: response) + + self.responseSerializerDidComplete { queue.async { completionHandler(response) } } + } + } + + return self + } + + private func _response(queue: DispatchQueue = .main, + responseSerializer: Serializer, + completionHandler: @escaping (AFDataResponse) -> Void) + -> Self { + appendResponseSerializer { + // Start work that should be on the serialization queue. + let start = ProcessInfo.processInfo.systemUptime + let result: AFResult = Result { + try responseSerializer.serialize(request: self.request, + response: self.response, + data: self.data, + error: self.error) + }.mapError { error in + error.asAFError(or: .responseSerializationFailed(reason: .customSerializationFailed(error: error))) + } + + let end = ProcessInfo.processInfo.systemUptime + // End work that should be on the serialization queue. + + self.underlyingQueue.async { + let response = DataResponse(request: self.request, + response: self.response, + data: self.data, + metrics: self.metrics, + serializationDuration: end - start, + result: result) + + self.eventMonitor?.request(self, didParseResponse: response) + + guard !self.isCancelled, let serializerError = result.failure, let delegate = self.delegate else { + self.responseSerializerDidComplete { queue.async { completionHandler(response) } } + return + } + + delegate.retryResult(for: self, dueTo: serializerError) { retryResult in + var didComplete: (() -> Void)? + + defer { + if let didComplete = didComplete { + self.responseSerializerDidComplete { queue.async { didComplete() } } + } + } + + switch retryResult { + case .doNotRetry: + didComplete = { completionHandler(response) } + + case let .doNotRetryWithError(retryError): + let result: AFResult = .failure(retryError.asAFError(orFailWith: "Received retryError was not already AFError")) + + let response = DataResponse(request: self.request, + response: self.response, + data: self.data, + metrics: self.metrics, + serializationDuration: end - start, + result: result) + + didComplete = { completionHandler(response) } + + case .retry, .retryWithDelay: + delegate.retryRequest(self, withDelay: retryResult.delay) + } + } + } + } + + return self + } + + /// Adds a handler to be called once the request has finished. + /// + /// - Parameters: + /// - queue: The queue on which the completion handler is dispatched. `.main` by default + /// - responseSerializer: The response serializer responsible for serializing the request, response, and data. + /// - completionHandler: The code to be executed once the request has finished. + /// + /// - Returns: The request. + @discardableResult + public func response(queue: DispatchQueue = .main, + responseSerializer: Serializer, + completionHandler: @escaping (AFDataResponse) -> Void) + -> Self { + _response(queue: queue, responseSerializer: responseSerializer, completionHandler: completionHandler) + } + + /// Adds a handler to be called once the request has finished. + /// + /// - Parameters: + /// - queue: The queue on which the completion handler is dispatched. `.main` by default + /// - responseSerializer: The response serializer responsible for serializing the request, response, and data. + /// - completionHandler: The code to be executed once the request has finished. + /// + /// - Returns: The request. + @discardableResult + public func response(queue: DispatchQueue = .main, + responseSerializer: Serializer, + completionHandler: @escaping (AFDataResponse) -> Void) + -> Self { + _response(queue: queue, responseSerializer: responseSerializer, completionHandler: completionHandler) + } +} + +extension DownloadRequest { + /// Adds a handler to be called once the request has finished. + /// + /// - Parameters: + /// - queue: The queue on which the completion handler is dispatched. `.main` by default. + /// - completionHandler: The code to be executed once the request has finished. + /// + /// - Returns: The request. + @discardableResult + public func response(queue: DispatchQueue = .main, + completionHandler: @escaping (AFDownloadResponse) -> Void) + -> Self { + appendResponseSerializer { + // Start work that should be on the serialization queue. + let result = AFResult(value: self.fileURL, error: self.error) + // End work that should be on the serialization queue. + + self.underlyingQueue.async { + let response = DownloadResponse(request: self.request, + response: self.response, + fileURL: self.fileURL, + resumeData: self.resumeData, + metrics: self.metrics, + serializationDuration: 0, + result: result) + + self.eventMonitor?.request(self, didParseResponse: response) + + self.responseSerializerDidComplete { queue.async { completionHandler(response) } } + } + } + + return self + } + + private func _response(queue: DispatchQueue = .main, + responseSerializer: Serializer, + completionHandler: @escaping (AFDownloadResponse) -> Void) + -> Self { + appendResponseSerializer { + // Start work that should be on the serialization queue. + let start = ProcessInfo.processInfo.systemUptime + let result: AFResult = Result { + try responseSerializer.serializeDownload(request: self.request, + response: self.response, + fileURL: self.fileURL, + error: self.error) + }.mapError { error in + error.asAFError(or: .responseSerializationFailed(reason: .customSerializationFailed(error: error))) + } + let end = ProcessInfo.processInfo.systemUptime + // End work that should be on the serialization queue. + + self.underlyingQueue.async { + let response = DownloadResponse(request: self.request, + response: self.response, + fileURL: self.fileURL, + resumeData: self.resumeData, + metrics: self.metrics, + serializationDuration: end - start, + result: result) + + self.eventMonitor?.request(self, didParseResponse: response) + + guard let serializerError = result.failure, let delegate = self.delegate else { + self.responseSerializerDidComplete { queue.async { completionHandler(response) } } + return + } + + delegate.retryResult(for: self, dueTo: serializerError) { retryResult in + var didComplete: (() -> Void)? + + defer { + if let didComplete = didComplete { + self.responseSerializerDidComplete { queue.async { didComplete() } } + } + } + + switch retryResult { + case .doNotRetry: + didComplete = { completionHandler(response) } + + case let .doNotRetryWithError(retryError): + let result: AFResult = .failure(retryError.asAFError(orFailWith: "Received retryError was not already AFError")) + + let response = DownloadResponse(request: self.request, + response: self.response, + fileURL: self.fileURL, + resumeData: self.resumeData, + metrics: self.metrics, + serializationDuration: end - start, + result: result) + + didComplete = { completionHandler(response) } + + case .retry, .retryWithDelay: + delegate.retryRequest(self, withDelay: retryResult.delay) + } + } + } + } + + return self + } + + /// Adds a handler to be called once the request has finished. + /// + /// - Parameters: + /// - queue: The queue on which the completion handler is dispatched. `.main` by default. + /// - responseSerializer: The response serializer responsible for serializing the request, response, and data + /// contained in the destination `URL`. + /// - completionHandler: The code to be executed once the request has finished. + /// + /// - Returns: The request. + @discardableResult + public func response(queue: DispatchQueue = .main, + responseSerializer: Serializer, + completionHandler: @escaping (AFDownloadResponse) -> Void) + -> Self { + _response(queue: queue, responseSerializer: responseSerializer, completionHandler: completionHandler) + } + + /// Adds a handler to be called once the request has finished. + /// + /// - Parameters: + /// - queue: The queue on which the completion handler is dispatched. `.main` by default. + /// - responseSerializer: The response serializer responsible for serializing the request, response, and data + /// contained in the destination `URL`. + /// - completionHandler: The code to be executed once the request has finished. + /// + /// - Returns: The request. + @discardableResult + public func response(queue: DispatchQueue = .main, + responseSerializer: Serializer, + completionHandler: @escaping (AFDownloadResponse) -> Void) + -> Self { + _response(queue: queue, responseSerializer: responseSerializer, completionHandler: completionHandler) + } +} + +// MARK: - URL + +/// A `DownloadResponseSerializerProtocol` that performs only `Error` checking and ensures that a downloaded `fileURL` +/// is present. +public struct URLResponseSerializer: DownloadResponseSerializerProtocol { + /// Creates an instance. + public init() {} + + public func serializeDownload(request: URLRequest?, + response: HTTPURLResponse?, + fileURL: URL?, + error: Error?) throws -> URL { + guard error == nil else { throw error! } + + guard let url = fileURL else { + throw AFError.responseSerializationFailed(reason: .inputFileNil) + } + + return url + } +} + +extension DownloadResponseSerializerProtocol where Self == URLResponseSerializer { + /// Provides a `URLResponseSerializer` instance. + public static var url: URLResponseSerializer { URLResponseSerializer() } +} + +extension DownloadRequest { + /// Adds a handler using a `URLResponseSerializer` to be called once the request is finished. + /// + /// - Parameters: + /// - queue: The queue on which the completion handler is called. `.main` by default. + /// - completionHandler: A closure to be executed once the request has finished. + /// + /// - Returns: The request. + @discardableResult + public func responseURL(queue: DispatchQueue = .main, + completionHandler: @escaping (AFDownloadResponse) -> Void) -> Self { + response(queue: queue, responseSerializer: URLResponseSerializer(), completionHandler: completionHandler) + } +} + +// MARK: - Data + +/// A `ResponseSerializer` that performs minimal response checking and returns any response `Data` as-is. By default, a +/// request returning `nil` or no data is considered an error. However, if the request has an `HTTPMethod` or the +/// response has an HTTP status code valid for empty responses, then an empty `Data` value is returned. +public final class DataResponseSerializer: ResponseSerializer { + public let dataPreprocessor: DataPreprocessor + public let emptyResponseCodes: Set + public let emptyRequestMethods: Set + + /// Creates a `DataResponseSerializer` using the provided parameters. + /// + /// - Parameters: + /// - dataPreprocessor: `DataPreprocessor` used to prepare the received `Data` for serialization. + /// - emptyResponseCodes: The HTTP response codes for which empty responses are allowed. `[204, 205]` by default. + /// - emptyRequestMethods: The HTTP request methods for which empty responses are allowed. `[.head]` by default. + public init(dataPreprocessor: DataPreprocessor = DataResponseSerializer.defaultDataPreprocessor, + emptyResponseCodes: Set = DataResponseSerializer.defaultEmptyResponseCodes, + emptyRequestMethods: Set = DataResponseSerializer.defaultEmptyRequestMethods) { + self.dataPreprocessor = dataPreprocessor + self.emptyResponseCodes = emptyResponseCodes + self.emptyRequestMethods = emptyRequestMethods + } + + public func serialize(request: URLRequest?, response: HTTPURLResponse?, data: Data?, error: Error?) throws -> Data { + guard error == nil else { throw error! } + + guard var data = data, !data.isEmpty else { + guard emptyResponseAllowed(forRequest: request, response: response) else { + throw AFError.responseSerializationFailed(reason: .inputDataNilOrZeroLength) + } + + return Data() + } + + data = try dataPreprocessor.preprocess(data) + + return data + } +} + +extension ResponseSerializer where Self == DataResponseSerializer { + /// Provides a default `DataResponseSerializer` instance. + public static var data: DataResponseSerializer { DataResponseSerializer() } + + /// Creates a `DataResponseSerializer` using the provided parameters. + /// + /// - Parameters: + /// - dataPreprocessor: `DataPreprocessor` used to prepare the received `Data` for serialization. + /// - emptyResponseCodes: The HTTP response codes for which empty responses are allowed. `[204, 205]` by default. + /// - emptyRequestMethods: The HTTP request methods for which empty responses are allowed. `[.head]` by default. + /// + /// - Returns: The `DataResponseSerializer`. + public static func data(dataPreprocessor: DataPreprocessor = DataResponseSerializer.defaultDataPreprocessor, + emptyResponseCodes: Set = DataResponseSerializer.defaultEmptyResponseCodes, + emptyRequestMethods: Set = DataResponseSerializer.defaultEmptyRequestMethods) -> DataResponseSerializer { + DataResponseSerializer(dataPreprocessor: dataPreprocessor, + emptyResponseCodes: emptyResponseCodes, + emptyRequestMethods: emptyRequestMethods) + } +} + +extension DataRequest { + /// Adds a handler using a `DataResponseSerializer` to be called once the request has finished. + /// + /// - Parameters: + /// - queue: The queue on which the completion handler is called. `.main` by default. + /// - dataPreprocessor: `DataPreprocessor` which processes the received `Data` before calling the + /// `completionHandler`. `PassthroughPreprocessor()` by default. + /// - emptyResponseCodes: HTTP status codes for which empty responses are always valid. `[204, 205]` by default. + /// - emptyRequestMethods: `HTTPMethod`s for which empty responses are always valid. `[.head]` by default. + /// - completionHandler: A closure to be executed once the request has finished. + /// + /// - Returns: The request. + @discardableResult + public func responseData(queue: DispatchQueue = .main, + dataPreprocessor: DataPreprocessor = DataResponseSerializer.defaultDataPreprocessor, + emptyResponseCodes: Set = DataResponseSerializer.defaultEmptyResponseCodes, + emptyRequestMethods: Set = DataResponseSerializer.defaultEmptyRequestMethods, + completionHandler: @escaping (AFDataResponse) -> Void) -> Self { + response(queue: queue, + responseSerializer: DataResponseSerializer(dataPreprocessor: dataPreprocessor, + emptyResponseCodes: emptyResponseCodes, + emptyRequestMethods: emptyRequestMethods), + completionHandler: completionHandler) + } +} + +extension DownloadRequest { + /// Adds a handler using a `DataResponseSerializer` to be called once the request has finished. + /// + /// - Parameters: + /// - queue: The queue on which the completion handler is called. `.main` by default. + /// - dataPreprocessor: `DataPreprocessor` which processes the received `Data` before calling the + /// `completionHandler`. `PassthroughPreprocessor()` by default. + /// - emptyResponseCodes: HTTP status codes for which empty responses are always valid. `[204, 205]` by default. + /// - emptyRequestMethods: `HTTPMethod`s for which empty responses are always valid. `[.head]` by default. + /// - completionHandler: A closure to be executed once the request has finished. + /// + /// - Returns: The request. + @discardableResult + public func responseData(queue: DispatchQueue = .main, + dataPreprocessor: DataPreprocessor = DataResponseSerializer.defaultDataPreprocessor, + emptyResponseCodes: Set = DataResponseSerializer.defaultEmptyResponseCodes, + emptyRequestMethods: Set = DataResponseSerializer.defaultEmptyRequestMethods, + completionHandler: @escaping (AFDownloadResponse) -> Void) -> Self { + response(queue: queue, + responseSerializer: DataResponseSerializer(dataPreprocessor: dataPreprocessor, + emptyResponseCodes: emptyResponseCodes, + emptyRequestMethods: emptyRequestMethods), + completionHandler: completionHandler) + } +} + +// MARK: - String + +/// A `ResponseSerializer` that decodes the response data as a `String`. By default, a request returning `nil` or no +/// data is considered an error. However, if the request has an `HTTPMethod` or the response has an HTTP status code +/// valid for empty responses, then an empty `String` is returned. +public final class StringResponseSerializer: ResponseSerializer { + public let dataPreprocessor: DataPreprocessor + /// Optional string encoding used to validate the response. + public let encoding: String.Encoding? + public let emptyResponseCodes: Set + public let emptyRequestMethods: Set + + /// Creates an instance with the provided values. + /// + /// - Parameters: + /// - dataPreprocessor: `DataPreprocessor` used to prepare the received `Data` for serialization. + /// - encoding: A string encoding. Defaults to `nil`, in which case the encoding will be determined + /// from the server response, falling back to the default HTTP character set, `ISO-8859-1`. + /// - emptyResponseCodes: The HTTP response codes for which empty responses are allowed. `[204, 205]` by default. + /// - emptyRequestMethods: The HTTP request methods for which empty responses are allowed. `[.head]` by default. + public init(dataPreprocessor: DataPreprocessor = StringResponseSerializer.defaultDataPreprocessor, + encoding: String.Encoding? = nil, + emptyResponseCodes: Set = StringResponseSerializer.defaultEmptyResponseCodes, + emptyRequestMethods: Set = StringResponseSerializer.defaultEmptyRequestMethods) { + self.dataPreprocessor = dataPreprocessor + self.encoding = encoding + self.emptyResponseCodes = emptyResponseCodes + self.emptyRequestMethods = emptyRequestMethods + } + + public func serialize(request: URLRequest?, response: HTTPURLResponse?, data: Data?, error: Error?) throws -> String { + guard error == nil else { throw error! } + + guard var data = data, !data.isEmpty else { + guard emptyResponseAllowed(forRequest: request, response: response) else { + throw AFError.responseSerializationFailed(reason: .inputDataNilOrZeroLength) + } + + return "" + } + + data = try dataPreprocessor.preprocess(data) + + var convertedEncoding = encoding + + if let encodingName = response?.textEncodingName, convertedEncoding == nil { + convertedEncoding = String.Encoding(ianaCharsetName: encodingName) + } + + let actualEncoding = convertedEncoding ?? .isoLatin1 + + guard let string = String(data: data, encoding: actualEncoding) else { + throw AFError.responseSerializationFailed(reason: .stringSerializationFailed(encoding: actualEncoding)) + } + + return string + } +} + +extension ResponseSerializer where Self == StringResponseSerializer { + /// Provides a default `StringResponseSerializer` instance. + public static var string: StringResponseSerializer { StringResponseSerializer() } + + /// Creates a `StringResponseSerializer` with the provided values. + /// + /// - Parameters: + /// - dataPreprocessor: `DataPreprocessor` used to prepare the received `Data` for serialization. + /// - encoding: A string encoding. Defaults to `nil`, in which case the encoding will be determined + /// from the server response, falling back to the default HTTP character set, `ISO-8859-1`. + /// - emptyResponseCodes: The HTTP response codes for which empty responses are allowed. `[204, 205]` by default. + /// - emptyRequestMethods: The HTTP request methods for which empty responses are allowed. `[.head]` by default. + /// + /// - Returns: The `StringResponseSerializer`. + public static func string(dataPreprocessor: DataPreprocessor = StringResponseSerializer.defaultDataPreprocessor, + encoding: String.Encoding? = nil, + emptyResponseCodes: Set = StringResponseSerializer.defaultEmptyResponseCodes, + emptyRequestMethods: Set = StringResponseSerializer.defaultEmptyRequestMethods) -> StringResponseSerializer { + StringResponseSerializer(dataPreprocessor: dataPreprocessor, + encoding: encoding, + emptyResponseCodes: emptyResponseCodes, + emptyRequestMethods: emptyRequestMethods) + } +} + +extension DataRequest { + /// Adds a handler using a `StringResponseSerializer` to be called once the request has finished. + /// + /// - Parameters: + /// - queue: The queue on which the completion handler is dispatched. `.main` by default. + /// - dataPreprocessor: `DataPreprocessor` which processes the received `Data` before calling the + /// `completionHandler`. `PassthroughPreprocessor()` by default. + /// - encoding: The string encoding. Defaults to `nil`, in which case the encoding will be determined + /// from the server response, falling back to the default HTTP character set, `ISO-8859-1`. + /// - emptyResponseCodes: HTTP status codes for which empty responses are always valid. `[204, 205]` by default. + /// - emptyRequestMethods: `HTTPMethod`s for which empty responses are always valid. `[.head]` by default. + /// - completionHandler: A closure to be executed once the request has finished. + /// + /// - Returns: The request. + @discardableResult + public func responseString(queue: DispatchQueue = .main, + dataPreprocessor: DataPreprocessor = StringResponseSerializer.defaultDataPreprocessor, + encoding: String.Encoding? = nil, + emptyResponseCodes: Set = StringResponseSerializer.defaultEmptyResponseCodes, + emptyRequestMethods: Set = StringResponseSerializer.defaultEmptyRequestMethods, + completionHandler: @escaping (AFDataResponse) -> Void) -> Self { + response(queue: queue, + responseSerializer: StringResponseSerializer(dataPreprocessor: dataPreprocessor, + encoding: encoding, + emptyResponseCodes: emptyResponseCodes, + emptyRequestMethods: emptyRequestMethods), + completionHandler: completionHandler) + } +} + +extension DownloadRequest { + /// Adds a handler using a `StringResponseSerializer` to be called once the request has finished. + /// + /// - Parameters: + /// - queue: The queue on which the completion handler is dispatched. `.main` by default. + /// - dataPreprocessor: `DataPreprocessor` which processes the received `Data` before calling the + /// `completionHandler`. `PassthroughPreprocessor()` by default. + /// - encoding: The string encoding. Defaults to `nil`, in which case the encoding will be determined + /// from the server response, falling back to the default HTTP character set, `ISO-8859-1`. + /// - emptyResponseCodes: HTTP status codes for which empty responses are always valid. `[204, 205]` by default. + /// - emptyRequestMethods: `HTTPMethod`s for which empty responses are always valid. `[.head]` by default. + /// - completionHandler: A closure to be executed once the request has finished. + /// + /// - Returns: The request. + @discardableResult + public func responseString(queue: DispatchQueue = .main, + dataPreprocessor: DataPreprocessor = StringResponseSerializer.defaultDataPreprocessor, + encoding: String.Encoding? = nil, + emptyResponseCodes: Set = StringResponseSerializer.defaultEmptyResponseCodes, + emptyRequestMethods: Set = StringResponseSerializer.defaultEmptyRequestMethods, + completionHandler: @escaping (AFDownloadResponse) -> Void) -> Self { + response(queue: queue, + responseSerializer: StringResponseSerializer(dataPreprocessor: dataPreprocessor, + encoding: encoding, + emptyResponseCodes: emptyResponseCodes, + emptyRequestMethods: emptyRequestMethods), + completionHandler: completionHandler) + } +} + +// MARK: - JSON + +/// A `ResponseSerializer` that decodes the response data using `JSONSerialization`. By default, a request returning +/// `nil` or no data is considered an error. However, if the request has an `HTTPMethod` or the response has an +/// HTTP status code valid for empty responses, then an `NSNull` value is returned. +@available(*, deprecated, message: "JSONResponseSerializer deprecated and will be removed in Alamofire 6. Use DecodableResponseSerializer instead.") +public final class JSONResponseSerializer: ResponseSerializer { + public let dataPreprocessor: DataPreprocessor + public let emptyResponseCodes: Set + public let emptyRequestMethods: Set + /// `JSONSerialization.ReadingOptions` used when serializing a response. + public let options: JSONSerialization.ReadingOptions + + /// Creates an instance with the provided values. + /// + /// - Parameters: + /// - dataPreprocessor: `DataPreprocessor` used to prepare the received `Data` for serialization. + /// - emptyResponseCodes: The HTTP response codes for which empty responses are allowed. `[204, 205]` by default. + /// - emptyRequestMethods: The HTTP request methods for which empty responses are allowed. `[.head]` by default. + /// - options: The options to use. `.allowFragments` by default. + public init(dataPreprocessor: DataPreprocessor = JSONResponseSerializer.defaultDataPreprocessor, + emptyResponseCodes: Set = JSONResponseSerializer.defaultEmptyResponseCodes, + emptyRequestMethods: Set = JSONResponseSerializer.defaultEmptyRequestMethods, + options: JSONSerialization.ReadingOptions = .allowFragments) { + self.dataPreprocessor = dataPreprocessor + self.emptyResponseCodes = emptyResponseCodes + self.emptyRequestMethods = emptyRequestMethods + self.options = options + } + + public func serialize(request: URLRequest?, response: HTTPURLResponse?, data: Data?, error: Error?) throws -> Any { + guard error == nil else { throw error! } + + guard var data = data, !data.isEmpty else { + guard emptyResponseAllowed(forRequest: request, response: response) else { + throw AFError.responseSerializationFailed(reason: .inputDataNilOrZeroLength) + } + + return NSNull() + } + + data = try dataPreprocessor.preprocess(data) + + do { + return try JSONSerialization.jsonObject(with: data, options: options) + } catch { + throw AFError.responseSerializationFailed(reason: .jsonSerializationFailed(error: error)) + } + } +} + +extension DataRequest { + /// Adds a handler using a `JSONResponseSerializer` to be called once the request has finished. + /// + /// - Parameters: + /// - queue: The queue on which the completion handler is dispatched. `.main` by default. + /// - dataPreprocessor: `DataPreprocessor` which processes the received `Data` before calling the + /// `completionHandler`. `PassthroughPreprocessor()` by default. + /// - emptyResponseCodes: HTTP status codes for which empty responses are always valid. `[204, 205]` by default. + /// - emptyRequestMethods: `HTTPMethod`s for which empty responses are always valid. `[.head]` by default. + /// - options: `JSONSerialization.ReadingOptions` used when parsing the response. `.allowFragments` + /// by default. + /// - completionHandler: A closure to be executed once the request has finished. + /// + /// - Returns: The request. + @available(*, deprecated, message: "responseJSON deprecated and will be removed in Alamofire 6. Use responseDecodable instead.") + @discardableResult + public func responseJSON(queue: DispatchQueue = .main, + dataPreprocessor: DataPreprocessor = JSONResponseSerializer.defaultDataPreprocessor, + emptyResponseCodes: Set = JSONResponseSerializer.defaultEmptyResponseCodes, + emptyRequestMethods: Set = JSONResponseSerializer.defaultEmptyRequestMethods, + options: JSONSerialization.ReadingOptions = .allowFragments, + completionHandler: @escaping (AFDataResponse) -> Void) -> Self { + response(queue: queue, + responseSerializer: JSONResponseSerializer(dataPreprocessor: dataPreprocessor, + emptyResponseCodes: emptyResponseCodes, + emptyRequestMethods: emptyRequestMethods, + options: options), + completionHandler: completionHandler) + } +} + +extension DownloadRequest { + /// Adds a handler using a `JSONResponseSerializer` to be called once the request has finished. + /// + /// - Parameters: + /// - queue: The queue on which the completion handler is dispatched. `.main` by default. + /// - dataPreprocessor: `DataPreprocessor` which processes the received `Data` before calling the + /// `completionHandler`. `PassthroughPreprocessor()` by default. + /// - emptyResponseCodes: HTTP status codes for which empty responses are always valid. `[204, 205]` by default. + /// - emptyRequestMethods: `HTTPMethod`s for which empty responses are always valid. `[.head]` by default. + /// - options: `JSONSerialization.ReadingOptions` used when parsing the response. `.allowFragments` + /// by default. + /// - completionHandler: A closure to be executed once the request has finished. + /// + /// - Returns: The request. + @available(*, deprecated, message: "responseJSON deprecated and will be removed in Alamofire 6. Use responseDecodable instead.") + @discardableResult + public func responseJSON(queue: DispatchQueue = .main, + dataPreprocessor: DataPreprocessor = JSONResponseSerializer.defaultDataPreprocessor, + emptyResponseCodes: Set = JSONResponseSerializer.defaultEmptyResponseCodes, + emptyRequestMethods: Set = JSONResponseSerializer.defaultEmptyRequestMethods, + options: JSONSerialization.ReadingOptions = .allowFragments, + completionHandler: @escaping (AFDownloadResponse) -> Void) -> Self { + response(queue: queue, + responseSerializer: JSONResponseSerializer(dataPreprocessor: dataPreprocessor, + emptyResponseCodes: emptyResponseCodes, + emptyRequestMethods: emptyRequestMethods, + options: options), + completionHandler: completionHandler) + } +} + +// MARK: - Empty + +/// Protocol representing an empty response. Use `T.emptyValue()` to get an instance. +public protocol EmptyResponse { + /// Empty value for the conforming type. + /// + /// - Returns: Value of `Self` to use for empty values. + static func emptyValue() -> Self +} + +/// Type representing an empty value. Use `Empty.value` to get the static instance. +public struct Empty: Codable { + /// Static `Empty` instance used for all `Empty` responses. + public static let value = Empty() +} + +extension Empty: EmptyResponse { + public static func emptyValue() -> Empty { + value + } +} + +// MARK: - DataDecoder Protocol + +/// Any type which can decode `Data` into a `Decodable` type. +public protocol DataDecoder { + /// Decode `Data` into the provided type. + /// + /// - Parameters: + /// - type: The `Type` to be decoded. + /// - data: The `Data` to be decoded. + /// + /// - Returns: The decoded value of type `D`. + /// - Throws: Any error that occurs during decode. + func decode(_ type: D.Type, from data: Data) throws -> D +} + +/// `JSONDecoder` automatically conforms to `DataDecoder`. +extension JSONDecoder: DataDecoder {} +/// `PropertyListDecoder` automatically conforms to `DataDecoder`. +extension PropertyListDecoder: DataDecoder {} + +// MARK: - Decodable + +/// A `ResponseSerializer` that decodes the response data as a generic value using any type that conforms to +/// `DataDecoder`. By default, this is an instance of `JSONDecoder`. Additionally, a request returning `nil` or no data +/// is considered an error. However, if the request has an `HTTPMethod` or the response has an HTTP status code valid +/// for empty responses then an empty value will be returned. If the decoded type conforms to `EmptyResponse`, the +/// type's `emptyValue()` will be returned. If the decoded type is `Empty`, the `.value` instance is returned. If the +/// decoded type *does not* conform to `EmptyResponse` and isn't `Empty`, an error will be produced. +public final class DecodableResponseSerializer: ResponseSerializer { + public let dataPreprocessor: DataPreprocessor + /// The `DataDecoder` instance used to decode responses. + public let decoder: DataDecoder + public let emptyResponseCodes: Set + public let emptyRequestMethods: Set + + /// Creates an instance using the values provided. + /// + /// - Parameters: + /// - dataPreprocessor: `DataPreprocessor` used to prepare the received `Data` for serialization. + /// - decoder: The `DataDecoder`. `JSONDecoder()` by default. + /// - emptyResponseCodes: The HTTP response codes for which empty responses are allowed. `[204, 205]` by default. + /// - emptyRequestMethods: The HTTP request methods for which empty responses are allowed. `[.head]` by default. + public init(dataPreprocessor: DataPreprocessor = DecodableResponseSerializer.defaultDataPreprocessor, + decoder: DataDecoder = JSONDecoder(), + emptyResponseCodes: Set = DecodableResponseSerializer.defaultEmptyResponseCodes, + emptyRequestMethods: Set = DecodableResponseSerializer.defaultEmptyRequestMethods) { + self.dataPreprocessor = dataPreprocessor + self.decoder = decoder + self.emptyResponseCodes = emptyResponseCodes + self.emptyRequestMethods = emptyRequestMethods + } + + public func serialize(request: URLRequest?, response: HTTPURLResponse?, data: Data?, error: Error?) throws -> T { + guard error == nil else { throw error! } + + guard var data = data, !data.isEmpty else { + guard emptyResponseAllowed(forRequest: request, response: response) else { + throw AFError.responseSerializationFailed(reason: .inputDataNilOrZeroLength) + } + + guard let emptyResponseType = T.self as? EmptyResponse.Type, let emptyValue = emptyResponseType.emptyValue() as? T else { + throw AFError.responseSerializationFailed(reason: .invalidEmptyResponse(type: "\(T.self)")) + } + + return emptyValue + } + + data = try dataPreprocessor.preprocess(data) + + do { + return try decoder.decode(T.self, from: data) + } catch { + throw AFError.responseSerializationFailed(reason: .decodingFailed(error: error)) + } + } +} + +extension ResponseSerializer { + /// Creates a `DecodableResponseSerializer` using the values provided. + /// + /// - Parameters: + /// - type: `Decodable` type to decode from response data. + /// - dataPreprocessor: `DataPreprocessor` used to prepare the received `Data` for serialization. + /// - decoder: The `DataDecoder`. `JSONDecoder()` by default. + /// - emptyResponseCodes: The HTTP response codes for which empty responses are allowed. `[204, 205]` by default. + /// - emptyRequestMethods: The HTTP request methods for which empty responses are allowed. `[.head]` by default. + /// + /// - Returns: The `DecodableResponseSerializer`. + public static func decodable(of type: T.Type, + dataPreprocessor: DataPreprocessor = DecodableResponseSerializer.defaultDataPreprocessor, + decoder: DataDecoder = JSONDecoder(), + emptyResponseCodes: Set = DecodableResponseSerializer.defaultEmptyResponseCodes, + emptyRequestMethods: Set = DecodableResponseSerializer.defaultEmptyRequestMethods) -> DecodableResponseSerializer where Self == DecodableResponseSerializer { + DecodableResponseSerializer(dataPreprocessor: dataPreprocessor, + decoder: decoder, + emptyResponseCodes: emptyResponseCodes, + emptyRequestMethods: emptyRequestMethods) + } +} + +extension DataRequest { + /// Adds a handler using a `DecodableResponseSerializer` to be called once the request has finished. + /// + /// - Parameters: + /// - type: `Decodable` type to decode from response data. + /// - queue: The queue on which the completion handler is dispatched. `.main` by default. + /// - dataPreprocessor: `DataPreprocessor` which processes the received `Data` before calling the + /// `completionHandler`. `PassthroughPreprocessor()` by default. + /// - decoder: `DataDecoder` to use to decode the response. `JSONDecoder()` by default. + /// - emptyResponseCodes: HTTP status codes for which empty responses are always valid. `[204, 205]` by default. + /// - emptyRequestMethods: `HTTPMethod`s for which empty responses are always valid. `[.head]` by default. + /// - completionHandler: A closure to be executed once the request has finished. + /// + /// - Returns: The request. + @discardableResult + public func responseDecodable(of type: T.Type = T.self, + queue: DispatchQueue = .main, + dataPreprocessor: DataPreprocessor = DecodableResponseSerializer.defaultDataPreprocessor, + decoder: DataDecoder = JSONDecoder(), + emptyResponseCodes: Set = DecodableResponseSerializer.defaultEmptyResponseCodes, + emptyRequestMethods: Set = DecodableResponseSerializer.defaultEmptyRequestMethods, + completionHandler: @escaping (AFDataResponse) -> Void) -> Self { + response(queue: queue, + responseSerializer: DecodableResponseSerializer(dataPreprocessor: dataPreprocessor, + decoder: decoder, + emptyResponseCodes: emptyResponseCodes, + emptyRequestMethods: emptyRequestMethods), + completionHandler: completionHandler) + } +} + +extension DownloadRequest { + /// Adds a handler using a `DecodableResponseSerializer` to be called once the request has finished. + /// + /// - Parameters: + /// - type: `Decodable` type to decode from response data. + /// - queue: The queue on which the completion handler is dispatched. `.main` by default. + /// - dataPreprocessor: `DataPreprocessor` which processes the received `Data` before calling the + /// `completionHandler`. `PassthroughPreprocessor()` by default. + /// - decoder: `DataDecoder` to use to decode the response. `JSONDecoder()` by default. + /// - emptyResponseCodes: HTTP status codes for which empty responses are always valid. `[204, 205]` by default. + /// - emptyRequestMethods: `HTTPMethod`s for which empty responses are always valid. `[.head]` by default. + /// - completionHandler: A closure to be executed once the request has finished. + /// + /// - Returns: The request. + @discardableResult + public func responseDecodable(of type: T.Type = T.self, + queue: DispatchQueue = .main, + dataPreprocessor: DataPreprocessor = DecodableResponseSerializer.defaultDataPreprocessor, + decoder: DataDecoder = JSONDecoder(), + emptyResponseCodes: Set = DecodableResponseSerializer.defaultEmptyResponseCodes, + emptyRequestMethods: Set = DecodableResponseSerializer.defaultEmptyRequestMethods, + completionHandler: @escaping (AFDownloadResponse) -> Void) -> Self { + response(queue: queue, + responseSerializer: DecodableResponseSerializer(dataPreprocessor: dataPreprocessor, + decoder: decoder, + emptyResponseCodes: emptyResponseCodes, + emptyRequestMethods: emptyRequestMethods), + completionHandler: completionHandler) + } +} + +// MARK: - DataStreamRequest + +/// A type which can serialize incoming `Data`. +public protocol DataStreamSerializer { + /// Type produced from the serialized `Data`. + associatedtype SerializedObject + + /// Serializes incoming `Data` into a `SerializedObject` value. + /// + /// - Parameter data: `Data` to be serialized. + /// + /// - Throws: Any error produced during serialization. + func serialize(_ data: Data) throws -> SerializedObject +} + +/// `DataStreamSerializer` which uses the provided `DataPreprocessor` and `DataDecoder` to serialize the incoming `Data`. +public struct DecodableStreamSerializer: DataStreamSerializer { + /// `DataDecoder` used to decode incoming `Data`. + public let decoder: DataDecoder + /// `DataPreprocessor` incoming `Data` is passed through before being passed to the `DataDecoder`. + public let dataPreprocessor: DataPreprocessor + + /// Creates an instance with the provided `DataDecoder` and `DataPreprocessor`. + /// - Parameters: + /// - decoder: ` DataDecoder` used to decode incoming `Data`. `JSONDecoder()` by default. + /// - dataPreprocessor: `DataPreprocessor` used to process incoming `Data` before it's passed through the + /// `decoder`. `PassthroughPreprocessor()` by default. + public init(decoder: DataDecoder = JSONDecoder(), dataPreprocessor: DataPreprocessor = PassthroughPreprocessor()) { + self.decoder = decoder + self.dataPreprocessor = dataPreprocessor + } + + public func serialize(_ data: Data) throws -> T { + let processedData = try dataPreprocessor.preprocess(data) + do { + return try decoder.decode(T.self, from: processedData) + } catch { + throw AFError.responseSerializationFailed(reason: .decodingFailed(error: error)) + } + } +} + +/// `DataStreamSerializer` which performs no serialization on incoming `Data`. +public struct PassthroughStreamSerializer: DataStreamSerializer { + /// Creates an instance. + public init() {} + + public func serialize(_ data: Data) throws -> Data { data } +} + +/// `DataStreamSerializer` which serializes incoming stream `Data` into `UTF8`-decoded `String` values. +public struct StringStreamSerializer: DataStreamSerializer { + /// Creates an instance. + public init() {} + + public func serialize(_ data: Data) throws -> String { + String(decoding: data, as: UTF8.self) + } +} + +extension DataStreamSerializer { + /// Creates a `DecodableStreamSerializer` instance with the provided `DataDecoder` and `DataPreprocessor`. + /// + /// - Parameters: + /// - type: `Decodable` type to decode from stream data. + /// - decoder: ` DataDecoder` used to decode incoming `Data`. `JSONDecoder()` by default. + /// - dataPreprocessor: `DataPreprocessor` used to process incoming `Data` before it's passed through the + /// `decoder`. `PassthroughPreprocessor()` by default. + public static func decodable(of type: T.Type, + decoder: DataDecoder = JSONDecoder(), + dataPreprocessor: DataPreprocessor = PassthroughPreprocessor()) -> Self where Self == DecodableStreamSerializer { + DecodableStreamSerializer(decoder: decoder, dataPreprocessor: dataPreprocessor) + } +} + +extension DataStreamSerializer where Self == PassthroughStreamSerializer { + /// Provides a `PassthroughStreamSerializer` instance. + public static var passthrough: PassthroughStreamSerializer { PassthroughStreamSerializer() } +} + +extension DataStreamSerializer where Self == StringStreamSerializer { + /// Provides a `StringStreamSerializer` instance. + public static var string: StringStreamSerializer { StringStreamSerializer() } +} + +extension DataStreamRequest { + /// Adds a `StreamHandler` which performs no parsing on incoming `Data`. + /// + /// - Parameters: + /// - queue: `DispatchQueue` on which to perform `StreamHandler` closure. + /// - stream: `StreamHandler` closure called as `Data` is received. May be called multiple times. + /// + /// - Returns: The `DataStreamRequest`. + @discardableResult + public func responseStream(on queue: DispatchQueue = .main, stream: @escaping Handler) -> Self { + let parser = { [unowned self] (data: Data) in + queue.async { + self.capturingError { + try stream(.init(event: .stream(.success(data)), token: .init(self))) + } + + self.updateAndCompleteIfPossible() + } + } + + $streamMutableState.write { $0.streams.append(parser) } + appendStreamCompletion(on: queue, stream: stream) + + return self + } + + /// Adds a `StreamHandler` which uses the provided `DataStreamSerializer` to process incoming `Data`. + /// + /// - Parameters: + /// - serializer: `DataStreamSerializer` used to process incoming `Data`. Its work is done on the `serializationQueue`. + /// - queue: `DispatchQueue` on which to perform `StreamHandler` closure. + /// - stream: `StreamHandler` closure called as `Data` is received. May be called multiple times. + /// + /// - Returns: The `DataStreamRequest`. + @discardableResult + public func responseStream(using serializer: Serializer, + on queue: DispatchQueue = .main, + stream: @escaping Handler) -> Self { + let parser = { [unowned self] (data: Data) in + serializationQueue.async { + // Start work on serialization queue. + let result = Result { try serializer.serialize(data) } + .mapError { $0.asAFError(or: .responseSerializationFailed(reason: .customSerializationFailed(error: $0))) } + // End work on serialization queue. + self.underlyingQueue.async { + self.eventMonitor?.request(self, didParseStream: result) + + if result.isFailure, self.automaticallyCancelOnStreamError { + self.cancel() + } + + queue.async { + self.capturingError { + try stream(.init(event: .stream(result), token: .init(self))) + } + + self.updateAndCompleteIfPossible() + } + } + } + } + + $streamMutableState.write { $0.streams.append(parser) } + appendStreamCompletion(on: queue, stream: stream) + + return self + } + + /// Adds a `StreamHandler` which parses incoming `Data` as a UTF8 `String`. + /// + /// - Parameters: + /// - queue: `DispatchQueue` on which to perform `StreamHandler` closure. + /// - stream: `StreamHandler` closure called as `Data` is received. May be called multiple times. + /// + /// - Returns: The `DataStreamRequest`. + @discardableResult + public func responseStreamString(on queue: DispatchQueue = .main, + stream: @escaping Handler) -> Self { + let parser = { [unowned self] (data: Data) in + serializationQueue.async { + // Start work on serialization queue. + let string = String(decoding: data, as: UTF8.self) + // End work on serialization queue. + self.underlyingQueue.async { + self.eventMonitor?.request(self, didParseStream: .success(string)) + + queue.async { + self.capturingError { + try stream(.init(event: .stream(.success(string)), token: .init(self))) + } + + self.updateAndCompleteIfPossible() + } + } + } + } + + $streamMutableState.write { $0.streams.append(parser) } + appendStreamCompletion(on: queue, stream: stream) + + return self + } + + private func updateAndCompleteIfPossible() { + $streamMutableState.write { state in + state.numberOfExecutingStreams -= 1 + + guard state.numberOfExecutingStreams == 0, !state.enqueuedCompletionEvents.isEmpty else { return } + + let completionEvents = state.enqueuedCompletionEvents + self.underlyingQueue.async { completionEvents.forEach { $0() } } + state.enqueuedCompletionEvents.removeAll() + } + } + + /// Adds a `StreamHandler` which parses incoming `Data` using the provided `DataDecoder`. + /// + /// - Parameters: + /// - type: `Decodable` type to parse incoming `Data` into. + /// - queue: `DispatchQueue` on which to perform `StreamHandler` closure. + /// - decoder: `DataDecoder` used to decode the incoming `Data`. + /// - preprocessor: `DataPreprocessor` used to process the incoming `Data` before it's passed to the `decoder`. + /// - stream: `StreamHandler` closure called as `Data` is received. May be called multiple times. + /// + /// - Returns: The `DataStreamRequest`. + @discardableResult + public func responseStreamDecodable(of type: T.Type = T.self, + on queue: DispatchQueue = .main, + using decoder: DataDecoder = JSONDecoder(), + preprocessor: DataPreprocessor = PassthroughPreprocessor(), + stream: @escaping Handler) -> Self { + responseStream(using: DecodableStreamSerializer(decoder: decoder, dataPreprocessor: preprocessor), + stream: stream) + } +} diff --git a/Pods/Alamofire/Source/Result+Alamofire.swift b/Pods/Alamofire/Source/Result+Alamofire.swift new file mode 100644 index 0000000..39ac286 --- /dev/null +++ b/Pods/Alamofire/Source/Result+Alamofire.swift @@ -0,0 +1,120 @@ +// +// Result+Alamofire.swift +// +// Copyright (c) 2019 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 + +/// Default type of `Result` returned by Alamofire, with an `AFError` `Failure` type. +public typealias AFResult = Result + +// MARK: - Internal APIs + +extension Result { + /// Returns whether the instance is `.success`. + var isSuccess: Bool { + guard case .success = self else { return false } + return true + } + + /// Returns whether the instance is `.failure`. + var isFailure: Bool { + !isSuccess + } + + /// Returns the associated value if the result is a success, `nil` otherwise. + var success: Success? { + guard case let .success(value) = self else { return nil } + return value + } + + /// Returns the associated error value if the result is a failure, `nil` otherwise. + var failure: Failure? { + guard case let .failure(error) = self else { return nil } + return error + } + + /// Initializes a `Result` from value or error. Returns `.failure` if the error is non-nil, `.success` otherwise. + /// + /// - Parameters: + /// - value: A value. + /// - error: An `Error`. + init(value: Success, error: Failure?) { + if let error = error { + self = .failure(error) + } else { + self = .success(value) + } + } + + /// Evaluates the specified closure when the `Result` is a success, passing the unwrapped value as a parameter. + /// + /// Use the `tryMap` method with a closure that may throw an error. For example: + /// + /// let possibleData: Result = .success(Data(...)) + /// let possibleObject = possibleData.tryMap { + /// 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. + func tryMap(_ transform: (Success) throws -> NewSuccess) -> Result { + switch self { + case let .success(value): + do { + return try .success(transform(value)) + } catch { + return .failure(error) + } + case let .failure(error): + return .failure(error) + } + } + + /// Evaluates the specified closure when the `Result` is a failure, passing the unwrapped error as a parameter. + /// + /// Use the `tryMapError` function with a closure that may throw an error. For example: + /// + /// let possibleData: Result = .success(Data(...)) + /// let possibleObject = possibleData.tryMapError { + /// 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 success. + func tryMapError(_ transform: (Failure) throws -> NewFailure) -> Result { + switch self { + case let .failure(error): + do { + return try .failure(transform(error)) + } catch { + return .failure(error) + } + case let .success(value): + return .success(value) + } + } +} diff --git a/Pods/Alamofire/Source/RetryPolicy.swift b/Pods/Alamofire/Source/RetryPolicy.swift new file mode 100644 index 0000000..bb52c6c --- /dev/null +++ b/Pods/Alamofire/Source/RetryPolicy.swift @@ -0,0 +1,430 @@ +// +// RetryPolicy.swift +// +// Copyright (c) 2019-2020 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 retry policy that retries requests using an exponential backoff for allowed HTTP methods and HTTP status codes +/// as well as certain types of networking errors. +open class RetryPolicy: RequestInterceptor { + /// The default retry limit for retry policies. + public static let defaultRetryLimit: UInt = 2 + + /// The default exponential backoff base for retry policies (must be a minimum of 2). + public static let defaultExponentialBackoffBase: UInt = 2 + + /// The default exponential backoff scale for retry policies. + public static let defaultExponentialBackoffScale: Double = 0.5 + + /// The default HTTP methods to retry. + /// See [RFC 2616 - Section 9.1.2](https://www.w3.org/Protocols/rfc2616/rfc2616-sec9.html) for more information. + public static let defaultRetryableHTTPMethods: Set = [.delete, // [Delete](https://www.w3.org/Protocols/rfc2616/rfc2616-sec9.html#sec9.7) - not always idempotent + .get, // [GET](https://www.w3.org/Protocols/rfc2616/rfc2616-sec9.html#sec9.3) - generally idempotent + .head, // [HEAD](https://www.w3.org/Protocols/rfc2616/rfc2616-sec9.html#sec9.4) - generally idempotent + .options, // [OPTIONS](https://www.w3.org/Protocols/rfc2616/rfc2616-sec9.html#sec9.2) - inherently idempotent + .put, // [PUT](https://www.w3.org/Protocols/rfc2616/rfc2616-sec9.html#sec9.6) - not always idempotent + .trace // [TRACE](https://www.w3.org/Protocols/rfc2616/rfc2616-sec9.html#sec9.8) - inherently idempotent + ] + + /// The default HTTP status codes to retry. + /// See [RFC 2616 - Section 10](https://www.w3.org/Protocols/rfc2616/rfc2616-sec10.html#sec10) for more information. + public static let defaultRetryableHTTPStatusCodes: Set = [408, // [Request Timeout](https://www.w3.org/Protocols/rfc2616/rfc2616-sec10.html#sec10.4.9) + 500, // [Internal Server Error](https://www.w3.org/Protocols/rfc2616/rfc2616-sec10.html#sec10.5.1) + 502, // [Bad Gateway](https://www.w3.org/Protocols/rfc2616/rfc2616-sec10.html#sec10.5.3) + 503, // [Service Unavailable](https://www.w3.org/Protocols/rfc2616/rfc2616-sec10.html#sec10.5.4) + 504 // [Gateway Timeout](https://www.w3.org/Protocols/rfc2616/rfc2616-sec10.html#sec10.5.5) + ] + + /// The default URL error codes to retry. + public static let defaultRetryableURLErrorCodes: Set = [ // [Security] App Transport Security disallowed a connection because there is no secure network connection. + // - [Disabled] ATS settings do not change at runtime. + // .appTransportSecurityRequiresSecureConnection, + + // [System] An app or app extension attempted to connect to a background session that is already connected to a + // process. + // - [Enabled] The other process could release the background session. + .backgroundSessionInUseByAnotherProcess, + + // [System] The shared container identifier of the URL session configuration is needed but has not been set. + // - [Disabled] Cannot change at runtime. + // .backgroundSessionRequiresSharedContainer, + + // [System] The app is suspended or exits while a background data task is processing. + // - [Enabled] App can be foregrounded or launched to recover. + .backgroundSessionWasDisconnected, + + // [Network] The URL Loading system received bad data from the server. + // - [Enabled] Server could return valid data when retrying. + .badServerResponse, + + // [Resource] A malformed URL prevented a URL request from being initiated. + // - [Disabled] URL was most likely constructed incorrectly. + // .badURL, + + // [System] A connection was attempted while a phone call is active on a network that does not support + // simultaneous phone and data communication (EDGE or GPRS). + // - [Enabled] Phone call could be ended to allow request to recover. + .callIsActive, + + // [Client] An asynchronous load has been canceled. + // - [Disabled] Request was cancelled by the client. + // .cancelled, + + // [File System] A download task couldn’t close the downloaded file on disk. + // - [Disabled] File system error is unlikely to recover with retry. + // .cannotCloseFile, + + // [Network] An attempt to connect to a host failed. + // - [Enabled] Server or DNS lookup could recover during retry. + .cannotConnectToHost, + + // [File System] A download task couldn’t create the downloaded file on disk because of an I/O failure. + // - [Disabled] File system error is unlikely to recover with retry. + // .cannotCreateFile, + + // [Data] Content data received during a connection request had an unknown content encoding. + // - [Disabled] Server is unlikely to modify the content encoding during a retry. + // .cannotDecodeContentData, + + // [Data] Content data received during a connection request could not be decoded for a known content encoding. + // - [Disabled] Server is unlikely to modify the content encoding during a retry. + // .cannotDecodeRawData, + + // [Network] The host name for a URL could not be resolved. + // - [Enabled] Server or DNS lookup could recover during retry. + .cannotFindHost, + + // [Network] A request to load an item only from the cache could not be satisfied. + // - [Enabled] Cache could be populated during a retry. + .cannotLoadFromNetwork, + + // [File System] A download task was unable to move a downloaded file on disk. + // - [Disabled] File system error is unlikely to recover with retry. + // .cannotMoveFile, + + // [File System] A download task was unable to open the downloaded file on disk. + // - [Disabled] File system error is unlikely to recover with retry. + // .cannotOpenFile, + + // [Data] A task could not parse a response. + // - [Disabled] Invalid response is unlikely to recover with retry. + // .cannotParseResponse, + + // [File System] A download task was unable to remove a downloaded file from disk. + // - [Disabled] File system error is unlikely to recover with retry. + // .cannotRemoveFile, + + // [File System] A download task was unable to write to the downloaded file on disk. + // - [Disabled] File system error is unlikely to recover with retry. + // .cannotWriteToFile, + + // [Security] A client certificate was rejected. + // - [Disabled] Client certificate is unlikely to change with retry. + // .clientCertificateRejected, + + // [Security] A client certificate was required to authenticate an SSL connection during a request. + // - [Disabled] Client certificate is unlikely to be provided with retry. + // .clientCertificateRequired, + + // [Data] The length of the resource data exceeds the maximum allowed. + // - [Disabled] Resource will likely still exceed the length maximum on retry. + // .dataLengthExceedsMaximum, + + // [System] The cellular network disallowed a connection. + // - [Enabled] WiFi connection could be established during retry. + .dataNotAllowed, + + // [Network] The host address could not be found via DNS lookup. + // - [Enabled] DNS lookup could succeed during retry. + .dnsLookupFailed, + + // [Data] A download task failed to decode an encoded file during the download. + // - [Enabled] Server could correct the decoding issue with retry. + .downloadDecodingFailedMidStream, + + // [Data] A download task failed to decode an encoded file after downloading. + // - [Enabled] Server could correct the decoding issue with retry. + .downloadDecodingFailedToComplete, + + // [File System] A file does not exist. + // - [Disabled] File system error is unlikely to recover with retry. + // .fileDoesNotExist, + + // [File System] A request for an FTP file resulted in the server responding that the file is not a plain file, + // but a directory. + // - [Disabled] FTP directory is not likely to change to a file during a retry. + // .fileIsDirectory, + + // [Network] A redirect loop has been detected or the threshold for number of allowable redirects has been + // exceeded (currently 16). + // - [Disabled] The redirect loop is unlikely to be resolved within the retry window. + // .httpTooManyRedirects, + + // [System] The attempted connection required activating a data context while roaming, but international roaming + // is disabled. + // - [Enabled] WiFi connection could be established during retry. + .internationalRoamingOff, + + // [Connectivity] A client or server connection was severed in the middle of an in-progress load. + // - [Enabled] A network connection could be established during retry. + .networkConnectionLost, + + // [File System] A resource couldn’t be read because of insufficient permissions. + // - [Disabled] Permissions are unlikely to be granted during retry. + // .noPermissionsToReadFile, + + // [Connectivity] A network resource was requested, but an internet connection has not been established and + // cannot be established automatically. + // - [Enabled] A network connection could be established during retry. + .notConnectedToInternet, + + // [Resource] A redirect was specified by way of server response code, but the server did not accompany this + // code with a redirect URL. + // - [Disabled] The redirect URL is unlikely to be supplied during a retry. + // .redirectToNonExistentLocation, + + // [Client] A body stream is needed but the client did not provide one. + // - [Disabled] The client will be unlikely to supply a body stream during retry. + // .requestBodyStreamExhausted, + + // [Resource] A requested resource couldn’t be retrieved. + // - [Disabled] The resource is unlikely to become available during the retry window. + // .resourceUnavailable, + + // [Security] An attempt to establish a secure connection failed for reasons that can’t be expressed more + // specifically. + // - [Enabled] The secure connection could be established during a retry given the lack of specificity + // provided by the error. + .secureConnectionFailed, + + // [Security] A server certificate had a date which indicates it has expired, or is not yet valid. + // - [Enabled] The server certificate could become valid within the retry window. + .serverCertificateHasBadDate, + + // [Security] A server certificate was not signed by any root server. + // - [Disabled] The server certificate is unlikely to change during the retry window. + // .serverCertificateHasUnknownRoot, + + // [Security] A server certificate is not yet valid. + // - [Enabled] The server certificate could become valid within the retry window. + .serverCertificateNotYetValid, + + // [Security] A server certificate was signed by a root server that isn’t trusted. + // - [Disabled] The server certificate is unlikely to become trusted within the retry window. + // .serverCertificateUntrusted, + + // [Network] An asynchronous operation timed out. + // - [Enabled] The request timed out for an unknown reason and should be retried. + .timedOut + + // [System] The URL Loading System encountered an error that it can’t interpret. + // - [Disabled] The error could not be interpreted and is unlikely to be recovered from during a retry. + // .unknown, + + // [Resource] A properly formed URL couldn’t be handled by the framework. + // - [Disabled] The URL is unlikely to change during a retry. + // .unsupportedURL, + + // [Client] Authentication is required to access a resource. + // - [Disabled] The user authentication is unlikely to be provided by retrying. + // .userAuthenticationRequired, + + // [Client] An asynchronous request for authentication has been canceled by the user. + // - [Disabled] The user cancelled authentication and explicitly took action to not retry. + // .userCancelledAuthentication, + + // [Resource] A server reported that a URL has a non-zero content length, but terminated the network connection + // gracefully without sending any data. + // - [Disabled] The server is unlikely to provide data during the retry window. + // .zeroByteResource, + ] + + /// The total number of times the request is allowed to be retried. + public let retryLimit: UInt + + /// The base of the exponential backoff policy (should always be greater than or equal to 2). + public let exponentialBackoffBase: UInt + + /// The scale of the exponential backoff. + public let exponentialBackoffScale: Double + + /// The HTTP methods that are allowed to be retried. + public let retryableHTTPMethods: Set + + /// The HTTP status codes that are automatically retried by the policy. + public let retryableHTTPStatusCodes: Set + + /// The URL error codes that are automatically retried by the policy. + public let retryableURLErrorCodes: Set + + /// Creates a `RetryPolicy` from the specified parameters. + /// + /// - Parameters: + /// - retryLimit: The total number of times the request is allowed to be retried. `2` by default. + /// - exponentialBackoffBase: The base of the exponential backoff policy. `2` by default. + /// - exponentialBackoffScale: The scale of the exponential backoff. `0.5` by default. + /// - retryableHTTPMethods: The HTTP methods that are allowed to be retried. + /// `RetryPolicy.defaultRetryableHTTPMethods` by default. + /// - retryableHTTPStatusCodes: The HTTP status codes that are automatically retried by the policy. + /// `RetryPolicy.defaultRetryableHTTPStatusCodes` by default. + /// - retryableURLErrorCodes: The URL error codes that are automatically retried by the policy. + /// `RetryPolicy.defaultRetryableURLErrorCodes` by default. + public init(retryLimit: UInt = RetryPolicy.defaultRetryLimit, + exponentialBackoffBase: UInt = RetryPolicy.defaultExponentialBackoffBase, + exponentialBackoffScale: Double = RetryPolicy.defaultExponentialBackoffScale, + retryableHTTPMethods: Set = RetryPolicy.defaultRetryableHTTPMethods, + retryableHTTPStatusCodes: Set = RetryPolicy.defaultRetryableHTTPStatusCodes, + retryableURLErrorCodes: Set = RetryPolicy.defaultRetryableURLErrorCodes) { + precondition(exponentialBackoffBase >= 2, "The `exponentialBackoffBase` must be a minimum of 2.") + + self.retryLimit = retryLimit + self.exponentialBackoffBase = exponentialBackoffBase + self.exponentialBackoffScale = exponentialBackoffScale + self.retryableHTTPMethods = retryableHTTPMethods + self.retryableHTTPStatusCodes = retryableHTTPStatusCodes + self.retryableURLErrorCodes = retryableURLErrorCodes + } + + open func retry(_ request: Request, + for session: Session, + dueTo error: Error, + completion: @escaping (RetryResult) -> Void) { + if request.retryCount < retryLimit, shouldRetry(request: request, dueTo: error) { + completion(.retryWithDelay(pow(Double(exponentialBackoffBase), Double(request.retryCount)) * exponentialBackoffScale)) + } else { + completion(.doNotRetry) + } + } + + /// Determines whether or not to retry the provided `Request`. + /// + /// - Parameters: + /// - request: `Request` that failed due to the provided `Error`. + /// - error: `Error` encountered while executing the `Request`. + /// + /// - Returns: `Bool` determining whether or not to retry the `Request`. + open func shouldRetry(request: Request, dueTo error: Error) -> Bool { + guard let httpMethod = request.request?.method, retryableHTTPMethods.contains(httpMethod) else { return false } + + if let statusCode = request.response?.statusCode, retryableHTTPStatusCodes.contains(statusCode) { + return true + } else { + let errorCode = (error as? URLError)?.code + let afErrorCode = (error.asAFError?.underlyingError as? URLError)?.code + + guard let code = errorCode ?? afErrorCode else { return false } + + return retryableURLErrorCodes.contains(code) + } + } +} + +extension RequestInterceptor where Self == RetryPolicy { + /// Provides a default `RetryPolicy` instance. + public static var retryPolicy: RetryPolicy { RetryPolicy() } + + /// Creates an `RetryPolicy` from the specified parameters. + /// + /// - Parameters: + /// - retryLimit: The total number of times the request is allowed to be retried. `2` by default. + /// - exponentialBackoffBase: The base of the exponential backoff policy. `2` by default. + /// - exponentialBackoffScale: The scale of the exponential backoff. `0.5` by default. + /// - retryableHTTPMethods: The HTTP methods that are allowed to be retried. + /// `RetryPolicy.defaultRetryableHTTPMethods` by default. + /// - retryableHTTPStatusCodes: The HTTP status codes that are automatically retried by the policy. + /// `RetryPolicy.defaultRetryableHTTPStatusCodes` by default. + /// - retryableURLErrorCodes: The URL error codes that are automatically retried by the policy. + /// `RetryPolicy.defaultRetryableURLErrorCodes` by default. + /// + /// - Returns: The `RetryPolicy` + public static func retryPolicy(retryLimit: UInt = RetryPolicy.defaultRetryLimit, + exponentialBackoffBase: UInt = RetryPolicy.defaultExponentialBackoffBase, + exponentialBackoffScale: Double = RetryPolicy.defaultExponentialBackoffScale, + retryableHTTPMethods: Set = RetryPolicy.defaultRetryableHTTPMethods, + retryableHTTPStatusCodes: Set = RetryPolicy.defaultRetryableHTTPStatusCodes, + retryableURLErrorCodes: Set = RetryPolicy.defaultRetryableURLErrorCodes) -> RetryPolicy { + RetryPolicy(retryLimit: retryLimit, + exponentialBackoffBase: exponentialBackoffBase, + exponentialBackoffScale: exponentialBackoffScale, + retryableHTTPMethods: retryableHTTPMethods, + retryableHTTPStatusCodes: retryableHTTPStatusCodes, + retryableURLErrorCodes: retryableURLErrorCodes) + } +} + +// MARK: - + +/// A retry policy that automatically retries idempotent requests for network connection lost errors. For more +/// information about retrying network connection lost errors, please refer to Apple's +/// [technical document](https://developer.apple.com/library/content/qa/qa1941/_index.html). +open class ConnectionLostRetryPolicy: RetryPolicy { + /// Creates a `ConnectionLostRetryPolicy` instance from the specified parameters. + /// + /// - Parameters: + /// - retryLimit: The total number of times the request is allowed to be retried. + /// `RetryPolicy.defaultRetryLimit` by default. + /// - exponentialBackoffBase: The base of the exponential backoff policy. + /// `RetryPolicy.defaultExponentialBackoffBase` by default. + /// - exponentialBackoffScale: The scale of the exponential backoff. + /// `RetryPolicy.defaultExponentialBackoffScale` by default. + /// - retryableHTTPMethods: The idempotent http methods to retry. + /// `RetryPolicy.defaultRetryableHTTPMethods` by default. + public init(retryLimit: UInt = RetryPolicy.defaultRetryLimit, + exponentialBackoffBase: UInt = RetryPolicy.defaultExponentialBackoffBase, + exponentialBackoffScale: Double = RetryPolicy.defaultExponentialBackoffScale, + retryableHTTPMethods: Set = RetryPolicy.defaultRetryableHTTPMethods) { + super.init(retryLimit: retryLimit, + exponentialBackoffBase: exponentialBackoffBase, + exponentialBackoffScale: exponentialBackoffScale, + retryableHTTPMethods: retryableHTTPMethods, + retryableHTTPStatusCodes: [], + retryableURLErrorCodes: [.networkConnectionLost]) + } +} + +extension RequestInterceptor where Self == ConnectionLostRetryPolicy { + /// Provides a default `ConnectionLostRetryPolicy` instance. + public static var connectionLostRetryPolicy: ConnectionLostRetryPolicy { ConnectionLostRetryPolicy() } + + /// Creates a `ConnectionLostRetryPolicy` instance from the specified parameters. + /// + /// - Parameters: + /// - retryLimit: The total number of times the request is allowed to be retried. + /// `RetryPolicy.defaultRetryLimit` by default. + /// - exponentialBackoffBase: The base of the exponential backoff policy. + /// `RetryPolicy.defaultExponentialBackoffBase` by default. + /// - exponentialBackoffScale: The scale of the exponential backoff. + /// `RetryPolicy.defaultExponentialBackoffScale` by default. + /// - retryableHTTPMethods: The idempotent http methods to retry. + /// + /// - Returns: The `ConnectionLostRetryPolicy`. + public static func connectionLostRetryPolicy(retryLimit: UInt = RetryPolicy.defaultRetryLimit, + exponentialBackoffBase: UInt = RetryPolicy.defaultExponentialBackoffBase, + exponentialBackoffScale: Double = RetryPolicy.defaultExponentialBackoffScale, + retryableHTTPMethods: Set = RetryPolicy.defaultRetryableHTTPMethods) -> ConnectionLostRetryPolicy { + ConnectionLostRetryPolicy(retryLimit: retryLimit, + exponentialBackoffBase: exponentialBackoffBase, + exponentialBackoffScale: exponentialBackoffScale, + retryableHTTPMethods: retryableHTTPMethods) + } +} diff --git a/Pods/Alamofire/Source/ServerTrustEvaluation.swift b/Pods/Alamofire/Source/ServerTrustEvaluation.swift new file mode 100644 index 0000000..4519a3d --- /dev/null +++ b/Pods/Alamofire/Source/ServerTrustEvaluation.swift @@ -0,0 +1,728 @@ +// +// ServerTrustPolicy.swift +// +// Copyright (c) 2014-2016 Alamofire Software Foundation (http://alamofire.org/) +// +// Permission is hereby granted, free of charge, to any person obtaining a copy +// of this software and associated documentation files (the "Software"), to deal +// in the Software without restriction, including without limitation the rights +// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +// copies of the Software, and to permit persons to whom the Software is +// furnished to do so, subject to the following conditions: +// +// The above copyright notice and this permission notice shall be included in +// all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN +// THE SOFTWARE. +// + +import Foundation + +/// Responsible for managing the mapping of `ServerTrustEvaluating` values to given hosts. +open class ServerTrustManager { + /// Determines whether all hosts for this `ServerTrustManager` must be evaluated. `true` by default. + public let allHostsMustBeEvaluated: Bool + + /// The dictionary of policies mapped to a particular host. + public let evaluators: [String: ServerTrustEvaluating] + + /// Initializes the `ServerTrustManager` instance with the given evaluators. + /// + /// Since different servers and web services can have different leaf certificates, intermediate and even root + /// certificates, 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. + /// + /// - Parameters: + /// - allHostsMustBeEvaluated: The value determining whether all hosts for this instance must be evaluated. `true` + /// by default. + /// - evaluators: A dictionary of evaluators mapped to hosts. + public init(allHostsMustBeEvaluated: Bool = true, evaluators: [String: ServerTrustEvaluating]) { + self.allHostsMustBeEvaluated = allHostsMustBeEvaluated + self.evaluators = evaluators + } + + #if !(os(Linux) || os(Windows)) + /// Returns the `ServerTrustEvaluating` value for the given host, if one is set. + /// + /// 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 `ServerTrustEvaluating` value for the given host if found, `nil` otherwise. + /// - Throws: `AFError.serverTrustEvaluationFailed` if `allHostsMustBeEvaluated` is `true` and no matching + /// evaluators are found. + open func serverTrustEvaluator(forHost host: String) throws -> ServerTrustEvaluating? { + guard let evaluator = evaluators[host] else { + if allHostsMustBeEvaluated { + throw AFError.serverTrustEvaluationFailed(reason: .noRequiredEvaluator(host: host)) + } + + return nil + } + + return evaluator + } + #endif +} + +/// A protocol describing the API used to evaluate server trusts. +public protocol ServerTrustEvaluating { + #if os(Linux) || os(Windows) + // Implement this once Linux/Windows has API for evaluating server trusts. + #else + /// Evaluates the given `SecTrust` value for the given `host`. + /// + /// - Parameters: + /// - trust: The `SecTrust` value to evaluate. + /// - host: The host for which to evaluate the `SecTrust` value. + /// + /// - Returns: A `Bool` indicating whether the evaluator considers the `SecTrust` value valid for `host`. + func evaluate(_ trust: SecTrust, forHost host: String) throws + #endif +} + +// MARK: - Server Trust Evaluators + +#if !(os(Linux) || os(Windows)) +/// An evaluator which 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. +public final class DefaultTrustEvaluator: ServerTrustEvaluating { + private let validateHost: Bool + + /// Creates a `DefaultTrustEvaluator`. + /// + /// - Parameter validateHost: Determines whether or not the evaluator should validate the host. `true` by default. + public init(validateHost: Bool = true) { + self.validateHost = validateHost + } + + public func evaluate(_ trust: SecTrust, forHost host: String) throws { + if validateHost { + try trust.af.performValidation(forHost: host) + } + + try trust.af.performDefaultValidation(forHost: host) + } +} + +/// An evaluator which 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. +public final class RevocationTrustEvaluator: ServerTrustEvaluating { + /// Represents the options to be use when evaluating the status of a certificate. + /// Only Revocation Policy Constants are valid, and can be found in [Apple's documentation](https://developer.apple.com/documentation/security/certificate_key_and_trust_services/policies/1563600-revocation_policy_constants). + public struct Options: OptionSet { + /// Perform revocation checking using the CRL (Certification Revocation List) method. + public static let crl = Options(rawValue: kSecRevocationCRLMethod) + /// Consult only locally cached replies; do not use network access. + public static let networkAccessDisabled = Options(rawValue: kSecRevocationNetworkAccessDisabled) + /// Perform revocation checking using OCSP (Online Certificate Status Protocol). + public static let ocsp = Options(rawValue: kSecRevocationOCSPMethod) + /// Prefer CRL revocation checking over OCSP; by default, OCSP is preferred. + public static let preferCRL = Options(rawValue: kSecRevocationPreferCRL) + /// Require a positive response to pass the policy. If the flag is not set, revocation checking is done on a + /// "best attempt" basis, where failure to reach the server is not considered fatal. + public static let requirePositiveResponse = Options(rawValue: kSecRevocationRequirePositiveResponse) + /// Perform either OCSP or CRL checking. The checking is performed according to the method(s) specified in the + /// certificate and the value of `preferCRL`. + public static let any = Options(rawValue: kSecRevocationUseAnyAvailableMethod) + + /// The raw value of the option. + public let rawValue: CFOptionFlags + + /// Creates an `Options` value with the given `CFOptionFlags`. + /// + /// - Parameter rawValue: The `CFOptionFlags` value to initialize with. + public init(rawValue: CFOptionFlags) { + self.rawValue = rawValue + } + } + + private let performDefaultValidation: Bool + private let validateHost: Bool + private let options: Options + + /// Creates a `RevocationTrustEvaluator` using the provided parameters. + /// + /// - Note: Default and host validation will fail when using this evaluator with self-signed certificates. Use + /// `PinnedCertificatesTrustEvaluator` if you need to use self-signed certificates. + /// + /// - Parameters: + /// - performDefaultValidation: Determines whether default validation should be performed in addition to + /// evaluating the pinned certificates. `true` by default. + /// - validateHost: Determines whether or not the evaluator should validate the host, in addition to + /// performing the default evaluation, even if `performDefaultValidation` is `false`. + /// `true` by default. + /// - options: The `Options` to use to check the revocation status of the certificate. `.any` by + /// default. + public init(performDefaultValidation: Bool = true, validateHost: Bool = true, options: Options = .any) { + self.performDefaultValidation = performDefaultValidation + self.validateHost = validateHost + self.options = options + } + + public func evaluate(_ trust: SecTrust, forHost host: String) throws { + if performDefaultValidation { + try trust.af.performDefaultValidation(forHost: host) + } + + if validateHost { + try trust.af.performValidation(forHost: host) + } + + if #available(iOS 12, macOS 10.14, tvOS 12, watchOS 5, *) { + try trust.af.evaluate(afterApplying: SecPolicy.af.revocation(options: options)) + } else { + try trust.af.validate(policy: SecPolicy.af.revocation(options: options)) { status, result in + AFError.serverTrustEvaluationFailed(reason: .revocationCheckFailed(output: .init(host, trust, status, result), options: options)) + } + } + } +} + +extension ServerTrustEvaluating where Self == RevocationTrustEvaluator { + /// Provides a default `RevocationTrustEvaluator` instance. + public static var revocationChecking: RevocationTrustEvaluator { RevocationTrustEvaluator() } + + /// Creates a `RevocationTrustEvaluator` using the provided parameters. + /// + /// - Note: Default and host validation will fail when using this evaluator with self-signed certificates. Use + /// `PinnedCertificatesTrustEvaluator` if you need to use self-signed certificates. + /// + /// - Parameters: + /// - performDefaultValidation: Determines whether default validation should be performed in addition to + /// evaluating the pinned certificates. `true` by default. + /// - validateHost: Determines whether or not the evaluator should validate the host, in addition + /// to performing the default evaluation, even if `performDefaultValidation` is + /// `false`. `true` by default. + /// - options: The `Options` to use to check the revocation status of the certificate. `.any` + /// by default. + /// - Returns: The `RevocationTrustEvaluator`. + public static func revocationChecking(performDefaultValidation: Bool = true, + validateHost: Bool = true, + options: RevocationTrustEvaluator.Options = .any) -> RevocationTrustEvaluator { + RevocationTrustEvaluator(performDefaultValidation: performDefaultValidation, + validateHost: validateHost, + options: options) + } +} + +/// 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. +public final class PinnedCertificatesTrustEvaluator: ServerTrustEvaluating { + private let certificates: [SecCertificate] + private let acceptSelfSignedCertificates: Bool + private let performDefaultValidation: Bool + private let validateHost: Bool + + /// Creates a `PinnedCertificatesTrustEvaluator` from the provided parameters. + /// + /// - Parameters: + /// - certificates: The certificates to use to evaluate the trust. All `cer`, `crt`, and `der` + /// certificates in `Bundle.main` by default. + /// - acceptSelfSignedCertificates: Adds the provided certificates as anchors for the trust evaluation, allowing + /// self-signed certificates to pass. `false` by default. THIS SETTING SHOULD BE + /// FALSE IN PRODUCTION! + /// - performDefaultValidation: Determines whether default validation should be performed in addition to + /// evaluating the pinned certificates. `true` by default. + /// - validateHost: Determines whether or not the evaluator should validate the host, in addition + /// to performing the default evaluation, even if `performDefaultValidation` is + /// `false`. `true` by default. + public init(certificates: [SecCertificate] = Bundle.main.af.certificates, + acceptSelfSignedCertificates: Bool = false, + performDefaultValidation: Bool = true, + validateHost: Bool = true) { + self.certificates = certificates + self.acceptSelfSignedCertificates = acceptSelfSignedCertificates + self.performDefaultValidation = performDefaultValidation + self.validateHost = validateHost + } + + public func evaluate(_ trust: SecTrust, forHost host: String) throws { + guard !certificates.isEmpty else { + throw AFError.serverTrustEvaluationFailed(reason: .noCertificatesFound) + } + + if acceptSelfSignedCertificates { + try trust.af.setAnchorCertificates(certificates) + } + + if performDefaultValidation { + try trust.af.performDefaultValidation(forHost: host) + } + + if validateHost { + try trust.af.performValidation(forHost: host) + } + + let serverCertificatesData = Set(trust.af.certificateData) + let pinnedCertificatesData = Set(certificates.af.data) + let pinnedCertificatesInServerData = !serverCertificatesData.isDisjoint(with: pinnedCertificatesData) + if !pinnedCertificatesInServerData { + throw AFError.serverTrustEvaluationFailed(reason: .certificatePinningFailed(host: host, + trust: trust, + pinnedCertificates: certificates, + serverCertificates: trust.af.certificates)) + } + } +} + +extension ServerTrustEvaluating where Self == PinnedCertificatesTrustEvaluator { + /// Provides a default `PinnedCertificatesTrustEvaluator` instance. + public static var pinnedCertificates: PinnedCertificatesTrustEvaluator { PinnedCertificatesTrustEvaluator() } + + /// Creates a `PinnedCertificatesTrustEvaluator` using the provided parameters. + /// + /// - Parameters: + /// - certificates: The certificates to use to evaluate the trust. All `cer`, `crt`, and `der` + /// certificates in `Bundle.main` by default. + /// - acceptSelfSignedCertificates: Adds the provided certificates as anchors for the trust evaluation, allowing + /// self-signed certificates to pass. `false` by default. THIS SETTING SHOULD BE + /// FALSE IN PRODUCTION! + /// - performDefaultValidation: Determines whether default validation should be performed in addition to + /// evaluating the pinned certificates. `true` by default. + /// - validateHost: Determines whether or not the evaluator should validate the host, in addition + /// to performing the default evaluation, even if `performDefaultValidation` is + /// `false`. `true` by default. + public static func pinnedCertificates(certificates: [SecCertificate] = Bundle.main.af.certificates, + acceptSelfSignedCertificates: Bool = false, + performDefaultValidation: Bool = true, + validateHost: Bool = true) -> PinnedCertificatesTrustEvaluator { + PinnedCertificatesTrustEvaluator(certificates: certificates, + acceptSelfSignedCertificates: acceptSelfSignedCertificates, + performDefaultValidation: performDefaultValidation, + validateHost: validateHost) + } +} + +/// 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. +public final class PublicKeysTrustEvaluator: ServerTrustEvaluating { + private let keys: [SecKey] + private let performDefaultValidation: Bool + private let validateHost: Bool + + /// Creates a `PublicKeysTrustEvaluator` from the provided parameters. + /// + /// - Note: Default and host validation will fail when using this evaluator with self-signed certificates. Use + /// `PinnedCertificatesTrustEvaluator` if you need to use self-signed certificates. + /// + /// - Parameters: + /// - keys: The `SecKey`s to use to validate public keys. Defaults to the public keys of all + /// certificates included in the main bundle. + /// - performDefaultValidation: Determines whether default validation should be performed in addition to + /// evaluating the pinned certificates. `true` by default. + /// - validateHost: Determines whether or not the evaluator should validate the host, in addition to + /// performing the default evaluation, even if `performDefaultValidation` is `false`. + /// `true` by default. + public init(keys: [SecKey] = Bundle.main.af.publicKeys, + performDefaultValidation: Bool = true, + validateHost: Bool = true) { + self.keys = keys + self.performDefaultValidation = performDefaultValidation + self.validateHost = validateHost + } + + public func evaluate(_ trust: SecTrust, forHost host: String) throws { + guard !keys.isEmpty else { + throw AFError.serverTrustEvaluationFailed(reason: .noPublicKeysFound) + } + + if performDefaultValidation { + try trust.af.performDefaultValidation(forHost: host) + } + + if validateHost { + try trust.af.performValidation(forHost: host) + } + + let pinnedKeysInServerKeys: Bool = { + for serverPublicKey in trust.af.publicKeys { + for pinnedPublicKey in keys { + if serverPublicKey == pinnedPublicKey { + return true + } + } + } + return false + }() + + if !pinnedKeysInServerKeys { + throw AFError.serverTrustEvaluationFailed(reason: .publicKeyPinningFailed(host: host, + trust: trust, + pinnedKeys: keys, + serverKeys: trust.af.publicKeys)) + } + } +} + +extension ServerTrustEvaluating where Self == PublicKeysTrustEvaluator { + /// Provides a default `PublicKeysTrustEvaluator` instance. + public static var publicKeys: PublicKeysTrustEvaluator { PublicKeysTrustEvaluator() } + + /// Creates a `PublicKeysTrustEvaluator` from the provided parameters. + /// + /// - Note: Default and host validation will fail when using this evaluator with self-signed certificates. Use + /// `PinnedCertificatesTrustEvaluator` if you need to use self-signed certificates. + /// + /// - Parameters: + /// - keys: The `SecKey`s to use to validate public keys. Defaults to the public keys of all + /// certificates included in the main bundle. + /// - performDefaultValidation: Determines whether default validation should be performed in addition to + /// evaluating the pinned certificates. `true` by default. + /// - validateHost: Determines whether or not the evaluator should validate the host, in addition to + /// performing the default evaluation, even if `performDefaultValidation` is `false`. + /// `true` by default. + public static func publicKeys(keys: [SecKey] = Bundle.main.af.publicKeys, + performDefaultValidation: Bool = true, + validateHost: Bool = true) -> PublicKeysTrustEvaluator { + PublicKeysTrustEvaluator(keys: keys, performDefaultValidation: performDefaultValidation, validateHost: validateHost) + } +} + +/// Uses the provided evaluators to validate the server trust. The trust is only considered valid if all of the +/// evaluators consider it valid. +public final class CompositeTrustEvaluator: ServerTrustEvaluating { + private let evaluators: [ServerTrustEvaluating] + + /// Creates a `CompositeTrustEvaluator` from the provided evaluators. + /// + /// - Parameter evaluators: The `ServerTrustEvaluating` values used to evaluate the server trust. + public init(evaluators: [ServerTrustEvaluating]) { + self.evaluators = evaluators + } + + public func evaluate(_ trust: SecTrust, forHost host: String) throws { + try evaluators.evaluate(trust, forHost: host) + } +} + +extension ServerTrustEvaluating where Self == CompositeTrustEvaluator { + /// Creates a `CompositeTrustEvaluator` from the provided evaluators. + /// + /// - Parameter evaluators: The `ServerTrustEvaluating` values used to evaluate the server trust. + public static func composite(evaluators: [ServerTrustEvaluating]) -> CompositeTrustEvaluator { + CompositeTrustEvaluator(evaluators: evaluators) + } +} + +/// Disables all evaluation which in turn will always consider any server trust as valid. +/// +/// - Note: Instead of disabling server trust evaluation, it's a better idea to configure systems to properly trust test +/// certificates, as outlined in [this Apple tech note](https://developer.apple.com/library/archive/qa/qa1948/_index.html). +/// +/// **THIS EVALUATOR SHOULD NEVER BE USED IN PRODUCTION!** +@available(*, deprecated, renamed: "DisabledTrustEvaluator", message: "DisabledEvaluator has been renamed DisabledTrustEvaluator.") +public typealias DisabledEvaluator = DisabledTrustEvaluator + +/// Disables all evaluation which in turn will always consider any server trust as valid. +/// +/// +/// - Note: Instead of disabling server trust evaluation, it's a better idea to configure systems to properly trust test +/// certificates, as outlined in [this Apple tech note](https://developer.apple.com/library/archive/qa/qa1948/_index.html). +/// +/// **THIS EVALUATOR SHOULD NEVER BE USED IN PRODUCTION!** +public final class DisabledTrustEvaluator: ServerTrustEvaluating { + /// Creates an instance. + public init() {} + + public func evaluate(_ trust: SecTrust, forHost host: String) throws {} +} + +// MARK: - Extensions + +extension Array where Element == ServerTrustEvaluating { + #if os(Linux) || os(Windows) + // Add this same convenience method for Linux/Windows. + #else + /// Evaluates the given `SecTrust` value for the given `host`. + /// + /// - Parameters: + /// - trust: The `SecTrust` value to evaluate. + /// - host: The host for which to evaluate the `SecTrust` value. + /// + /// - Returns: Whether or not the evaluator considers the `SecTrust` value valid for `host`. + public func evaluate(_ trust: SecTrust, forHost host: String) throws { + for evaluator in self { + try evaluator.evaluate(trust, forHost: host) + } + } + #endif +} + +extension Bundle: AlamofireExtended {} +extension AlamofireExtension where ExtendedType: Bundle { + /// Returns all valid `cer`, `crt`, and `der` certificates in the bundle. + public var certificates: [SecCertificate] { + paths(forResourcesOfTypes: [".cer", ".CER", ".crt", ".CRT", ".der", ".DER"]).compactMap { path in + guard + let certificateData = try? Data(contentsOf: URL(fileURLWithPath: path)) as CFData, + let certificate = SecCertificateCreateWithData(nil, certificateData) else { return nil } + + return certificate + } + } + + /// Returns all public keys for the valid certificates in the bundle. + public var publicKeys: [SecKey] { + certificates.af.publicKeys + } + + /// Returns all pathnames for the resources identified by the provided file extensions. + /// + /// - Parameter types: The filename extensions locate. + /// + /// - Returns: All pathnames for the given filename extensions. + public func paths(forResourcesOfTypes types: [String]) -> [String] { + Array(Set(types.flatMap { type.paths(forResourcesOfType: $0, inDirectory: nil) })) + } +} + +extension SecTrust: AlamofireExtended {} +extension AlamofireExtension where ExtendedType == SecTrust { + /// Evaluates `self` after applying the `SecPolicy` value provided. + /// + /// - Parameter policy: The `SecPolicy` to apply to `self` before evaluation. + /// + /// - Throws: Any `Error` from applying the `SecPolicy` or from evaluation. + @available(iOS 12, macOS 10.14, tvOS 12, watchOS 5, *) + public func evaluate(afterApplying policy: SecPolicy) throws { + try apply(policy: policy).af.evaluate() + } + + /// Attempts to validate `self` using the `SecPolicy` provided and transforming any error produced using the closure passed. + /// + /// - Parameters: + /// - policy: The `SecPolicy` used to evaluate `self`. + /// - errorProducer: The closure used transform the failed `OSStatus` and `SecTrustResultType`. + /// - Throws: Any `Error` from applying the `policy`, or the result of `errorProducer` if validation fails. + @available(iOS, introduced: 10, deprecated: 12, renamed: "evaluate(afterApplying:)") + @available(macOS, introduced: 10.12, deprecated: 10.14, renamed: "evaluate(afterApplying:)") + @available(tvOS, introduced: 10, deprecated: 12, renamed: "evaluate(afterApplying:)") + @available(watchOS, introduced: 3, deprecated: 5, renamed: "evaluate(afterApplying:)") + public func validate(policy: SecPolicy, errorProducer: (_ status: OSStatus, _ result: SecTrustResultType) -> Error) throws { + try apply(policy: policy).af.validate(errorProducer: errorProducer) + } + + /// Applies a `SecPolicy` to `self`, throwing if it fails. + /// + /// - Parameter policy: The `SecPolicy`. + /// + /// - Returns: `self`, with the policy applied. + /// - Throws: An `AFError.serverTrustEvaluationFailed` instance with a `.policyApplicationFailed` reason. + public func apply(policy: SecPolicy) throws -> SecTrust { + let status = SecTrustSetPolicies(type, policy) + + guard status.af.isSuccess else { + throw AFError.serverTrustEvaluationFailed(reason: .policyApplicationFailed(trust: type, + policy: policy, + status: status)) + } + + return type + } + + /// Evaluate `self`, throwing an `Error` if evaluation fails. + /// + /// - Throws: `AFError.serverTrustEvaluationFailed` with reason `.trustValidationFailed` and associated error from + /// the underlying evaluation. + @available(iOS 12, macOS 10.14, tvOS 12, watchOS 5, *) + public func evaluate() throws { + var error: CFError? + let evaluationSucceeded = SecTrustEvaluateWithError(type, &error) + + if !evaluationSucceeded { + throw AFError.serverTrustEvaluationFailed(reason: .trustEvaluationFailed(error: error)) + } + } + + /// Validate `self`, passing any failure values through `errorProducer`. + /// + /// - Parameter errorProducer: The closure used to transform the failed `OSStatus` and `SecTrustResultType` into an + /// `Error`. + /// - Throws: The `Error` produced by the `errorProducer` closure. + @available(iOS, introduced: 10, deprecated: 12, renamed: "evaluate()") + @available(macOS, introduced: 10.12, deprecated: 10.14, renamed: "evaluate()") + @available(tvOS, introduced: 10, deprecated: 12, renamed: "evaluate()") + @available(watchOS, introduced: 3, deprecated: 5, renamed: "evaluate()") + public func validate(errorProducer: (_ status: OSStatus, _ result: SecTrustResultType) -> Error) throws { + var result = SecTrustResultType.invalid + let status = SecTrustEvaluate(type, &result) + + guard status.af.isSuccess && result.af.isSuccess else { + throw errorProducer(status, result) + } + } + + /// Sets a custom certificate chain on `self`, allowing full validation of a self-signed certificate and its chain. + /// + /// - Parameter certificates: The `SecCertificate`s to add to the chain. + /// - Throws: Any error produced when applying the new certificate chain. + public func setAnchorCertificates(_ certificates: [SecCertificate]) throws { + // Add additional anchor certificates. + let status = SecTrustSetAnchorCertificates(type, certificates as CFArray) + guard status.af.isSuccess else { + throw AFError.serverTrustEvaluationFailed(reason: .settingAnchorCertificatesFailed(status: status, + certificates: certificates)) + } + + // Trust only the set anchor certs. + let onlyStatus = SecTrustSetAnchorCertificatesOnly(type, true) + guard onlyStatus.af.isSuccess else { + throw AFError.serverTrustEvaluationFailed(reason: .settingAnchorCertificatesFailed(status: onlyStatus, + certificates: certificates)) + } + } + + /// The public keys contained in `self`. + public var publicKeys: [SecKey] { + certificates.af.publicKeys + } + + /// The `SecCertificate`s contained in `self`. + public var certificates: [SecCertificate] { + #if swift(>=5.5.1) // Xcode 13.1 / 2021 SDKs. + if #available(iOS 15, macOS 12, tvOS 15, watchOS 8, *) { + return (SecTrustCopyCertificateChain(type) as? [SecCertificate]) ?? [] + } else { + return (0.. SecPolicy { + SecPolicyCreateSSL(true, hostname as CFString) + } + + /// Creates a `SecPolicy` which checks the revocation of certificates. + /// + /// - Parameter options: The `RevocationTrustEvaluator.Options` for evaluation. + /// + /// - Returns: The `SecPolicy`. + /// - Throws: An `AFError.serverTrustEvaluationFailed` error with reason `.revocationPolicyCreationFailed` + /// if the policy cannot be created. + public static func revocation(options: RevocationTrustEvaluator.Options) throws -> SecPolicy { + guard let policy = SecPolicyCreateRevocation(options.rawValue) else { + throw AFError.serverTrustEvaluationFailed(reason: .revocationPolicyCreationFailed) + } + + return policy + } +} + +extension Array: AlamofireExtended {} +extension AlamofireExtension where ExtendedType == [SecCertificate] { + /// All `Data` values for the contained `SecCertificate`s. + public var data: [Data] { + type.map { SecCertificateCopyData($0) as Data } + } + + /// All public `SecKey` values for the contained `SecCertificate`s. + public var publicKeys: [SecKey] { + type.compactMap(\.af.publicKey) + } +} + +extension SecCertificate: AlamofireExtended {} +extension AlamofireExtension where ExtendedType == SecCertificate { + /// The public key for `self`, if it can be extracted. + /// + /// - Note: On 2020 OSes and newer, only RSA and ECDSA keys are supported. + /// + public var publicKey: SecKey? { + let policy = SecPolicyCreateBasicX509() + var trust: SecTrust? + let trustCreationStatus = SecTrustCreateWithCertificates(type, policy, &trust) + + guard let createdTrust = trust, trustCreationStatus == errSecSuccess else { return nil } + + if #available(iOS 14, macOS 11, tvOS 14, watchOS 7, *) { + return SecTrustCopyKey(createdTrust) + } else { + return SecTrustCopyPublicKey(createdTrust) + } + } +} + +extension OSStatus: AlamofireExtended {} +extension AlamofireExtension where ExtendedType == OSStatus { + /// Returns whether `self` is `errSecSuccess`. + public var isSuccess: Bool { type == errSecSuccess } +} + +extension SecTrustResultType: AlamofireExtended {} +extension AlamofireExtension where ExtendedType == SecTrustResultType { + /// Returns whether `self is `.unspecified` or `.proceed`. + public var isSuccess: Bool { + type == .unspecified || type == .proceed + } +} +#endif diff --git a/Pods/Alamofire/Source/Session.swift b/Pods/Alamofire/Source/Session.swift new file mode 100644 index 0000000..4232f85 --- /dev/null +++ b/Pods/Alamofire/Source/Session.swift @@ -0,0 +1,1264 @@ +// +// Session.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 + +/// `Session` creates and manages Alamofire's `Request` types during their lifetimes. It also provides common +/// functionality for all `Request`s, including queuing, interception, trust management, redirect handling, and response +/// cache handling. +open class Session { + /// Shared singleton instance used by all `AF.request` APIs. Cannot be modified. + public static let `default` = Session() + + /// Underlying `URLSession` used to create `URLSessionTasks` for this instance, and for which this instance's + /// `delegate` handles `URLSessionDelegate` callbacks. + /// + /// - Note: This instance should **NOT** be used to interact with the underlying `URLSessionTask`s. Doing so will + /// break internal Alamofire logic that tracks those tasks. + /// + public let session: URLSession + /// Instance's `SessionDelegate`, which handles the `URLSessionDelegate` methods and `Request` interaction. + public let delegate: SessionDelegate + /// Root `DispatchQueue` for all internal callbacks and state update. **MUST** be a serial queue. + public let rootQueue: DispatchQueue + /// Value determining whether this instance automatically calls `resume()` on all created `Request`s. + public let startRequestsImmediately: Bool + /// `DispatchQueue` on which `URLRequest`s are created asynchronously. By default this queue uses `rootQueue` as its + /// `target`, but a separate queue can be used if request creation is determined to be a bottleneck. Always profile + /// and test before introducing an additional queue. + public let requestQueue: DispatchQueue + /// `DispatchQueue` passed to all `Request`s on which they perform their response serialization. By default this + /// queue uses `rootQueue` as its `target` but a separate queue can be used if response serialization is determined + /// to be a bottleneck. Always profile and test before introducing an additional queue. + public let serializationQueue: DispatchQueue + /// `RequestInterceptor` used for all `Request` created by the instance. `RequestInterceptor`s can also be set on a + /// per-`Request` basis, in which case the `Request`'s interceptor takes precedence over this value. + public let interceptor: RequestInterceptor? + /// `ServerTrustManager` instance used to evaluate all trust challenges and provide certificate and key pinning. + public let serverTrustManager: ServerTrustManager? + /// `RedirectHandler` instance used to provide customization for request redirection. + public let redirectHandler: RedirectHandler? + /// `CachedResponseHandler` instance used to provide customization of cached response handling. + public let cachedResponseHandler: CachedResponseHandler? + /// `CompositeEventMonitor` used to compose Alamofire's `defaultEventMonitors` and any passed `EventMonitor`s. + public let eventMonitor: CompositeEventMonitor + /// `EventMonitor`s included in all instances. `[AlamofireNotifications()]` by default. + public let defaultEventMonitors: [EventMonitor] = [AlamofireNotifications()] + + /// Internal map between `Request`s and any `URLSessionTasks` that may be in flight for them. + var requestTaskMap = RequestTaskMap() + /// `Set` of currently active `Request`s. + var activeRequests: Set = [] + /// Completion events awaiting `URLSessionTaskMetrics`. + var waitingCompletions: [URLSessionTask: () -> Void] = [:] + + /// Creates a `Session` from a `URLSession` and other parameters. + /// + /// - Note: When passing a `URLSession`, you must create the `URLSession` with a specific `delegateQueue` value and + /// pass the `delegateQueue`'s `underlyingQueue` as the `rootQueue` parameter of this initializer. + /// + /// - Parameters: + /// - session: Underlying `URLSession` for this instance. + /// - delegate: `SessionDelegate` that handles `session`'s delegate callbacks as well as `Request` + /// interaction. + /// - rootQueue: Root `DispatchQueue` for all internal callbacks and state updates. **MUST** be a + /// serial queue. + /// - startRequestsImmediately: Determines whether this instance will automatically start all `Request`s. `true` + /// by default. If set to `false`, all `Request`s created must have `.resume()` called. + /// on them for them to start. + /// - requestQueue: `DispatchQueue` on which to perform `URLRequest` creation. By default this queue + /// will use the `rootQueue` as its `target`. A separate queue can be used if it's + /// determined request creation is a bottleneck, but that should only be done after + /// careful testing and profiling. `nil` by default. + /// - serializationQueue: `DispatchQueue` on which to perform all response serialization. By default this + /// queue will use the `rootQueue` as its `target`. A separate queue can be used if + /// it's determined response serialization is a bottleneck, but that should only be + /// done after careful testing and profiling. `nil` by default. + /// - interceptor: `RequestInterceptor` to be used for all `Request`s created by this instance. `nil` + /// by default. + /// - serverTrustManager: `ServerTrustManager` to be used for all trust evaluations by this instance. `nil` + /// by default. + /// - redirectHandler: `RedirectHandler` to be used by all `Request`s created by this instance. `nil` by + /// default. + /// - cachedResponseHandler: `CachedResponseHandler` to be used by all `Request`s created by this instance. + /// `nil` by default. + /// - eventMonitors: Additional `EventMonitor`s used by the instance. Alamofire always adds a + /// `AlamofireNotifications` `EventMonitor` to the array passed here. `[]` by default. + public init(session: URLSession, + delegate: SessionDelegate, + rootQueue: DispatchQueue, + startRequestsImmediately: Bool = true, + requestQueue: DispatchQueue? = nil, + serializationQueue: DispatchQueue? = nil, + interceptor: RequestInterceptor? = nil, + serverTrustManager: ServerTrustManager? = nil, + redirectHandler: RedirectHandler? = nil, + cachedResponseHandler: CachedResponseHandler? = nil, + eventMonitors: [EventMonitor] = []) { + precondition(session.configuration.identifier == nil, + "Alamofire does not support background URLSessionConfigurations.") + precondition(session.delegateQueue.underlyingQueue === rootQueue, + "Session(session:) initializer must be passed the DispatchQueue used as the delegateQueue's underlyingQueue as rootQueue.") + + self.session = session + self.delegate = delegate + self.rootQueue = rootQueue + self.startRequestsImmediately = startRequestsImmediately + self.requestQueue = requestQueue ?? DispatchQueue(label: "\(rootQueue.label).requestQueue", target: rootQueue) + self.serializationQueue = serializationQueue ?? DispatchQueue(label: "\(rootQueue.label).serializationQueue", target: rootQueue) + self.interceptor = interceptor + self.serverTrustManager = serverTrustManager + self.redirectHandler = redirectHandler + self.cachedResponseHandler = cachedResponseHandler + eventMonitor = CompositeEventMonitor(monitors: defaultEventMonitors + eventMonitors) + delegate.eventMonitor = eventMonitor + delegate.stateProvider = self + } + + /// Creates a `Session` from a `URLSessionConfiguration`. + /// + /// - Note: This initializer lets Alamofire handle the creation of the underlying `URLSession` and its + /// `delegateQueue`, and is the recommended initializer for most uses. + /// + /// - Parameters: + /// - configuration: `URLSessionConfiguration` to be used to create the underlying `URLSession`. Changes + /// to this value after being passed to this initializer will have no effect. + /// `URLSessionConfiguration.af.default` by default. + /// - delegate: `SessionDelegate` that handles `session`'s delegate callbacks as well as `Request` + /// interaction. `SessionDelegate()` by default. + /// - rootQueue: Root `DispatchQueue` for all internal callbacks and state updates. **MUST** be a + /// serial queue. `DispatchQueue(label: "org.alamofire.session.rootQueue")` by default. + /// - startRequestsImmediately: Determines whether this instance will automatically start all `Request`s. `true` + /// by default. If set to `false`, all `Request`s created must have `.resume()` called. + /// on them for them to start. + /// - requestQueue: `DispatchQueue` on which to perform `URLRequest` creation. By default this queue + /// will use the `rootQueue` as its `target`. A separate queue can be used if it's + /// determined request creation is a bottleneck, but that should only be done after + /// careful testing and profiling. `nil` by default. + /// - serializationQueue: `DispatchQueue` on which to perform all response serialization. By default this + /// queue will use the `rootQueue` as its `target`. A separate queue can be used if + /// it's determined response serialization is a bottleneck, but that should only be + /// done after careful testing and profiling. `nil` by default. + /// - interceptor: `RequestInterceptor` to be used for all `Request`s created by this instance. `nil` + /// by default. + /// - serverTrustManager: `ServerTrustManager` to be used for all trust evaluations by this instance. `nil` + /// by default. + /// - redirectHandler: `RedirectHandler` to be used by all `Request`s created by this instance. `nil` by + /// default. + /// - cachedResponseHandler: `CachedResponseHandler` to be used by all `Request`s created by this instance. + /// `nil` by default. + /// - eventMonitors: Additional `EventMonitor`s used by the instance. Alamofire always adds a + /// `AlamofireNotifications` `EventMonitor` to the array passed here. `[]` by default. + public convenience init(configuration: URLSessionConfiguration = URLSessionConfiguration.af.default, + delegate: SessionDelegate = SessionDelegate(), + rootQueue: DispatchQueue = DispatchQueue(label: "org.alamofire.session.rootQueue"), + startRequestsImmediately: Bool = true, + requestQueue: DispatchQueue? = nil, + serializationQueue: DispatchQueue? = nil, + interceptor: RequestInterceptor? = nil, + serverTrustManager: ServerTrustManager? = nil, + redirectHandler: RedirectHandler? = nil, + cachedResponseHandler: CachedResponseHandler? = nil, + eventMonitors: [EventMonitor] = []) { + precondition(configuration.identifier == nil, "Alamofire does not support background URLSessionConfigurations.") + + // Retarget the incoming rootQueue for safety, unless it's the main queue, which we know is safe. + let serialRootQueue = (rootQueue === DispatchQueue.main) ? rootQueue : DispatchQueue(label: rootQueue.label, + target: rootQueue) + let delegateQueue = OperationQueue(maxConcurrentOperationCount: 1, underlyingQueue: serialRootQueue, name: "\(serialRootQueue.label).sessionDelegate") + let session = URLSession(configuration: configuration, delegate: delegate, delegateQueue: delegateQueue) + + self.init(session: session, + delegate: delegate, + rootQueue: serialRootQueue, + startRequestsImmediately: startRequestsImmediately, + requestQueue: requestQueue, + serializationQueue: serializationQueue, + interceptor: interceptor, + serverTrustManager: serverTrustManager, + redirectHandler: redirectHandler, + cachedResponseHandler: cachedResponseHandler, + eventMonitors: eventMonitors) + } + + deinit { + finishRequestsForDeinit() + session.invalidateAndCancel() + } + + // MARK: - All Requests API + + /// Perform an action on all active `Request`s. + /// + /// - Note: The provided `action` closure is performed asynchronously, meaning that some `Request`s may complete and + /// be unavailable by time it runs. Additionally, this action is performed on the instances's `rootQueue`, + /// so care should be taken that actions are fast. Once the work on the `Request`s is complete, any + /// additional work should be performed on another queue. + /// + /// - Parameters: + /// - action: Closure to perform with all `Request`s. + public func withAllRequests(perform action: @escaping (Set) -> Void) { + rootQueue.async { + action(self.activeRequests) + } + } + + /// Cancel all active `Request`s, optionally calling a completion handler when complete. + /// + /// - Note: This is an asynchronous operation and does not block the creation of future `Request`s. Cancelled + /// `Request`s may not cancel immediately due internal work, and may not cancel at all if they are close to + /// completion when cancelled. + /// + /// - Parameters: + /// - queue: `DispatchQueue` on which the completion handler is run. `.main` by default. + /// - completion: Closure to be called when all `Request`s have been cancelled. + public func cancelAllRequests(completingOnQueue queue: DispatchQueue = .main, completion: (() -> Void)? = nil) { + withAllRequests { requests in + requests.forEach { $0.cancel() } + queue.async { + completion?() + } + } + } + + // MARK: - DataRequest + + /// Closure which provides a `URLRequest` for mutation. + public typealias RequestModifier = (inout URLRequest) throws -> Void + + struct RequestConvertible: URLRequestConvertible { + let url: URLConvertible + let method: HTTPMethod + let parameters: Parameters? + let encoding: ParameterEncoding + let headers: HTTPHeaders? + let requestModifier: RequestModifier? + + func asURLRequest() throws -> URLRequest { + var request = try URLRequest(url: url, method: method, headers: headers) + try requestModifier?(&request) + + return try encoding.encode(request, with: parameters) + } + } + + /// Creates a `DataRequest` from a `URLRequest` created using the passed components and a `RequestInterceptor`. + /// + /// - Parameters: + /// - convertible: `URLConvertible` value to be used as the `URLRequest`'s `URL`. + /// - method: `HTTPMethod` for the `URLRequest`. `.get` by default. + /// - parameters: `Parameters` (a.k.a. `[String: Any]`) value to be encoded into the `URLRequest`. `nil` by + /// default. + /// - encoding: `ParameterEncoding` to be used to encode the `parameters` value into the `URLRequest`. + /// `URLEncoding.default` by default. + /// - headers: `HTTPHeaders` value to be added to the `URLRequest`. `nil` by default. + /// - interceptor: `RequestInterceptor` value to be used by the returned `DataRequest`. `nil` by default. + /// - requestModifier: `RequestModifier` which will be applied to the `URLRequest` created from the provided + /// parameters. `nil` by default. + /// + /// - Returns: The created `DataRequest`. + open func request(_ convertible: URLConvertible, + method: HTTPMethod = .get, + parameters: Parameters? = nil, + encoding: ParameterEncoding = URLEncoding.default, + headers: HTTPHeaders? = nil, + interceptor: RequestInterceptor? = nil, + requestModifier: RequestModifier? = nil) -> DataRequest { + let convertible = RequestConvertible(url: convertible, + method: method, + parameters: parameters, + encoding: encoding, + headers: headers, + requestModifier: requestModifier) + + return request(convertible, interceptor: interceptor) + } + + struct RequestEncodableConvertible: URLRequestConvertible { + let url: URLConvertible + let method: HTTPMethod + let parameters: Parameters? + let encoder: ParameterEncoder + let headers: HTTPHeaders? + let requestModifier: RequestModifier? + + func asURLRequest() throws -> URLRequest { + var request = try URLRequest(url: url, method: method, headers: headers) + try requestModifier?(&request) + + return try parameters.map { try encoder.encode($0, into: request) } ?? request + } + } + + /// Creates a `DataRequest` from a `URLRequest` created using the passed components, `Encodable` parameters, and a + /// `RequestInterceptor`. + /// + /// - Parameters: + /// - convertible: `URLConvertible` value to be used as the `URLRequest`'s `URL`. + /// - method: `HTTPMethod` for the `URLRequest`. `.get` by default. + /// - parameters: `Encodable` value to be encoded into the `URLRequest`. `nil` by default. + /// - encoder: `ParameterEncoder` to be used to encode the `parameters` value into the `URLRequest`. + /// `URLEncodedFormParameterEncoder.default` by default. + /// - headers: `HTTPHeaders` value to be added to the `URLRequest`. `nil` by default. + /// - interceptor: `RequestInterceptor` value to be used by the returned `DataRequest`. `nil` by default. + /// - requestModifier: `RequestModifier` which will be applied to the `URLRequest` created from + /// the provided parameters. `nil` by default. + /// + /// - Returns: The created `DataRequest`. + open func request(_ convertible: URLConvertible, + method: HTTPMethod = .get, + parameters: Parameters? = nil, + encoder: ParameterEncoder = URLEncodedFormParameterEncoder.default, + headers: HTTPHeaders? = nil, + interceptor: RequestInterceptor? = nil, + requestModifier: RequestModifier? = nil) -> DataRequest { + let convertible = RequestEncodableConvertible(url: convertible, + method: method, + parameters: parameters, + encoder: encoder, + headers: headers, + requestModifier: requestModifier) + + return request(convertible, interceptor: interceptor) + } + + /// Creates a `DataRequest` from a `URLRequestConvertible` value and a `RequestInterceptor`. + /// + /// - Parameters: + /// - convertible: `URLRequestConvertible` value to be used to create the `URLRequest`. + /// - interceptor: `RequestInterceptor` value to be used by the returned `DataRequest`. `nil` by default. + /// + /// - Returns: The created `DataRequest`. + open func request(_ convertible: URLRequestConvertible, interceptor: RequestInterceptor? = nil) -> DataRequest { + let request = DataRequest(convertible: convertible, + underlyingQueue: rootQueue, + serializationQueue: serializationQueue, + eventMonitor: eventMonitor, + interceptor: interceptor, + delegate: self) + + perform(request) + + return request + } + + // MARK: - DataStreamRequest + + /// Creates a `DataStreamRequest` from the passed components, `Encodable` parameters, and `RequestInterceptor`. + /// + /// - Parameters: + /// - convertible: `URLConvertible` value to be used as the `URLRequest`'s `URL`. + /// - method: `HTTPMethod` for the `URLRequest`. `.get` by default. + /// - parameters: `Encodable` value to be encoded into the `URLRequest`. `nil` by default. + /// - encoder: `ParameterEncoder` to be used to encode the `parameters` value into the + /// `URLRequest`. + /// `URLEncodedFormParameterEncoder.default` by default. + /// - headers: `HTTPHeaders` value to be added to the `URLRequest`. `nil` by default. + /// - automaticallyCancelOnStreamError: `Bool` indicating whether the instance should be canceled when an `Error` + /// is thrown while serializing stream `Data`. `false` by default. + /// - interceptor: `RequestInterceptor` value to be used by the returned `DataRequest`. `nil` + /// by default. + /// - requestModifier: `RequestModifier` which will be applied to the `URLRequest` created from + /// the provided parameters. `nil` by default. + /// + /// - Returns: The created `DataStream` request. + open func streamRequest(_ convertible: URLConvertible, + method: HTTPMethod = .get, + parameters: Parameters? = nil, + encoder: ParameterEncoder = URLEncodedFormParameterEncoder.default, + headers: HTTPHeaders? = nil, + automaticallyCancelOnStreamError: Bool = false, + interceptor: RequestInterceptor? = nil, + requestModifier: RequestModifier? = nil) -> DataStreamRequest { + let convertible = RequestEncodableConvertible(url: convertible, + method: method, + parameters: parameters, + encoder: encoder, + headers: headers, + requestModifier: requestModifier) + + return streamRequest(convertible, + automaticallyCancelOnStreamError: automaticallyCancelOnStreamError, + interceptor: interceptor) + } + + /// Creates a `DataStreamRequest` from the passed components and `RequestInterceptor`. + /// + /// - Parameters: + /// - convertible: `URLConvertible` value to be used as the `URLRequest`'s `URL`. + /// - method: `HTTPMethod` for the `URLRequest`. `.get` by default. + /// - headers: `HTTPHeaders` value to be added to the `URLRequest`. `nil` by default. + /// - automaticallyCancelOnStreamError: `Bool` indicating whether the instance should be canceled when an `Error` + /// is thrown while serializing stream `Data`. `false` by default. + /// - interceptor: `RequestInterceptor` value to be used by the returned `DataRequest`. `nil` + /// by default. + /// - requestModifier: `RequestModifier` which will be applied to the `URLRequest` created from + /// the provided parameters. `nil` by default. + /// + /// - Returns: The created `DataStream` request. + open func streamRequest(_ convertible: URLConvertible, + method: HTTPMethod = .get, + headers: HTTPHeaders? = nil, + automaticallyCancelOnStreamError: Bool = false, + interceptor: RequestInterceptor? = nil, + requestModifier: RequestModifier? = nil) -> DataStreamRequest { + let convertible = RequestEncodableConvertible(url: convertible, + method: method, + parameters: Empty?.none, + encoder: URLEncodedFormParameterEncoder.default, + headers: headers, + requestModifier: requestModifier) + + return streamRequest(convertible, + automaticallyCancelOnStreamError: automaticallyCancelOnStreamError, + interceptor: interceptor) + } + + /// Creates a `DataStreamRequest` from the passed `URLRequestConvertible` value and `RequestInterceptor`. + /// + /// - Parameters: + /// - convertible: `URLRequestConvertible` value to be used to create the `URLRequest`. + /// - automaticallyCancelOnStreamError: `Bool` indicating whether the instance should be canceled when an `Error` + /// is thrown while serializing stream `Data`. `false` by default. + /// - interceptor: `RequestInterceptor` value to be used by the returned `DataRequest`. `nil` + /// by default. + /// + /// - Returns: The created `DataStreamRequest`. + open func streamRequest(_ convertible: URLRequestConvertible, + automaticallyCancelOnStreamError: Bool = false, + interceptor: RequestInterceptor? = nil) -> DataStreamRequest { + let request = DataStreamRequest(convertible: convertible, + automaticallyCancelOnStreamError: automaticallyCancelOnStreamError, + underlyingQueue: rootQueue, + serializationQueue: serializationQueue, + eventMonitor: eventMonitor, + interceptor: interceptor, + delegate: self) + + perform(request) + + return request + } + + // MARK: - DownloadRequest + + /// Creates a `DownloadRequest` using a `URLRequest` created using the passed components, `RequestInterceptor`, and + /// `Destination`. + /// + /// - Parameters: + /// - convertible: `URLConvertible` value to be used as the `URLRequest`'s `URL`. + /// - method: `HTTPMethod` for the `URLRequest`. `.get` by default. + /// - parameters: `Parameters` (a.k.a. `[String: Any]`) value to be encoded into the `URLRequest`. `nil` by + /// default. + /// - encoding: `ParameterEncoding` to be used to encode the `parameters` value into the `URLRequest`. + /// Defaults to `URLEncoding.default`. + /// - headers: `HTTPHeaders` value to be added to the `URLRequest`. `nil` by default. + /// - interceptor: `RequestInterceptor` value to be used by the returned `DataRequest`. `nil` by default. + /// - requestModifier: `RequestModifier` which will be applied to the `URLRequest` created from the provided + /// parameters. `nil` by default. + /// - destination: `DownloadRequest.Destination` closure used to determine how and where the downloaded file + /// should be moved. `nil` by default. + /// + /// - Returns: The created `DownloadRequest`. + open func download(_ convertible: URLConvertible, + method: HTTPMethod = .get, + parameters: Parameters? = nil, + encoding: ParameterEncoding = URLEncoding.default, + headers: HTTPHeaders? = nil, + interceptor: RequestInterceptor? = nil, + requestModifier: RequestModifier? = nil, + to destination: DownloadRequest.Destination? = nil) -> DownloadRequest { + let convertible = RequestConvertible(url: convertible, + method: method, + parameters: parameters, + encoding: encoding, + headers: headers, + requestModifier: requestModifier) + + return download(convertible, interceptor: interceptor, to: destination) + } + + /// Creates a `DownloadRequest` from a `URLRequest` created using the passed components, `Encodable` parameters, and + /// a `RequestInterceptor`. + /// + /// - Parameters: + /// - convertible: `URLConvertible` value to be used as the `URLRequest`'s `URL`. + /// - method: `HTTPMethod` for the `URLRequest`. `.get` by default. + /// - parameters: Value conforming to `Encodable` to be encoded into the `URLRequest`. `nil` by default. + /// - encoder: `ParameterEncoder` to be used to encode the `parameters` value into the `URLRequest`. + /// Defaults to `URLEncodedFormParameterEncoder.default`. + /// - headers: `HTTPHeaders` value to be added to the `URLRequest`. `nil` by default. + /// - interceptor: `RequestInterceptor` value to be used by the returned `DataRequest`. `nil` by default. + /// - requestModifier: `RequestModifier` which will be applied to the `URLRequest` created from the provided + /// parameters. `nil` by default. + /// - destination: `DownloadRequest.Destination` closure used to determine how and where the downloaded file + /// should be moved. `nil` by default. + /// + /// - Returns: The created `DownloadRequest`. + open func download(_ convertible: URLConvertible, + method: HTTPMethod = .get, + parameters: Parameters? = nil, + encoder: ParameterEncoder = URLEncodedFormParameterEncoder.default, + headers: HTTPHeaders? = nil, + interceptor: RequestInterceptor? = nil, + requestModifier: RequestModifier? = nil, + to destination: DownloadRequest.Destination? = nil) -> DownloadRequest { + let convertible = RequestEncodableConvertible(url: convertible, + method: method, + parameters: parameters, + encoder: encoder, + headers: headers, + requestModifier: requestModifier) + + return download(convertible, interceptor: interceptor, to: destination) + } + + /// Creates a `DownloadRequest` from a `URLRequestConvertible` value, a `RequestInterceptor`, and a `Destination`. + /// + /// - Parameters: + /// - convertible: `URLRequestConvertible` value to be used to create the `URLRequest`. + /// - interceptor: `RequestInterceptor` value to be used by the returned `DataRequest`. `nil` by default. + /// - destination: `DownloadRequest.Destination` closure used to determine how and where the downloaded file + /// should be moved. `nil` by default. + /// + /// - Returns: The created `DownloadRequest`. + open func download(_ convertible: URLRequestConvertible, + interceptor: RequestInterceptor? = nil, + to destination: DownloadRequest.Destination? = nil) -> DownloadRequest { + let request = DownloadRequest(downloadable: .request(convertible), + underlyingQueue: rootQueue, + serializationQueue: serializationQueue, + eventMonitor: eventMonitor, + interceptor: interceptor, + delegate: self, + destination: destination ?? DownloadRequest.defaultDestination) + + perform(request) + + return request + } + + /// Creates a `DownloadRequest` from the `resumeData` produced from a previously cancelled `DownloadRequest`, as + /// well as a `RequestInterceptor`, and a `Destination`. + /// + /// - Note: If `destination` is not specified, the download will be moved to a temporary location determined by + /// Alamofire. The file will not be deleted until the system purges the temporary files. + /// + /// - Note: On some versions of all Apple platforms (iOS 10 - 10.2, macOS 10.12 - 10.12.2, tvOS 10 - 10.1, watchOS 3 - 3.1.1), + /// `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 [this Stack Overflow post](http://stackoverflow.com/a/39347461/1342462). + /// + /// - Parameters: + /// - data: The resume data from a previously cancelled `DownloadRequest` or `URLSessionDownloadTask`. + /// - interceptor: `RequestInterceptor` value to be used by the returned `DataRequest`. `nil` by default. + /// - destination: `DownloadRequest.Destination` closure used to determine how and where the downloaded file + /// should be moved. `nil` by default. + /// + /// - Returns: The created `DownloadRequest`. + open func download(resumingWith data: Data, + interceptor: RequestInterceptor? = nil, + to destination: DownloadRequest.Destination? = nil) -> DownloadRequest { + let request = DownloadRequest(downloadable: .resumeData(data), + underlyingQueue: rootQueue, + serializationQueue: serializationQueue, + eventMonitor: eventMonitor, + interceptor: interceptor, + delegate: self, + destination: destination ?? DownloadRequest.defaultDestination) + + perform(request) + + return request + } + + // MARK: - UploadRequest + + struct ParameterlessRequestConvertible: URLRequestConvertible { + let url: URLConvertible + let method: HTTPMethod + let headers: HTTPHeaders? + let requestModifier: RequestModifier? + + func asURLRequest() throws -> URLRequest { + var request = try URLRequest(url: url, method: method, headers: headers) + try requestModifier?(&request) + + return request + } + } + + struct Upload: UploadConvertible { + let request: URLRequestConvertible + let uploadable: UploadableConvertible + + func createUploadable() throws -> UploadRequest.Uploadable { + try uploadable.createUploadable() + } + + func asURLRequest() throws -> URLRequest { + try request.asURLRequest() + } + } + + // MARK: Data + + /// Creates an `UploadRequest` for the given `Data`, `URLRequest` components, and `RequestInterceptor`. + /// + /// - Parameters: + /// - data: The `Data` to upload. + /// - convertible: `URLConvertible` value to be used as the `URLRequest`'s `URL`. + /// - method: `HTTPMethod` for the `URLRequest`. `.post` by default. + /// - headers: `HTTPHeaders` value to be added to the `URLRequest`. `nil` by default. + /// - interceptor: `RequestInterceptor` value to be used by the returned `DataRequest`. `nil` by default. + /// - fileManager: `FileManager` instance to be used by the returned `UploadRequest`. `.default` instance by + /// default. + /// - requestModifier: `RequestModifier` which will be applied to the `URLRequest` created from the provided + /// parameters. `nil` by default. + /// + /// - Returns: The created `UploadRequest`. + open func upload(_ data: Data, + to convertible: URLConvertible, + method: HTTPMethod = .post, + headers: HTTPHeaders? = nil, + interceptor: RequestInterceptor? = nil, + fileManager: FileManager = .default, + requestModifier: RequestModifier? = nil) -> UploadRequest { + let convertible = ParameterlessRequestConvertible(url: convertible, + method: method, + headers: headers, + requestModifier: requestModifier) + + return upload(data, with: convertible, interceptor: interceptor, fileManager: fileManager) + } + + /// Creates an `UploadRequest` for the given `Data` using the `URLRequestConvertible` value and `RequestInterceptor`. + /// + /// - Parameters: + /// - data: The `Data` to upload. + /// - convertible: `URLRequestConvertible` value to be used to create the `URLRequest`. + /// - interceptor: `RequestInterceptor` value to be used by the returned `DataRequest`. `nil` by default. + /// - fileManager: `FileManager` instance to be used by the returned `UploadRequest`. `.default` instance by + /// default. + /// + /// - Returns: The created `UploadRequest`. + open func upload(_ data: Data, + with convertible: URLRequestConvertible, + interceptor: RequestInterceptor? = nil, + fileManager: FileManager = .default) -> UploadRequest { + upload(.data(data), with: convertible, interceptor: interceptor, fileManager: fileManager) + } + + // MARK: File + + /// Creates an `UploadRequest` for the file at the given file `URL`, using a `URLRequest` from the provided + /// components and `RequestInterceptor`. + /// + /// - Parameters: + /// - fileURL: The `URL` of the file to upload. + /// - convertible: `URLConvertible` value to be used as the `URLRequest`'s `URL`. + /// - method: `HTTPMethod` for the `URLRequest`. `.post` by default. + /// - headers: `HTTPHeaders` value to be added to the `URLRequest`. `nil` by default. + /// - interceptor: `RequestInterceptor` value to be used by the returned `UploadRequest`. `nil` by default. + /// - fileManager: `FileManager` instance to be used by the returned `UploadRequest`. `.default` instance by + /// default. + /// - requestModifier: `RequestModifier` which will be applied to the `URLRequest` created from the provided + /// parameters. `nil` by default. + /// + /// - Returns: The created `UploadRequest`. + open func upload(_ fileURL: URL, + to convertible: URLConvertible, + method: HTTPMethod = .post, + headers: HTTPHeaders? = nil, + interceptor: RequestInterceptor? = nil, + fileManager: FileManager = .default, + requestModifier: RequestModifier? = nil) -> UploadRequest { + let convertible = ParameterlessRequestConvertible(url: convertible, + method: method, + headers: headers, + requestModifier: requestModifier) + + return upload(fileURL, with: convertible, interceptor: interceptor, fileManager: fileManager) + } + + /// Creates an `UploadRequest` for the file at the given file `URL` using the `URLRequestConvertible` value and + /// `RequestInterceptor`. + /// + /// - Parameters: + /// - fileURL: The `URL` of the file to upload. + /// - convertible: `URLRequestConvertible` value to be used to create the `URLRequest`. + /// - interceptor: `RequestInterceptor` value to be used by the returned `DataRequest`. `nil` by default. + /// - fileManager: `FileManager` instance to be used by the returned `UploadRequest`. `.default` instance by + /// default. + /// + /// - Returns: The created `UploadRequest`. + open func upload(_ fileURL: URL, + with convertible: URLRequestConvertible, + interceptor: RequestInterceptor? = nil, + fileManager: FileManager = .default) -> UploadRequest { + upload(.file(fileURL, shouldRemove: false), with: convertible, interceptor: interceptor, fileManager: fileManager) + } + + // MARK: InputStream + + /// Creates an `UploadRequest` from the `InputStream` provided using a `URLRequest` from the provided components and + /// `RequestInterceptor`. + /// + /// - Parameters: + /// - stream: The `InputStream` that provides the data to upload. + /// - convertible: `URLConvertible` value to be used as the `URLRequest`'s `URL`. + /// - method: `HTTPMethod` for the `URLRequest`. `.post` by default. + /// - headers: `HTTPHeaders` value to be added to the `URLRequest`. `nil` by default. + /// - interceptor: `RequestInterceptor` value to be used by the returned `DataRequest`. `nil` by default. + /// - fileManager: `FileManager` instance to be used by the returned `UploadRequest`. `.default` instance by + /// default. + /// - requestModifier: `RequestModifier` which will be applied to the `URLRequest` created from the provided + /// parameters. `nil` by default. + /// + /// - Returns: The created `UploadRequest`. + open func upload(_ stream: InputStream, + to convertible: URLConvertible, + method: HTTPMethod = .post, + headers: HTTPHeaders? = nil, + interceptor: RequestInterceptor? = nil, + fileManager: FileManager = .default, + requestModifier: RequestModifier? = nil) -> UploadRequest { + let convertible = ParameterlessRequestConvertible(url: convertible, + method: method, + headers: headers, + requestModifier: requestModifier) + + return upload(stream, with: convertible, interceptor: interceptor, fileManager: fileManager) + } + + /// Creates an `UploadRequest` from the provided `InputStream` using the `URLRequestConvertible` value and + /// `RequestInterceptor`. + /// + /// - Parameters: + /// - stream: The `InputStream` that provides the data to upload. + /// - convertible: `URLRequestConvertible` value to be used to create the `URLRequest`. + /// - interceptor: `RequestInterceptor` value to be used by the returned `DataRequest`. `nil` by default. + /// - fileManager: `FileManager` instance to be used by the returned `UploadRequest`. `.default` instance by + /// default. + /// + /// - Returns: The created `UploadRequest`. + open func upload(_ stream: InputStream, + with convertible: URLRequestConvertible, + interceptor: RequestInterceptor? = nil, + fileManager: FileManager = .default) -> UploadRequest { + upload(.stream(stream), with: convertible, interceptor: interceptor, fileManager: fileManager) + } + + // MARK: MultipartFormData + + /// Creates an `UploadRequest` for the multipart form data built using a closure and sent using the provided + /// `URLRequest` components and `RequestInterceptor`. + /// + /// It is important to understand the memory implications of uploading `MultipartFormData`. If the cumulative + /// 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. + /// + /// - Parameters: + /// - multipartFormData: `MultipartFormData` building closure. + /// - url: `URLConvertible` value to be used as the `URLRequest`'s `URL`. + /// - encodingMemoryThreshold: Byte threshold used to determine whether the form data is encoded into memory or + /// onto disk before being uploaded. `MultipartFormData.encodingMemoryThreshold` by + /// default. + /// - method: `HTTPMethod` for the `URLRequest`. `.post` by default. + /// - headers: `HTTPHeaders` value to be added to the `URLRequest`. `nil` by default. + /// - interceptor: `RequestInterceptor` value to be used by the returned `DataRequest`. `nil` by default. + /// - fileManager: `FileManager` to be used if the form data exceeds the memory threshold and is + /// written to disk before being uploaded. `.default` instance by default. + /// - requestModifier: `RequestModifier` which will be applied to the `URLRequest` created from the + /// provided parameters. `nil` by default. + /// + /// - Returns: The created `UploadRequest`. + open func upload(multipartFormData: @escaping (MultipartFormData) -> Void, + to url: URLConvertible, + usingThreshold encodingMemoryThreshold: UInt64 = MultipartFormData.encodingMemoryThreshold, + method: HTTPMethod = .post, + headers: HTTPHeaders? = nil, + interceptor: RequestInterceptor? = nil, + fileManager: FileManager = .default, + requestModifier: RequestModifier? = nil) -> UploadRequest { + let convertible = ParameterlessRequestConvertible(url: url, + method: method, + headers: headers, + requestModifier: requestModifier) + + let formData = MultipartFormData(fileManager: fileManager) + multipartFormData(formData) + + return upload(multipartFormData: formData, + with: convertible, + usingThreshold: encodingMemoryThreshold, + interceptor: interceptor, + fileManager: fileManager) + } + + /// Creates an `UploadRequest` using a `MultipartFormData` building closure, the provided `URLRequestConvertible` + /// value, and a `RequestInterceptor`. + /// + /// It is important to understand the memory implications of uploading `MultipartFormData`. If the cumulative + /// 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. + /// + /// - Parameters: + /// - multipartFormData: `MultipartFormData` building closure. + /// - request: `URLRequestConvertible` value to be used to create the `URLRequest`. + /// - encodingMemoryThreshold: Byte threshold used to determine whether the form data is encoded into memory or + /// onto disk before being uploaded. `MultipartFormData.encodingMemoryThreshold` by + /// default. + /// - interceptor: `RequestInterceptor` value to be used by the returned `DataRequest`. `nil` by default. + /// - fileManager: `FileManager` to be used if the form data exceeds the memory threshold and is + /// written to disk before being uploaded. `.default` instance by default. + /// + /// - Returns: The created `UploadRequest`. + open func upload(multipartFormData: @escaping (MultipartFormData) -> Void, + with request: URLRequestConvertible, + usingThreshold encodingMemoryThreshold: UInt64 = MultipartFormData.encodingMemoryThreshold, + interceptor: RequestInterceptor? = nil, + fileManager: FileManager = .default) -> UploadRequest { + let formData = MultipartFormData(fileManager: fileManager) + multipartFormData(formData) + + return upload(multipartFormData: formData, + with: request, + usingThreshold: encodingMemoryThreshold, + interceptor: interceptor, + fileManager: fileManager) + } + + /// Creates an `UploadRequest` for the prebuilt `MultipartFormData` value using the provided `URLRequest` components + /// and `RequestInterceptor`. + /// + /// It is important to understand the memory implications of uploading `MultipartFormData`. If the cumulative + /// 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. + /// + /// - Parameters: + /// - multipartFormData: `MultipartFormData` instance to upload. + /// - url: `URLConvertible` value to be used as the `URLRequest`'s `URL`. + /// - encodingMemoryThreshold: Byte threshold used to determine whether the form data is encoded into memory or + /// onto disk before being uploaded. `MultipartFormData.encodingMemoryThreshold` by + /// default. + /// - method: `HTTPMethod` for the `URLRequest`. `.post` by default. + /// - headers: `HTTPHeaders` value to be added to the `URLRequest`. `nil` by default. + /// - interceptor: `RequestInterceptor` value to be used by the returned `DataRequest`. `nil` by default. + /// - fileManager: `FileManager` to be used if the form data exceeds the memory threshold and is + /// written to disk before being uploaded. `.default` instance by default. + /// - requestModifier: `RequestModifier` which will be applied to the `URLRequest` created from the + /// provided parameters. `nil` by default. + /// + /// - Returns: The created `UploadRequest`. + open func upload(multipartFormData: MultipartFormData, + to url: URLConvertible, + usingThreshold encodingMemoryThreshold: UInt64 = MultipartFormData.encodingMemoryThreshold, + method: HTTPMethod = .post, + headers: HTTPHeaders? = nil, + interceptor: RequestInterceptor? = nil, + fileManager: FileManager = .default, + requestModifier: RequestModifier? = nil) -> UploadRequest { + let convertible = ParameterlessRequestConvertible(url: url, + method: method, + headers: headers, + requestModifier: requestModifier) + + let multipartUpload = MultipartUpload(encodingMemoryThreshold: encodingMemoryThreshold, + request: convertible, + multipartFormData: multipartFormData) + + return upload(multipartUpload, interceptor: interceptor, fileManager: fileManager) + } + + /// Creates an `UploadRequest` for the prebuilt `MultipartFormData` value using the providing `URLRequestConvertible` + /// value and `RequestInterceptor`. + /// + /// It is important to understand the memory implications of uploading `MultipartFormData`. If the cumulative + /// 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. + /// + /// - Parameters: + /// - multipartFormData: `MultipartFormData` instance to upload. + /// - request: `URLRequestConvertible` value to be used to create the `URLRequest`. + /// - encodingMemoryThreshold: Byte threshold used to determine whether the form data is encoded into memory or + /// onto disk before being uploaded. `MultipartFormData.encodingMemoryThreshold` by + /// default. + /// - interceptor: `RequestInterceptor` value to be used by the returned `DataRequest`. `nil` by default. + /// - fileManager: `FileManager` instance to be used by the returned `UploadRequest`. `.default` instance by + /// default. + /// + /// - Returns: The created `UploadRequest`. + open func upload(multipartFormData: MultipartFormData, + with request: URLRequestConvertible, + usingThreshold encodingMemoryThreshold: UInt64 = MultipartFormData.encodingMemoryThreshold, + interceptor: RequestInterceptor? = nil, + fileManager: FileManager = .default) -> UploadRequest { + let multipartUpload = MultipartUpload(encodingMemoryThreshold: encodingMemoryThreshold, + request: request, + multipartFormData: multipartFormData) + + return upload(multipartUpload, interceptor: interceptor, fileManager: fileManager) + } + + // MARK: - Internal API + + // MARK: Uploadable + + func upload(_ uploadable: UploadRequest.Uploadable, + with convertible: URLRequestConvertible, + interceptor: RequestInterceptor?, + fileManager: FileManager) -> UploadRequest { + let uploadable = Upload(request: convertible, uploadable: uploadable) + + return upload(uploadable, interceptor: interceptor, fileManager: fileManager) + } + + func upload(_ upload: UploadConvertible, interceptor: RequestInterceptor?, fileManager: FileManager) -> UploadRequest { + let request = UploadRequest(convertible: upload, + underlyingQueue: rootQueue, + serializationQueue: serializationQueue, + eventMonitor: eventMonitor, + interceptor: interceptor, + fileManager: fileManager, + delegate: self) + + perform(request) + + return request + } + + // MARK: Perform + + /// Starts performing the provided `Request`. + /// + /// - Parameter request: The `Request` to perform. + func perform(_ request: Request) { + rootQueue.async { + guard !request.isCancelled else { return } + + self.activeRequests.insert(request) + + self.requestQueue.async { + // Leaf types must come first, otherwise they will cast as their superclass. + switch request { + case let r as UploadRequest: self.performUploadRequest(r) // UploadRequest must come before DataRequest due to subtype relationship. + case let r as DataRequest: self.performDataRequest(r) + case let r as DownloadRequest: self.performDownloadRequest(r) + case let r as DataStreamRequest: self.performDataStreamRequest(r) + default: fatalError("Attempted to perform unsupported Request subclass: \(type(of: request))") + } + } + } + } + + func performDataRequest(_ request: DataRequest) { + dispatchPrecondition(condition: .onQueue(requestQueue)) + + performSetupOperations(for: request, convertible: request.convertible) + } + + func performDataStreamRequest(_ request: DataStreamRequest) { + dispatchPrecondition(condition: .onQueue(requestQueue)) + + performSetupOperations(for: request, convertible: request.convertible) + } + + func performUploadRequest(_ request: UploadRequest) { + dispatchPrecondition(condition: .onQueue(requestQueue)) + + performSetupOperations(for: request, convertible: request.convertible) { + do { + let uploadable = try request.upload.createUploadable() + self.rootQueue.async { request.didCreateUploadable(uploadable) } + return true + } catch { + self.rootQueue.async { request.didFailToCreateUploadable(with: error.asAFError(or: .createUploadableFailed(error: error))) } + return false + } + } + } + + func performDownloadRequest(_ request: DownloadRequest) { + dispatchPrecondition(condition: .onQueue(requestQueue)) + + switch request.downloadable { + case let .request(convertible): + performSetupOperations(for: request, convertible: convertible) + case let .resumeData(resumeData): + rootQueue.async { self.didReceiveResumeData(resumeData, for: request) } + } + } + + func performSetupOperations(for request: Request, + convertible: URLRequestConvertible, + shouldCreateTask: @escaping () -> Bool = { true }) { + dispatchPrecondition(condition: .onQueue(requestQueue)) + + let initialRequest: URLRequest + + do { + initialRequest = try convertible.asURLRequest() + try initialRequest.validate() + } catch { + rootQueue.async { request.didFailToCreateURLRequest(with: error.asAFError(or: .createURLRequestFailed(error: error))) } + return + } + + rootQueue.async { request.didCreateInitialURLRequest(initialRequest) } + + guard !request.isCancelled else { return } + + guard let adapter = adapter(for: request) else { + guard shouldCreateTask() else { return } + rootQueue.async { self.didCreateURLRequest(initialRequest, for: request) } + return + } + + let adapterState = RequestAdapterState(requestID: request.id, session: self) + + adapter.adapt(initialRequest, using: adapterState) { result in + do { + let adaptedRequest = try result.get() + try adaptedRequest.validate() + + self.rootQueue.async { request.didAdaptInitialRequest(initialRequest, to: adaptedRequest) } + + guard shouldCreateTask() else { return } + + self.rootQueue.async { self.didCreateURLRequest(adaptedRequest, for: request) } + } catch { + self.rootQueue.async { request.didFailToAdaptURLRequest(initialRequest, withError: .requestAdaptationFailed(error: error)) } + } + } + } + + // MARK: - Task Handling + + func didCreateURLRequest(_ urlRequest: URLRequest, for request: Request) { + dispatchPrecondition(condition: .onQueue(rootQueue)) + + request.didCreateURLRequest(urlRequest) + + guard !request.isCancelled else { return } + + let task = request.task(for: urlRequest, using: session) + requestTaskMap[request] = task + request.didCreateTask(task) + + updateStatesForTask(task, request: request) + } + + func didReceiveResumeData(_ data: Data, for request: DownloadRequest) { + dispatchPrecondition(condition: .onQueue(rootQueue)) + + guard !request.isCancelled else { return } + + let task = request.task(forResumeData: data, using: session) + requestTaskMap[request] = task + request.didCreateTask(task) + + updateStatesForTask(task, request: request) + } + + func updateStatesForTask(_ task: URLSessionTask, request: Request) { + dispatchPrecondition(condition: .onQueue(rootQueue)) + + request.withState { state in + switch state { + case .initialized, .finished: + // Do nothing. + break + case .resumed: + task.resume() + rootQueue.async { request.didResumeTask(task) } + case .suspended: + task.suspend() + rootQueue.async { request.didSuspendTask(task) } + case .cancelled: + // Resume to ensure metrics are gathered. + task.resume() + task.cancel() + rootQueue.async { request.didCancelTask(task) } + } + } + } + + // MARK: - Adapters and Retriers + + func adapter(for request: Request) -> RequestAdapter? { + if let requestInterceptor = request.interceptor, let sessionInterceptor = interceptor { + return Interceptor(adapters: [requestInterceptor, sessionInterceptor]) + } else { + return request.interceptor ?? interceptor + } + } + + func retrier(for request: Request) -> RequestRetrier? { + if let requestInterceptor = request.interceptor, let sessionInterceptor = interceptor { + return Interceptor(retriers: [requestInterceptor, sessionInterceptor]) + } else { + return request.interceptor ?? interceptor + } + } + + // MARK: - Invalidation + + func finishRequestsForDeinit() { + requestTaskMap.requests.forEach { request in + rootQueue.async { + request.finish(error: AFError.sessionDeinitialized) + } + } + } +} + +// MARK: - RequestDelegate + +extension Session: RequestDelegate { + public var sessionConfiguration: URLSessionConfiguration { + session.configuration + } + + public var startImmediately: Bool { startRequestsImmediately } + + public func cleanup(after request: Request) { + activeRequests.remove(request) + } + + public func retryResult(for request: Request, dueTo error: AFError, completion: @escaping (RetryResult) -> Void) { + guard let retrier = retrier(for: request) else { + rootQueue.async { completion(.doNotRetry) } + return + } + + retrier.retry(request, for: self, dueTo: error) { retryResult in + self.rootQueue.async { + guard let retryResultError = retryResult.error else { completion(retryResult); return } + + let retryError = AFError.requestRetryFailed(retryError: retryResultError, originalError: error) + completion(.doNotRetryWithError(retryError)) + } + } + } + + public func retryRequest(_ request: Request, withDelay timeDelay: TimeInterval?) { + rootQueue.async { + let retry: () -> Void = { + guard !request.isCancelled else { return } + + request.prepareForRetry() + self.perform(request) + } + + if let retryDelay = timeDelay { + self.rootQueue.after(retryDelay) { retry() } + } else { + retry() + } + } + } +} + +// MARK: - SessionStateProvider + +extension Session: SessionStateProvider { + func request(for task: URLSessionTask) -> Request? { + dispatchPrecondition(condition: .onQueue(rootQueue)) + + return requestTaskMap[task] + } + + func didGatherMetricsForTask(_ task: URLSessionTask) { + dispatchPrecondition(condition: .onQueue(rootQueue)) + + let didDisassociate = requestTaskMap.disassociateIfNecessaryAfterGatheringMetricsForTask(task) + + if didDisassociate { + waitingCompletions[task]?() + waitingCompletions[task] = nil + } + } + + func didCompleteTask(_ task: URLSessionTask, completion: @escaping () -> Void) { + dispatchPrecondition(condition: .onQueue(rootQueue)) + + let didDisassociate = requestTaskMap.disassociateIfNecessaryAfterCompletingTask(task) + + if didDisassociate { + completion() + } else { + waitingCompletions[task] = completion + } + } + + func credential(for task: URLSessionTask, in protectionSpace: URLProtectionSpace) -> URLCredential? { + dispatchPrecondition(condition: .onQueue(rootQueue)) + + return requestTaskMap[task]?.credential ?? + session.configuration.urlCredentialStorage?.defaultCredential(for: protectionSpace) + } + + func cancelRequestsForSessionInvalidation(with error: Error?) { + dispatchPrecondition(condition: .onQueue(rootQueue)) + + requestTaskMap.requests.forEach { $0.finish(error: AFError.sessionInvalidated(error: error)) } + } +} diff --git a/Pods/Alamofire/Source/SessionDelegate.swift b/Pods/Alamofire/Source/SessionDelegate.swift new file mode 100644 index 0000000..a794d83 --- /dev/null +++ b/Pods/Alamofire/Source/SessionDelegate.swift @@ -0,0 +1,336 @@ +// +// 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 + +/// Class which implements the various `URLSessionDelegate` methods to connect various Alamofire features. +open class SessionDelegate: NSObject { + private let fileManager: FileManager + + weak var stateProvider: SessionStateProvider? + var eventMonitor: EventMonitor? + + /// Creates an instance from the given `FileManager`. + /// + /// - Parameter fileManager: `FileManager` to use for underlying file management, such as moving downloaded files. + /// `.default` by default. + public init(fileManager: FileManager = .default) { + self.fileManager = fileManager + } + + /// Internal method to find and cast requests while maintaining some integrity checking. + /// + /// - Parameters: + /// - task: The `URLSessionTask` for which to find the associated `Request`. + /// - type: The `Request` subclass type to cast any `Request` associate with `task`. + func request(for task: URLSessionTask, as type: R.Type) -> R? { + guard let provider = stateProvider else { + assertionFailure("StateProvider is nil.") + return nil + } + + return provider.request(for: task) as? R + } +} + +/// Type which provides various `Session` state values. +protocol SessionStateProvider: AnyObject { + var serverTrustManager: ServerTrustManager? { get } + var redirectHandler: RedirectHandler? { get } + var cachedResponseHandler: CachedResponseHandler? { get } + + func request(for task: URLSessionTask) -> Request? + func didGatherMetricsForTask(_ task: URLSessionTask) + func didCompleteTask(_ task: URLSessionTask, completion: @escaping () -> Void) + func credential(for task: URLSessionTask, in protectionSpace: URLProtectionSpace) -> URLCredential? + func cancelRequestsForSessionInvalidation(with error: Error?) +} + +// MARK: URLSessionDelegate + +extension SessionDelegate: URLSessionDelegate { + open func urlSession(_ session: URLSession, didBecomeInvalidWithError error: Error?) { + eventMonitor?.urlSession(session, didBecomeInvalidWithError: error) + + stateProvider?.cancelRequestsForSessionInvalidation(with: error) + } +} + +// MARK: URLSessionTaskDelegate + +extension SessionDelegate: URLSessionTaskDelegate { + /// Result of a `URLAuthenticationChallenge` evaluation. + typealias ChallengeEvaluation = (disposition: URLSession.AuthChallengeDisposition, credential: URLCredential?, error: AFError?) + + open func urlSession(_ session: URLSession, + task: URLSessionTask, + didReceive challenge: URLAuthenticationChallenge, + completionHandler: @escaping (URLSession.AuthChallengeDisposition, URLCredential?) -> Void) { + eventMonitor?.urlSession(session, task: task, didReceive: challenge) + + let evaluation: ChallengeEvaluation + switch challenge.protectionSpace.authenticationMethod { + case NSURLAuthenticationMethodHTTPBasic, NSURLAuthenticationMethodHTTPDigest, NSURLAuthenticationMethodNTLM, + NSURLAuthenticationMethodNegotiate: + evaluation = attemptCredentialAuthentication(for: challenge, belongingTo: task) + #if !(os(Linux) || os(Windows)) + case NSURLAuthenticationMethodServerTrust: + evaluation = attemptServerTrustAuthentication(with: challenge) + case NSURLAuthenticationMethodClientCertificate: + evaluation = attemptCredentialAuthentication(for: challenge, belongingTo: task) + #endif + default: + evaluation = (.performDefaultHandling, nil, nil) + } + + if let error = evaluation.error { + stateProvider?.request(for: task)?.didFailTask(task, earlyWithError: error) + } + + completionHandler(evaluation.disposition, evaluation.credential) + } + + #if !(os(Linux) || os(Windows)) + /// Evaluates the server trust `URLAuthenticationChallenge` received. + /// + /// - Parameter challenge: The `URLAuthenticationChallenge`. + /// + /// - Returns: The `ChallengeEvaluation`. + func attemptServerTrustAuthentication(with challenge: URLAuthenticationChallenge) -> ChallengeEvaluation { + let host = challenge.protectionSpace.host + + guard challenge.protectionSpace.authenticationMethod == NSURLAuthenticationMethodServerTrust, + let trust = challenge.protectionSpace.serverTrust + else { + return (.performDefaultHandling, nil, nil) + } + + do { + guard let evaluator = try stateProvider?.serverTrustManager?.serverTrustEvaluator(forHost: host) else { + return (.performDefaultHandling, nil, nil) + } + + try evaluator.evaluate(trust, forHost: host) + + return (.useCredential, URLCredential(trust: trust), nil) + } catch { + return (.cancelAuthenticationChallenge, nil, error.asAFError(or: .serverTrustEvaluationFailed(reason: .customEvaluationFailed(error: error)))) + } + } + #endif + + /// Evaluates the credential-based authentication `URLAuthenticationChallenge` received for `task`. + /// + /// - Parameters: + /// - challenge: The `URLAuthenticationChallenge`. + /// - task: The `URLSessionTask` which received the challenge. + /// + /// - Returns: The `ChallengeEvaluation`. + func attemptCredentialAuthentication(for challenge: URLAuthenticationChallenge, + belongingTo task: URLSessionTask) -> ChallengeEvaluation { + guard challenge.previousFailureCount == 0 else { + return (.rejectProtectionSpace, nil, nil) + } + + guard let credential = stateProvider?.credential(for: task, in: challenge.protectionSpace) else { + return (.performDefaultHandling, nil, nil) + } + + return (.useCredential, credential, nil) + } + + open func urlSession(_ session: URLSession, + task: URLSessionTask, + didSendBodyData bytesSent: Int64, + totalBytesSent: Int64, + totalBytesExpectedToSend: Int64) { + eventMonitor?.urlSession(session, + task: task, + didSendBodyData: bytesSent, + totalBytesSent: totalBytesSent, + totalBytesExpectedToSend: totalBytesExpectedToSend) + + stateProvider?.request(for: task)?.updateUploadProgress(totalBytesSent: totalBytesSent, + totalBytesExpectedToSend: totalBytesExpectedToSend) + } + + open func urlSession(_ session: URLSession, + task: URLSessionTask, + needNewBodyStream completionHandler: @escaping (InputStream?) -> Void) { + eventMonitor?.urlSession(session, taskNeedsNewBodyStream: task) + + guard let request = request(for: task, as: UploadRequest.self) else { + assertionFailure("needNewBodyStream did not find UploadRequest.") + completionHandler(nil) + return + } + + completionHandler(request.inputStream()) + } + + open func urlSession(_ session: URLSession, + task: URLSessionTask, + willPerformHTTPRedirection response: HTTPURLResponse, + newRequest request: URLRequest, + completionHandler: @escaping (URLRequest?) -> Void) { + eventMonitor?.urlSession(session, task: task, willPerformHTTPRedirection: response, newRequest: request) + + if let redirectHandler = stateProvider?.request(for: task)?.redirectHandler ?? stateProvider?.redirectHandler { + redirectHandler.task(task, willBeRedirectedTo: request, for: response, completion: completionHandler) + } else { + completionHandler(request) + } + } + + open func urlSession(_ session: URLSession, task: URLSessionTask, didFinishCollecting metrics: URLSessionTaskMetrics) { + eventMonitor?.urlSession(session, task: task, didFinishCollecting: metrics) + + stateProvider?.request(for: task)?.didGatherMetrics(metrics) + + stateProvider?.didGatherMetricsForTask(task) + } + + open func urlSession(_ session: URLSession, task: URLSessionTask, didCompleteWithError error: Error?) { + eventMonitor?.urlSession(session, task: task, didCompleteWithError: error) + + let request = stateProvider?.request(for: task) + + stateProvider?.didCompleteTask(task) { + request?.didCompleteTask(task, with: error.map { $0.asAFError(or: .sessionTaskFailed(error: $0)) }) + } + } + + @available(macOS 10.13, iOS 11.0, tvOS 11.0, watchOS 4.0, *) + open func urlSession(_ session: URLSession, taskIsWaitingForConnectivity task: URLSessionTask) { + eventMonitor?.urlSession(session, taskIsWaitingForConnectivity: task) + } +} + +// MARK: URLSessionDataDelegate + +extension SessionDelegate: URLSessionDataDelegate { + open func urlSession(_ session: URLSession, dataTask: URLSessionDataTask, didReceive data: Data) { + eventMonitor?.urlSession(session, dataTask: dataTask, didReceive: data) + + if let request = request(for: dataTask, as: DataRequest.self) { + request.didReceive(data: data) + } else if let request = request(for: dataTask, as: DataStreamRequest.self) { + request.didReceive(data: data) + } else { + assertionFailure("dataTask did not find DataRequest or DataStreamRequest in didReceive") + return + } + } + + open func urlSession(_ session: URLSession, + dataTask: URLSessionDataTask, + willCacheResponse proposedResponse: CachedURLResponse, + completionHandler: @escaping (CachedURLResponse?) -> Void) { + eventMonitor?.urlSession(session, dataTask: dataTask, willCacheResponse: proposedResponse) + + if let handler = stateProvider?.request(for: dataTask)?.cachedResponseHandler ?? stateProvider?.cachedResponseHandler { + handler.dataTask(dataTask, willCacheResponse: proposedResponse, completion: completionHandler) + } else { + completionHandler(proposedResponse) + } + } +} + +// MARK: URLSessionDownloadDelegate + +extension SessionDelegate: URLSessionDownloadDelegate { + open func urlSession(_ session: URLSession, + downloadTask: URLSessionDownloadTask, + didResumeAtOffset fileOffset: Int64, + expectedTotalBytes: Int64) { + eventMonitor?.urlSession(session, + downloadTask: downloadTask, + didResumeAtOffset: fileOffset, + expectedTotalBytes: expectedTotalBytes) + guard let downloadRequest = request(for: downloadTask, as: DownloadRequest.self) else { + assertionFailure("downloadTask did not find DownloadRequest.") + return + } + + downloadRequest.updateDownloadProgress(bytesWritten: fileOffset, + totalBytesExpectedToWrite: expectedTotalBytes) + } + + open func urlSession(_ session: URLSession, + downloadTask: URLSessionDownloadTask, + didWriteData bytesWritten: Int64, + totalBytesWritten: Int64, + totalBytesExpectedToWrite: Int64) { + eventMonitor?.urlSession(session, + downloadTask: downloadTask, + didWriteData: bytesWritten, + totalBytesWritten: totalBytesWritten, + totalBytesExpectedToWrite: totalBytesExpectedToWrite) + guard let downloadRequest = request(for: downloadTask, as: DownloadRequest.self) else { + assertionFailure("downloadTask did not find DownloadRequest.") + return + } + + downloadRequest.updateDownloadProgress(bytesWritten: bytesWritten, + totalBytesExpectedToWrite: totalBytesExpectedToWrite) + } + + open func urlSession(_ session: URLSession, downloadTask: URLSessionDownloadTask, didFinishDownloadingTo location: URL) { + eventMonitor?.urlSession(session, downloadTask: downloadTask, didFinishDownloadingTo: location) + + guard let request = request(for: downloadTask, as: DownloadRequest.self) else { + assertionFailure("downloadTask did not find DownloadRequest.") + return + } + + let (destination, options): (URL, DownloadRequest.Options) + if let response = request.response { + (destination, options) = request.destination(location, response) + } else { + // If there's no response this is likely a local file download, so generate the temporary URL directly. + (destination, options) = (DownloadRequest.defaultDestinationURL(location), []) + } + + eventMonitor?.request(request, didCreateDestinationURL: destination) + + do { + if options.contains(.removePreviousFile), fileManager.fileExists(atPath: destination.path) { + try fileManager.removeItem(at: destination) + } + + if options.contains(.createIntermediateDirectories) { + let directory = destination.deletingLastPathComponent() + try fileManager.createDirectory(at: directory, withIntermediateDirectories: true) + } + + try fileManager.moveItem(at: location, to: destination) + + request.didFinishDownloading(using: downloadTask, with: .success(destination)) + } catch { + request.didFinishDownloading(using: downloadTask, with: .failure(.downloadedFileMoveFailed(error: error, + source: location, + destination: destination))) + } + } +} diff --git a/Pods/Alamofire/Source/StringEncoding+Alamofire.swift b/Pods/Alamofire/Source/StringEncoding+Alamofire.swift new file mode 100644 index 0000000..8fa6133 --- /dev/null +++ b/Pods/Alamofire/Source/StringEncoding+Alamofire.swift @@ -0,0 +1,55 @@ +// +// StringEncoding+Alamofire.swift +// +// Copyright (c) 2020 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 String.Encoding { + /// Creates an encoding from the IANA charset name. + /// + /// - Notes: These mappings match those [provided by CoreFoundation](https://opensource.apple.com/source/CF/CF-476.18/CFStringUtilities.c.auto.html) + /// + /// - Parameter name: IANA charset name. + init?(ianaCharsetName name: String) { + switch name.lowercased() { + case "utf-8": + self = .utf8 + case "iso-8859-1": + self = .isoLatin1 + case "unicode-1-1", "iso-10646-ucs-2", "utf-16": + self = .utf16 + case "utf-16be": + self = .utf16BigEndian + case "utf-16le": + self = .utf16LittleEndian + case "utf-32": + self = .utf32 + case "utf-32be": + self = .utf32BigEndian + case "utf-32le": + self = .utf32LittleEndian + default: + return nil + } + } +} diff --git a/Pods/Alamofire/Source/URLConvertible+URLRequestConvertible.swift b/Pods/Alamofire/Source/URLConvertible+URLRequestConvertible.swift new file mode 100644 index 0000000..455c4bc --- /dev/null +++ b/Pods/Alamofire/Source/URLConvertible+URLRequestConvertible.swift @@ -0,0 +1,105 @@ +// +// URLConvertible+URLRequestConvertible.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 `URL`s, which can then be used to construct +/// `URLRequests`. +public protocol URLConvertible { + /// Returns a `URL` from the conforming instance or throws. + /// + /// - Returns: The `URL` created from the instance. + /// - Throws: Any error thrown while creating the `URL`. + func asURL() throws -> URL +} + +extension String: URLConvertible { + /// Returns a `URL` if `self` can be used to initialize a `URL` instance, otherwise throws. + /// + /// - Returns: The `URL` initialized with `self`. + /// - Throws: An `AFError.invalidURL` instance. + 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 { self } +} + +extension URLComponents: URLConvertible { + /// Returns a `URL` if the `self`'s `url` is not nil, otherwise throws. + /// + /// - Returns: The `URL` from the `url` property. + /// - Throws: An `AFError.invalidURL` instance. + 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 safely construct `URLRequest`s. +public protocol URLRequestConvertible { + /// Returns a `URLRequest` or throws if an `Error` was encountered. + /// + /// - Returns: A `URLRequest`. + /// - Throws: Any error thrown while constructing the `URLRequest`. + func asURLRequest() throws -> URLRequest +} + +extension URLRequestConvertible { + /// The `URLRequest` returned by discarding any `Error` encountered. + public var urlRequest: URLRequest? { try? asURLRequest() } +} + +extension URLRequest: URLRequestConvertible { + /// Returns `self`. + public func asURLRequest() throws -> URLRequest { self } +} + +// MARK: - + +extension URLRequest { + /// Creates an instance with the specified `url`, `method`, and `headers`. + /// + /// - Parameters: + /// - url: The `URLConvertible` value. + /// - method: The `HTTPMethod`. + /// - headers: The `HTTPHeaders`, `nil` by default. + /// - Throws: Any error thrown while converting the `URLConvertible` to a `URL`. + public init(url: URLConvertible, method: HTTPMethod, headers: HTTPHeaders? = nil) throws { + let url = try url.asURL() + + self.init(url: url) + + httpMethod = method.rawValue + allHTTPHeaderFields = headers?.dictionary + } +} diff --git a/Pods/Alamofire/Source/URLEncodedFormEncoder.swift b/Pods/Alamofire/Source/URLEncodedFormEncoder.swift new file mode 100644 index 0000000..dcb5991 --- /dev/null +++ b/Pods/Alamofire/Source/URLEncodedFormEncoder.swift @@ -0,0 +1,1083 @@ +// +// URLEncodedFormEncoder.swift +// +// Copyright (c) 2019 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 + +/// An object that encodes instances into URL-encoded query strings. +/// +/// `ArrayEncoding` can be used to configure how `Array` values are encoded. By default, the `.brackets` encoding is +/// used, encoding array values with brackets for each value. e.g `array[]=1&array[]=2`. +/// +/// `BoolEncoding` can be used to configure how `Bool` values are encoded. By default, the `.numeric` encoding is used, +/// encoding `true` as `1` and `false` as `0`. +/// +/// `DataEncoding` can be used to configure how `Data` values are encoded. By default, the `.deferredToData` encoding is +/// used, which encodes `Data` values using their default `Encodable` implementation. +/// +/// `DateEncoding` can be used to configure how `Date` values are encoded. By default, the `.deferredToDate` +/// encoding is used, which encodes `Date`s using their default `Encodable` implementation. +/// +/// `KeyEncoding` can be used to configure how keys are encoded. By default, the `.useDefaultKeys` encoding is used, +/// which encodes the keys directly from the `Encodable` implementation. +/// +/// `KeyPathEncoding` can be used to configure how paths within nested objects are encoded. By default, the `.brackets` +/// encoding is used, which encodes each sub-key in brackets. e.g. `parent[child][grandchild]=value`. +/// +/// `NilEncoding` can be used to configure how `nil` `Optional` values are encoded. By default, the `.dropKey` encoding +/// is used, which drops `nil` key / value pairs from the output entirely. +/// +/// `SpaceEncoding` can be used to configure how spaces are encoded. By default, the `.percentEscaped` encoding is used, +/// replacing spaces with `%20`. +/// +/// This type is largely based on Vapor's [`url-encoded-form`](https://github.com/vapor/url-encoded-form) project. +public final class URLEncodedFormEncoder { + /// Encoding to use for `Array` values. + public enum ArrayEncoding { + /// An empty set of square brackets ("[]") are appended to the key for every value. This is the default encoding. + case brackets + /// No brackets are appended to the key and the key is encoded as is. + case noBrackets + /// Brackets containing the item index are appended. This matches the jQuery and Node.js behavior. + case indexInBrackets + /// Provide a custom array key encoding with the given closure. + case custom((_ key: String, _ index: Int) -> String) + + /// Encodes the key according to the encoding. + /// + /// - Parameters: + /// - key: The `key` to encode. + /// - index: When this enum instance is `.indexInBrackets`, the `index` to encode. + /// + /// - Returns: The encoded key. + func encode(_ key: String, atIndex index: Int) -> String { + switch self { + case .brackets: return "\(key)[]" + case .noBrackets: return key + case .indexInBrackets: return "\(key)[\(index)]" + case let .custom(encoding): return encoding(key, index) + } + } + } + + /// Encoding to use for `Bool` values. + public enum BoolEncoding { + /// Encodes `true` as `1`, `false` as `0`. + case numeric + /// Encodes `true` as "true", `false` as "false". This is the default encoding. + case literal + + /// Encodes the given `Bool` as a `String`. + /// + /// - Parameter value: The `Bool` to encode. + /// + /// - Returns: The encoded `String`. + func encode(_ value: Bool) -> String { + switch self { + case .numeric: return value ? "1" : "0" + case .literal: return value ? "true" : "false" + } + } + } + + /// Encoding to use for `Data` values. + public enum DataEncoding { + /// Defers encoding to the `Data` type. + case deferredToData + /// Encodes `Data` as a Base64-encoded string. This is the default encoding. + case base64 + /// Encode the `Data` as a custom value encoded by the given closure. + case custom((Data) throws -> String) + + /// Encodes `Data` according to the encoding. + /// + /// - Parameter data: The `Data` to encode. + /// + /// - Returns: The encoded `String`, or `nil` if the `Data` should be encoded according to its + /// `Encodable` implementation. + func encode(_ data: Data) throws -> String? { + switch self { + case .deferredToData: return nil + case .base64: return data.base64EncodedString() + case let .custom(encoding): return try encoding(data) + } + } + } + + /// Encoding to use for `Date` values. + public enum DateEncoding { + /// ISO8601 and RFC3339 formatter. + private static let iso8601Formatter: ISO8601DateFormatter = { + let formatter = ISO8601DateFormatter() + formatter.formatOptions = .withInternetDateTime + return formatter + }() + + /// Defers encoding to the `Date` type. This is the default encoding. + case deferredToDate + /// Encodes `Date`s as seconds since midnight UTC on January 1, 1970. + case secondsSince1970 + /// Encodes `Date`s as milliseconds since midnight UTC on January 1, 1970. + case millisecondsSince1970 + /// Encodes `Date`s according to the ISO8601 and RFC3339 standards. + case iso8601 + /// Encodes `Date`s using the given `DateFormatter`. + case formatted(DateFormatter) + /// Encodes `Date`s using the given closure. + case custom((Date) throws -> String) + + /// Encodes the date according to the encoding. + /// + /// - Parameter date: The `Date` to encode. + /// + /// - Returns: The encoded `String`, or `nil` if the `Date` should be encoded according to its + /// `Encodable` implementation. + func encode(_ date: Date) throws -> String? { + switch self { + case .deferredToDate: + return nil + case .secondsSince1970: + return String(date.timeIntervalSince1970) + case .millisecondsSince1970: + return String(date.timeIntervalSince1970 * 1000.0) + case .iso8601: + return DateEncoding.iso8601Formatter.string(from: date) + case let .formatted(formatter): + return formatter.string(from: date) + case let .custom(closure): + return try closure(date) + } + } + } + + /// Encoding to use for keys. + /// + /// This type is derived from [`JSONEncoder`'s `KeyEncodingStrategy`](https://github.com/apple/swift/blob/6aa313b8dd5f05135f7f878eccc1db6f9fbe34ff/stdlib/public/Darwin/Foundation/JSONEncoder.swift#L128) + /// and [`XMLEncoder`s `KeyEncodingStrategy`](https://github.com/MaxDesiatov/XMLCoder/blob/master/Sources/XMLCoder/Encoder/XMLEncoder.swift#L102). + public enum KeyEncoding { + /// Use the keys specified by each type. This is the default encoding. + case useDefaultKeys + /// Convert from "camelCaseKeys" to "snake_case_keys" before writing a key. + /// + /// Capital characters are determined by testing membership in + /// `CharacterSet.uppercaseLetters` and `CharacterSet.lowercaseLetters` + /// (Unicode General Categories Lu and Lt). + /// The conversion to lower case uses `Locale.system`, also known as + /// the ICU "root" locale. This means the result is consistent + /// regardless of the current user's locale and language preferences. + /// + /// Converting from camel case to snake case: + /// 1. Splits words at the boundary of lower-case to upper-case + /// 2. Inserts `_` between words + /// 3. Lowercases the entire string + /// 4. Preserves starting and ending `_`. + /// + /// For example, `oneTwoThree` becomes `one_two_three`. `_oneTwoThree_` becomes `_one_two_three_`. + /// + /// - Note: Using a key encoding strategy has a nominal performance cost, as each string key has to be converted. + case convertToSnakeCase + /// Same as convertToSnakeCase, but using `-` instead of `_`. + /// For example `oneTwoThree` becomes `one-two-three`. + case convertToKebabCase + /// Capitalize the first letter only. + /// For example `oneTwoThree` becomes `OneTwoThree`. + case capitalized + /// Uppercase all letters. + /// For example `oneTwoThree` becomes `ONETWOTHREE`. + case uppercased + /// Lowercase all letters. + /// For example `oneTwoThree` becomes `onetwothree`. + case lowercased + /// A custom encoding using the provided closure. + case custom((String) -> String) + + func encode(_ key: String) -> String { + switch self { + case .useDefaultKeys: return key + case .convertToSnakeCase: return convertToSnakeCase(key) + case .convertToKebabCase: return convertToKebabCase(key) + case .capitalized: return String(key.prefix(1).uppercased() + key.dropFirst()) + case .uppercased: return key.uppercased() + case .lowercased: return key.lowercased() + case let .custom(encoding): return encoding(key) + } + } + + private func convertToSnakeCase(_ key: String) -> String { + convert(key, usingSeparator: "_") + } + + private func convertToKebabCase(_ key: String) -> String { + convert(key, usingSeparator: "-") + } + + private func convert(_ key: String, usingSeparator separator: String) -> String { + guard !key.isEmpty else { return key } + + var words: [Range] = [] + // The general idea of this algorithm is to split words on + // transition from lower to upper case, then on transition of >1 + // upper case characters to lowercase + // + // myProperty -> my_property + // myURLProperty -> my_url_property + // + // It is assumed, per Swift naming conventions, that the first character of the key is lowercase. + var wordStart = key.startIndex + var searchRange = key.index(after: wordStart)..1 capital letters. Turn those into a word, stopping at the capital before + // the lower case character. + let beforeLowerIndex = key.index(before: lowerCaseRange.lowerBound) + words.append(upperCaseRange.lowerBound.. String + + /// Creates an instance with the encoding closure called for each sub-key in a key path. + /// + /// - Parameter encoding: Closure used to perform the encoding. + public init(encoding: @escaping (_ subkey: String) -> String) { + self.encoding = encoding + } + + func encodeKeyPath(_ keyPath: String) -> String { + encoding(keyPath) + } + } + + /// Encoding to use for `nil` values. + public struct NilEncoding { + /// Encodes `nil` by dropping the entire key / value pair. + public static let dropKey = NilEncoding { nil } + /// Encodes `nil` by dropping only the value. e.g. `value1=one&nilValue=&value2=two`. + public static let dropValue = NilEncoding { "" } + /// Encodes `nil` as `null`. + public static let null = NilEncoding { "null" } + + private let encoding: () -> String? + + /// Creates an instance with the encoding closure called for `nil` values. + /// + /// - Parameter encoding: Closure used to perform the encoding. + public init(encoding: @escaping () -> String?) { + self.encoding = encoding + } + + func encodeNil() -> String? { + encoding() + } + } + + /// Encoding to use for spaces. + public enum SpaceEncoding { + /// Encodes spaces using percent escaping (`%20`). + case percentEscaped + /// Encodes spaces as `+`. + case plusReplaced + + /// Encodes the string according to the encoding. + /// + /// - Parameter string: The `String` to encode. + /// + /// - Returns: The encoded `String`. + func encode(_ string: String) -> String { + switch self { + case .percentEscaped: return string.replacingOccurrences(of: " ", with: "%20") + case .plusReplaced: return string.replacingOccurrences(of: " ", with: "+") + } + } + } + + /// `URLEncodedFormEncoder` error. + public enum Error: Swift.Error { + /// An invalid root object was created by the encoder. Only keyed values are valid. + case invalidRootObject(String) + + var localizedDescription: String { + switch self { + case let .invalidRootObject(object): + return "URLEncodedFormEncoder requires keyed root object. Received \(object) instead." + } + } + } + + /// Whether or not to sort the encoded key value pairs. + /// + /// - Note: This setting ensures a consistent ordering for all encodings of the same parameters. When set to `false`, + /// encoded `Dictionary` values may have a different encoded order each time they're encoded due to + /// ` Dictionary`'s random storage order, but `Encodable` types will maintain their encoded order. + public let alphabetizeKeyValuePairs: Bool + /// The `ArrayEncoding` to use. + public let arrayEncoding: ArrayEncoding + /// The `BoolEncoding` to use. + public let boolEncoding: BoolEncoding + /// THe `DataEncoding` to use. + public let dataEncoding: DataEncoding + /// The `DateEncoding` to use. + public let dateEncoding: DateEncoding + /// The `KeyEncoding` to use. + public let keyEncoding: KeyEncoding + /// The `KeyPathEncoding` to use. + public let keyPathEncoding: KeyPathEncoding + /// The `NilEncoding` to use. + public let nilEncoding: NilEncoding + /// The `SpaceEncoding` to use. + public let spaceEncoding: SpaceEncoding + /// The `CharacterSet` of allowed (non-escaped) characters. + public var allowedCharacters: CharacterSet + + /// Creates an instance from the supplied parameters. + /// + /// - Parameters: + /// - alphabetizeKeyValuePairs: Whether or not to sort the encoded key value pairs. `true` by default. + /// - arrayEncoding: The `ArrayEncoding` to use. `.brackets` by default. + /// - boolEncoding: The `BoolEncoding` to use. `.numeric` by default. + /// - dataEncoding: The `DataEncoding` to use. `.base64` by default. + /// - dateEncoding: The `DateEncoding` to use. `.deferredToDate` by default. + /// - keyEncoding: The `KeyEncoding` to use. `.useDefaultKeys` by default. + /// - nilEncoding: The `NilEncoding` to use. `.drop` by default. + /// - spaceEncoding: The `SpaceEncoding` to use. `.percentEscaped` by default. + /// - allowedCharacters: The `CharacterSet` of allowed (non-escaped) characters. `.afURLQueryAllowed` by + /// default. + public init(alphabetizeKeyValuePairs: Bool = true, + arrayEncoding: ArrayEncoding = .brackets, + boolEncoding: BoolEncoding = .numeric, + dataEncoding: DataEncoding = .base64, + dateEncoding: DateEncoding = .deferredToDate, + keyEncoding: KeyEncoding = .useDefaultKeys, + keyPathEncoding: KeyPathEncoding = .brackets, + nilEncoding: NilEncoding = .dropKey, + spaceEncoding: SpaceEncoding = .percentEscaped, + allowedCharacters: CharacterSet = .afURLQueryAllowed) { + self.alphabetizeKeyValuePairs = alphabetizeKeyValuePairs + self.arrayEncoding = arrayEncoding + self.boolEncoding = boolEncoding + self.dataEncoding = dataEncoding + self.dateEncoding = dateEncoding + self.keyEncoding = keyEncoding + self.keyPathEncoding = keyPathEncoding + self.nilEncoding = nilEncoding + self.spaceEncoding = spaceEncoding + self.allowedCharacters = allowedCharacters + } + + func encode(_ value: Encodable) throws -> URLEncodedFormComponent { + let context = URLEncodedFormContext(.object([])) + let encoder = _URLEncodedFormEncoder(context: context, + boolEncoding: boolEncoding, + dataEncoding: dataEncoding, + dateEncoding: dateEncoding, + nilEncoding: nilEncoding) + try value.encode(to: encoder) + + return context.component + } + + /// Encodes the `value` as a URL form encoded `String`. + /// + /// - Parameter value: The `Encodable` value.` + /// + /// - Returns: The encoded `String`. + /// - Throws: An `Error` or `EncodingError` instance if encoding fails. + public func encode(_ value: Encodable) throws -> String { + let component: URLEncodedFormComponent = try encode(value) + + guard case let .object(object) = component else { + throw Error.invalidRootObject("\(component)") + } + + let serializer = URLEncodedFormSerializer(alphabetizeKeyValuePairs: alphabetizeKeyValuePairs, + arrayEncoding: arrayEncoding, + keyEncoding: keyEncoding, + keyPathEncoding: keyPathEncoding, + spaceEncoding: spaceEncoding, + allowedCharacters: allowedCharacters) + let query = serializer.serialize(object) + + return query + } + + /// Encodes the value as `Data`. This is performed by first creating an encoded `String` and then returning the + /// `.utf8` data. + /// + /// - Parameter value: The `Encodable` value. + /// + /// - Returns: The encoded `Data`. + /// + /// - Throws: An `Error` or `EncodingError` instance if encoding fails. + public func encode(_ value: Encodable) throws -> Data { + let string: String = try encode(value) + + return Data(string.utf8) + } +} + +final class _URLEncodedFormEncoder { + var codingPath: [CodingKey] + // Returns an empty dictionary, as this encoder doesn't support userInfo. + var userInfo: [CodingUserInfoKey: Any] { [:] } + + let context: URLEncodedFormContext + + private let boolEncoding: URLEncodedFormEncoder.BoolEncoding + private let dataEncoding: URLEncodedFormEncoder.DataEncoding + private let dateEncoding: URLEncodedFormEncoder.DateEncoding + private let nilEncoding: URLEncodedFormEncoder.NilEncoding + + init(context: URLEncodedFormContext, + codingPath: [CodingKey] = [], + boolEncoding: URLEncodedFormEncoder.BoolEncoding, + dataEncoding: URLEncodedFormEncoder.DataEncoding, + dateEncoding: URLEncodedFormEncoder.DateEncoding, + nilEncoding: URLEncodedFormEncoder.NilEncoding) { + self.context = context + self.codingPath = codingPath + self.boolEncoding = boolEncoding + self.dataEncoding = dataEncoding + self.dateEncoding = dateEncoding + self.nilEncoding = nilEncoding + } +} + +extension _URLEncodedFormEncoder: Encoder { + func container(keyedBy type: Key.Type) -> KeyedEncodingContainer where Key: CodingKey { + let container = _URLEncodedFormEncoder.KeyedContainer(context: context, + codingPath: codingPath, + boolEncoding: boolEncoding, + dataEncoding: dataEncoding, + dateEncoding: dateEncoding, + nilEncoding: nilEncoding) + return KeyedEncodingContainer(container) + } + + func unkeyedContainer() -> UnkeyedEncodingContainer { + _URLEncodedFormEncoder.UnkeyedContainer(context: context, + codingPath: codingPath, + boolEncoding: boolEncoding, + dataEncoding: dataEncoding, + dateEncoding: dateEncoding, + nilEncoding: nilEncoding) + } + + func singleValueContainer() -> SingleValueEncodingContainer { + _URLEncodedFormEncoder.SingleValueContainer(context: context, + codingPath: codingPath, + boolEncoding: boolEncoding, + dataEncoding: dataEncoding, + dateEncoding: dateEncoding, + nilEncoding: nilEncoding) + } +} + +final class URLEncodedFormContext { + var component: URLEncodedFormComponent + + init(_ component: URLEncodedFormComponent) { + self.component = component + } +} + +enum URLEncodedFormComponent { + typealias Object = [(key: String, value: URLEncodedFormComponent)] + + case string(String) + case array([URLEncodedFormComponent]) + case object(Object) + + /// Converts self to an `[URLEncodedFormData]` or returns `nil` if not convertible. + var array: [URLEncodedFormComponent]? { + switch self { + case let .array(array): return array + default: return nil + } + } + + /// Converts self to an `Object` or returns `nil` if not convertible. + var object: Object? { + switch self { + case let .object(object): return object + default: return nil + } + } + + /// Sets self to the supplied value at a given path. + /// + /// data.set(to: "hello", at: ["path", "to", "value"]) + /// + /// - parameters: + /// - value: Value of `Self` to set at the supplied path. + /// - path: `CodingKey` path to update with the supplied value. + public mutating func set(to value: URLEncodedFormComponent, at path: [CodingKey]) { + set(&self, to: value, at: path) + } + + /// Recursive backing method to `set(to:at:)`. + private func set(_ context: inout URLEncodedFormComponent, to value: URLEncodedFormComponent, at path: [CodingKey]) { + guard !path.isEmpty else { + context = value + return + } + + let end = path[0] + var child: URLEncodedFormComponent + switch path.count { + case 1: + child = value + case 2...: + if let index = end.intValue { + let array = context.array ?? [] + if array.count > index { + child = array[index] + } else { + child = .array([]) + } + set(&child, to: value, at: Array(path[1...])) + } else { + child = context.object?.first { $0.key == end.stringValue }?.value ?? .object(.init()) + set(&child, to: value, at: Array(path[1...])) + } + default: fatalError("Unreachable") + } + + if let index = end.intValue { + if var array = context.array { + if array.count > index { + array[index] = child + } else { + array.append(child) + } + context = .array(array) + } else { + context = .array([child]) + } + } else { + if var object = context.object { + if let index = object.firstIndex(where: { $0.key == end.stringValue }) { + object[index] = (key: end.stringValue, value: child) + } else { + object.append((key: end.stringValue, value: child)) + } + context = .object(object) + } else { + context = .object([(key: end.stringValue, value: child)]) + } + } + } +} + +struct AnyCodingKey: CodingKey, Hashable { + let stringValue: String + let intValue: Int? + + init?(stringValue: String) { + self.stringValue = stringValue + intValue = nil + } + + init?(intValue: Int) { + stringValue = "\(intValue)" + self.intValue = intValue + } + + init(_ base: Key) where Key: CodingKey { + if let intValue = base.intValue { + self.init(intValue: intValue)! + } else { + self.init(stringValue: base.stringValue)! + } + } +} + +extension _URLEncodedFormEncoder { + final class KeyedContainer where Key: CodingKey { + var codingPath: [CodingKey] + + private let context: URLEncodedFormContext + private let boolEncoding: URLEncodedFormEncoder.BoolEncoding + private let dataEncoding: URLEncodedFormEncoder.DataEncoding + private let dateEncoding: URLEncodedFormEncoder.DateEncoding + private let nilEncoding: URLEncodedFormEncoder.NilEncoding + + init(context: URLEncodedFormContext, + codingPath: [CodingKey], + boolEncoding: URLEncodedFormEncoder.BoolEncoding, + dataEncoding: URLEncodedFormEncoder.DataEncoding, + dateEncoding: URLEncodedFormEncoder.DateEncoding, + nilEncoding: URLEncodedFormEncoder.NilEncoding) { + self.context = context + self.codingPath = codingPath + self.boolEncoding = boolEncoding + self.dataEncoding = dataEncoding + self.dateEncoding = dateEncoding + self.nilEncoding = nilEncoding + } + + private func nestedCodingPath(for key: CodingKey) -> [CodingKey] { + codingPath + [key] + } + } +} + +extension _URLEncodedFormEncoder.KeyedContainer: KeyedEncodingContainerProtocol { + func encodeNil(forKey key: Key) throws { + guard let nilValue = nilEncoding.encodeNil() else { return } + + try encode(nilValue, forKey: key) + } + + func encode(_ value: T, forKey key: Key) throws where T: Encodable { + var container = nestedSingleValueEncoder(for: key) + try container.encode(value) + } + + func nestedSingleValueEncoder(for key: Key) -> SingleValueEncodingContainer { + let container = _URLEncodedFormEncoder.SingleValueContainer(context: context, + codingPath: nestedCodingPath(for: key), + boolEncoding: boolEncoding, + dataEncoding: dataEncoding, + dateEncoding: dateEncoding, + nilEncoding: nilEncoding) + + return container + } + + func nestedUnkeyedContainer(forKey key: Key) -> UnkeyedEncodingContainer { + let container = _URLEncodedFormEncoder.UnkeyedContainer(context: context, + codingPath: nestedCodingPath(for: key), + boolEncoding: boolEncoding, + dataEncoding: dataEncoding, + dateEncoding: dateEncoding, + nilEncoding: nilEncoding) + + return container + } + + func nestedContainer(keyedBy keyType: NestedKey.Type, forKey key: Key) -> KeyedEncodingContainer where NestedKey: CodingKey { + let container = _URLEncodedFormEncoder.KeyedContainer(context: context, + codingPath: nestedCodingPath(for: key), + boolEncoding: boolEncoding, + dataEncoding: dataEncoding, + dateEncoding: dateEncoding, + nilEncoding: nilEncoding) + + return KeyedEncodingContainer(container) + } + + func superEncoder() -> Encoder { + _URLEncodedFormEncoder(context: context, + codingPath: codingPath, + boolEncoding: boolEncoding, + dataEncoding: dataEncoding, + dateEncoding: dateEncoding, + nilEncoding: nilEncoding) + } + + func superEncoder(forKey key: Key) -> Encoder { + _URLEncodedFormEncoder(context: context, + codingPath: nestedCodingPath(for: key), + boolEncoding: boolEncoding, + dataEncoding: dataEncoding, + dateEncoding: dateEncoding, + nilEncoding: nilEncoding) + } +} + +extension _URLEncodedFormEncoder { + final class SingleValueContainer { + var codingPath: [CodingKey] + + private var canEncodeNewValue = true + + private let context: URLEncodedFormContext + private let boolEncoding: URLEncodedFormEncoder.BoolEncoding + private let dataEncoding: URLEncodedFormEncoder.DataEncoding + private let dateEncoding: URLEncodedFormEncoder.DateEncoding + private let nilEncoding: URLEncodedFormEncoder.NilEncoding + + init(context: URLEncodedFormContext, + codingPath: [CodingKey], + boolEncoding: URLEncodedFormEncoder.BoolEncoding, + dataEncoding: URLEncodedFormEncoder.DataEncoding, + dateEncoding: URLEncodedFormEncoder.DateEncoding, + nilEncoding: URLEncodedFormEncoder.NilEncoding) { + self.context = context + self.codingPath = codingPath + self.boolEncoding = boolEncoding + self.dataEncoding = dataEncoding + self.dateEncoding = dateEncoding + self.nilEncoding = nilEncoding + } + + private func checkCanEncode(value: Any?) throws { + guard canEncodeNewValue else { + let context = EncodingError.Context(codingPath: codingPath, + debugDescription: "Attempt to encode value through single value container when previously value already encoded.") + throw EncodingError.invalidValue(value as Any, context) + } + } + } +} + +extension _URLEncodedFormEncoder.SingleValueContainer: SingleValueEncodingContainer { + func encodeNil() throws { + guard let nilValue = nilEncoding.encodeNil() else { return } + + try encode(nilValue) + } + + func encode(_ value: Bool) throws { + try encode(value, as: String(boolEncoding.encode(value))) + } + + func encode(_ value: String) throws { + try encode(value, as: value) + } + + func encode(_ value: Double) throws { + try encode(value, as: String(value)) + } + + func encode(_ value: Float) throws { + try encode(value, as: String(value)) + } + + func encode(_ value: Int) throws { + try encode(value, as: String(value)) + } + + func encode(_ value: Int8) throws { + try encode(value, as: String(value)) + } + + func encode(_ value: Int16) throws { + try encode(value, as: String(value)) + } + + func encode(_ value: Int32) throws { + try encode(value, as: String(value)) + } + + func encode(_ value: Int64) throws { + try encode(value, as: String(value)) + } + + func encode(_ value: UInt) throws { + try encode(value, as: String(value)) + } + + func encode(_ value: UInt8) throws { + try encode(value, as: String(value)) + } + + func encode(_ value: UInt16) throws { + try encode(value, as: String(value)) + } + + func encode(_ value: UInt32) throws { + try encode(value, as: String(value)) + } + + func encode(_ value: UInt64) throws { + try encode(value, as: String(value)) + } + + private func encode(_ value: T, as string: String) throws where T: Encodable { + try checkCanEncode(value: value) + defer { canEncodeNewValue = false } + + context.component.set(to: .string(string), at: codingPath) + } + + func encode(_ value: T) throws where T: Encodable { + switch value { + case let date as Date: + guard let string = try dateEncoding.encode(date) else { + try attemptToEncode(value) + return + } + + try encode(value, as: string) + case let data as Data: + guard let string = try dataEncoding.encode(data) else { + try attemptToEncode(value) + return + } + + try encode(value, as: string) + case let decimal as Decimal: + // Decimal's `Encodable` implementation returns an object, not a single value, so override it. + try encode(value, as: String(describing: decimal)) + default: + try attemptToEncode(value) + } + } + + private func attemptToEncode(_ value: T) throws where T: Encodable { + try checkCanEncode(value: value) + defer { canEncodeNewValue = false } + + let encoder = _URLEncodedFormEncoder(context: context, + codingPath: codingPath, + boolEncoding: boolEncoding, + dataEncoding: dataEncoding, + dateEncoding: dateEncoding, + nilEncoding: nilEncoding) + try value.encode(to: encoder) + } +} + +extension _URLEncodedFormEncoder { + final class UnkeyedContainer { + var codingPath: [CodingKey] + + var count = 0 + var nestedCodingPath: [CodingKey] { + codingPath + [AnyCodingKey(intValue: count)!] + } + + private let context: URLEncodedFormContext + private let boolEncoding: URLEncodedFormEncoder.BoolEncoding + private let dataEncoding: URLEncodedFormEncoder.DataEncoding + private let dateEncoding: URLEncodedFormEncoder.DateEncoding + private let nilEncoding: URLEncodedFormEncoder.NilEncoding + + init(context: URLEncodedFormContext, + codingPath: [CodingKey], + boolEncoding: URLEncodedFormEncoder.BoolEncoding, + dataEncoding: URLEncodedFormEncoder.DataEncoding, + dateEncoding: URLEncodedFormEncoder.DateEncoding, + nilEncoding: URLEncodedFormEncoder.NilEncoding) { + self.context = context + self.codingPath = codingPath + self.boolEncoding = boolEncoding + self.dataEncoding = dataEncoding + self.dateEncoding = dateEncoding + self.nilEncoding = nilEncoding + } + } +} + +extension _URLEncodedFormEncoder.UnkeyedContainer: UnkeyedEncodingContainer { + func encodeNil() throws { + guard let nilValue = nilEncoding.encodeNil() else { return } + + try encode(nilValue) + } + + func encode(_ value: T) throws where T: Encodable { + var container = nestedSingleValueContainer() + try container.encode(value) + } + + func nestedSingleValueContainer() -> SingleValueEncodingContainer { + defer { count += 1 } + + return _URLEncodedFormEncoder.SingleValueContainer(context: context, + codingPath: nestedCodingPath, + boolEncoding: boolEncoding, + dataEncoding: dataEncoding, + dateEncoding: dateEncoding, + nilEncoding: nilEncoding) + } + + func nestedContainer(keyedBy keyType: NestedKey.Type) -> KeyedEncodingContainer where NestedKey: CodingKey { + defer { count += 1 } + let container = _URLEncodedFormEncoder.KeyedContainer(context: context, + codingPath: nestedCodingPath, + boolEncoding: boolEncoding, + dataEncoding: dataEncoding, + dateEncoding: dateEncoding, + nilEncoding: nilEncoding) + + return KeyedEncodingContainer(container) + } + + func nestedUnkeyedContainer() -> UnkeyedEncodingContainer { + defer { count += 1 } + + return _URLEncodedFormEncoder.UnkeyedContainer(context: context, + codingPath: nestedCodingPath, + boolEncoding: boolEncoding, + dataEncoding: dataEncoding, + dateEncoding: dateEncoding, + nilEncoding: nilEncoding) + } + + func superEncoder() -> Encoder { + defer { count += 1 } + + return _URLEncodedFormEncoder(context: context, + codingPath: codingPath, + boolEncoding: boolEncoding, + dataEncoding: dataEncoding, + dateEncoding: dateEncoding, + nilEncoding: nilEncoding) + } +} + +final class URLEncodedFormSerializer { + private let alphabetizeKeyValuePairs: Bool + private let arrayEncoding: URLEncodedFormEncoder.ArrayEncoding + private let keyEncoding: URLEncodedFormEncoder.KeyEncoding + private let keyPathEncoding: URLEncodedFormEncoder.KeyPathEncoding + private let spaceEncoding: URLEncodedFormEncoder.SpaceEncoding + private let allowedCharacters: CharacterSet + + init(alphabetizeKeyValuePairs: Bool, + arrayEncoding: URLEncodedFormEncoder.ArrayEncoding, + keyEncoding: URLEncodedFormEncoder.KeyEncoding, + keyPathEncoding: URLEncodedFormEncoder.KeyPathEncoding, + spaceEncoding: URLEncodedFormEncoder.SpaceEncoding, + allowedCharacters: CharacterSet) { + self.alphabetizeKeyValuePairs = alphabetizeKeyValuePairs + self.arrayEncoding = arrayEncoding + self.keyEncoding = keyEncoding + self.keyPathEncoding = keyPathEncoding + self.spaceEncoding = spaceEncoding + self.allowedCharacters = allowedCharacters + } + + func serialize(_ object: URLEncodedFormComponent.Object) -> String { + var output: [String] = [] + for (key, component) in object { + let value = serialize(component, forKey: key) + output.append(value) + } + output = alphabetizeKeyValuePairs ? output.sorted() : output + + return output.joinedWithAmpersands() + } + + func serialize(_ component: URLEncodedFormComponent, forKey key: String) -> String { + switch component { + case let .string(string): return "\(escape(keyEncoding.encode(key)))=\(escape(string))" + case let .array(array): return serialize(array, forKey: key) + case let .object(object): return serialize(object, forKey: key) + } + } + + func serialize(_ object: URLEncodedFormComponent.Object, forKey key: String) -> String { + var segments: [String] = object.map { subKey, value in + let keyPath = keyPathEncoding.encodeKeyPath(subKey) + return serialize(value, forKey: key + keyPath) + } + segments = alphabetizeKeyValuePairs ? segments.sorted() : segments + + return segments.joinedWithAmpersands() + } + + func serialize(_ array: [URLEncodedFormComponent], forKey key: String) -> String { + var segments: [String] = array.enumerated().map { index, component in + let keyPath = arrayEncoding.encode(key, atIndex: index) + return serialize(component, forKey: keyPath) + } + segments = alphabetizeKeyValuePairs ? segments.sorted() : segments + + return segments.joinedWithAmpersands() + } + + func escape(_ query: String) -> String { + var allowedCharactersWithSpace = allowedCharacters + allowedCharactersWithSpace.insert(charactersIn: " ") + let escapedQuery = query.addingPercentEncoding(withAllowedCharacters: allowedCharactersWithSpace) ?? query + let spaceEncodedQuery = spaceEncoding.encode(escapedQuery) + + return spaceEncodedQuery + } +} + +extension Array where Element == String { + func joinedWithAmpersands() -> String { + joined(separator: "&") + } +} + +extension CharacterSet { + /// Creates a CharacterSet from RFC 3986 allowed characters. + /// + /// 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. + public static let afURLQueryAllowed: CharacterSet = { + let generalDelimitersToEncode = ":#[]@" // does not include "?" or "/" due to RFC 3986 - Section 3.4 + let subDelimitersToEncode = "!$&'()*+,;=" + let encodableDelimiters = CharacterSet(charactersIn: "\(generalDelimitersToEncode)\(subDelimitersToEncode)") + + return CharacterSet.urlQueryAllowed.subtracting(encodableDelimiters) + }() +} diff --git a/Pods/Alamofire/Source/URLRequest+Alamofire.swift b/Pods/Alamofire/Source/URLRequest+Alamofire.swift new file mode 100644 index 0000000..ab72fb5 --- /dev/null +++ b/Pods/Alamofire/Source/URLRequest+Alamofire.swift @@ -0,0 +1,39 @@ +// +// URLRequest+Alamofire.swift +// +// Copyright (c) 2019 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 URLRequest { + /// Returns the `httpMethod` as Alamofire's `HTTPMethod` type. + public var method: HTTPMethod? { + get { httpMethod.map(HTTPMethod.init) } + set { httpMethod = newValue?.rawValue } + } + + public func validate() throws { + if method == .get, let bodyData = httpBody { + throw AFError.urlRequestValidationFailed(reason: .bodyDataInGETRequest(bodyData)) + } + } +} diff --git a/Pods/Alamofire/Source/URLSessionConfiguration+Alamofire.swift b/Pods/Alamofire/Source/URLSessionConfiguration+Alamofire.swift new file mode 100644 index 0000000..292a8fe --- /dev/null +++ b/Pods/Alamofire/Source/URLSessionConfiguration+Alamofire.swift @@ -0,0 +1,46 @@ +// +// URLSessionConfiguration+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 + +extension URLSessionConfiguration: AlamofireExtended {} +extension AlamofireExtension where ExtendedType: URLSessionConfiguration { + /// Alamofire's default configuration. Same as `URLSessionConfiguration.default` but adds Alamofire default + /// `Accept-Language`, `Accept-Encoding`, and `User-Agent` headers. + public static var `default`: URLSessionConfiguration { + let configuration = URLSessionConfiguration.default + configuration.headers = .default + + return configuration + } + + /// `.ephemeral` configuration with Alamofire's default `Accept-Language`, `Accept-Encoding`, and `User-Agent` + /// headers. + public static var ephemeral: URLSessionConfiguration { + let configuration = URLSessionConfiguration.ephemeral + configuration.headers = .default + + return configuration + } +} diff --git a/Pods/Alamofire/Source/Validation.swift b/Pods/Alamofire/Source/Validation.swift new file mode 100644 index 0000000..2cf23fb --- /dev/null +++ b/Pods/Alamofire/Source/Validation.swift @@ -0,0 +1,302 @@ +// +// 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 a validation succeeded or failed. + public typealias ValidationResult = Result + + fileprivate struct MIMEType { + let type: String + let subtype: String + + var isWildcard: Bool { type == "*" && subtype == "*" } + + init?(_ string: String) { + let components: [String] = { + let stripped = string.trimmingCharacters(in: .whitespacesAndNewlines) + let split = stripped[..<(stripped.range(of: ";")?.lowerBound ?? stripped.endIndex)] + + return split.components(separatedBy: "/") + }() + + if let type = components.first, let subtype = components.last { + self.type = type + self.subtype = subtype + } else { + return nil + } + } + + func matches(_ mime: MIMEType) -> Bool { + switch (type, subtype) { + case (mime.type, mime.subtype), (mime.type, "*"), ("*", mime.subtype), ("*", "*"): + return true + default: + return false + } + } + } + + // MARK: Properties + + fileprivate var acceptableStatusCodes: Range { 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.isEmpty else { return .success(()) } + + return validate(contentType: acceptableContentTypes, response: response) + } + + fileprivate func validate(contentType acceptableContentTypes: S, + response: HTTPURLResponse) + -> ValidationResult + where S.Iterator.Element == String { + 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: acceptableContentTypes.sorted()) + 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: acceptableContentTypes.sorted(), + 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 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 acceptableStatusCodes: `Sequence` of acceptable response status codes. + /// + /// - Returns: The instance. + @discardableResult + public func validate(statusCode acceptableStatusCodes: S) -> Self where S.Iterator.Element == Int { + validate { [unowned self] _, response, _ in + 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: @escaping @autoclosure () -> S) -> Self where S.Iterator.Element == String { + validate { [unowned self] _, response, data in + 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 { + let contentTypes: () -> [String] = { [unowned self] in + acceptableContentTypes + } + return validate(statusCode: acceptableStatusCodes).validate(contentType: contentTypes()) + } +} + +extension DataStreamRequest { + /// A closure used to validate a request that takes a `URLRequest` and `HTTPURLResponse` and returns whether the + /// request was valid. + public typealias Validation = (_ request: URLRequest?, _ response: HTTPURLResponse) -> ValidationResult + + /// 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 acceptableStatusCodes: `Sequence` of acceptable response status codes. + /// + /// - Returns: The instance. + @discardableResult + public func validate(statusCode acceptableStatusCodes: S) -> Self where S.Iterator.Element == Int { + validate { [unowned self] _, response in + 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: @escaping @autoclosure () -> S) -> Self where S.Iterator.Element == String { + validate { [unowned self] _, response in + self.validate(contentType: acceptableContentTypes(), response: response) + } + } + + /// 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 instance. + @discardableResult + public func validate() -> Self { + let contentTypes: () -> [String] = { [unowned self] in + acceptableContentTypes + } + return validate(statusCode: acceptableStatusCodes).validate(contentType: contentTypes()) + } +} + +// 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, + _ fileURL: URL?) + -> ValidationResult + + /// 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 acceptableStatusCodes: `Sequence` of acceptable response status codes. + /// + /// - Returns: The instance. + @discardableResult + public func validate(statusCode acceptableStatusCodes: S) -> Self where S.Iterator.Element == Int { + validate { [unowned self] _, response, _ in + 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: @escaping @autoclosure () -> S) -> Self where S.Iterator.Element == String { + validate { [unowned self] _, response, fileURL in + 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 { + let contentTypes = { [unowned self] in + acceptableContentTypes + } + return validate(statusCode: acceptableStatusCodes).validate(contentType: contentTypes()) + } +} diff --git a/Pods/HandyJSON/LICENSE b/Pods/HandyJSON/LICENSE new file mode 100644 index 0000000..213436d --- /dev/null +++ b/Pods/HandyJSON/LICENSE @@ -0,0 +1,48 @@ + Copyright 1999-2016 Alibaba Group Holding Ltd. + + Licensed under the Apache License, Version 2.0 (the "License"); + you may not use this file except in compliance with the License. + You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. + +1. reflection + +The MIT License (MIT) + +Copyright (c) 2016 Brad Hilton + +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. + +2. ObjectMapper + +The MIT License (MIT) +Copyright (c) 2014 Hearst + +Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. diff --git a/Pods/HandyJSON/README.md b/Pods/HandyJSON/README.md new file mode 100644 index 0000000..2595e9b --- /dev/null +++ b/Pods/HandyJSON/README.md @@ -0,0 +1,695 @@ +# HandyJSON + +HandyJSON is a framework written in Swift which to make converting model objects( **pure classes/structs** ) to and from JSON easy on iOS. + +Compared with others, the most significant feature of HandyJSON is that it does not require the objects inherit from NSObject(**not using KVC but reflection**), neither implements a 'mapping' function(**writing value to memory directly to achieve property assignment**). + +HandyJSON is totally depend on the memory layout rules infered from Swift runtime code. We are watching it and will follow every bit if it changes. + +[![Build Status](https://travis-ci.org/alibaba/HandyJSON.svg?branch=master)](https://travis-ci.org/alibaba/HandyJSON) +[![Carthage compatible](https://img.shields.io/badge/Carthage-compatible-4BC51D.svg?style=flat)](https://github.com/Carthage/Carthage) +[![Cocoapods Version](https://img.shields.io/cocoapods/v/HandyJSON.svg?style=flat)](http://cocoadocs.org/docsets/HandyJSON) +[![Cocoapods Platform](https://img.shields.io/cocoapods/p/HandyJSON.svg?style=flat)](http://cocoadocs.org/docsets/HandyJSON) +[![Codecov branch](https://img.shields.io/codecov/c/github/alibaba/HandyJSON/master.svg?style=flat)](https://codecov.io/gh/alibaba/HandyJSON/branch/master) + +## [中文文档](./README_cn.md) + +## 交流群 + +群号: 581331250 + +![交流群](qq_group.png) + +## Sample Code + +### Deserialization + +```swift +class BasicTypes: HandyJSON { + var int: Int = 2 + var doubleOptional: Double? + var stringImplicitlyUnwrapped: String! + + required init() {} +} + +let jsonString = "{\"doubleOptional\":1.1,\"stringImplicitlyUnwrapped\":\"hello\",\"int\":1}" +if let object = BasicTypes.deserialize(from: jsonString) { + print(object.int) + print(object.doubleOptional!) + print(object.stringImplicitlyUnwrapped) +} +``` + +### Serialization + +```swift + +let object = BasicTypes() +object.int = 1 +object.doubleOptional = 1.1 +object.stringImplicitlyUnwrapped = “hello" + +print(object.toJSON()!) // serialize to dictionary +print(object.toJSONString()!) // serialize to JSON string +print(object.toJSONString(prettyPrint: true)!) // serialize to pretty JSON string +``` + +# Content + +- [Features](#features) +- [Requirements](#requirements) +- [Installation](#installation) + - [Cocoapods](#cocoapods) + - [Carthage](#carthage) + - [Manually](#manually) +- [Deserialization](#deserialization) + - [The Basics](#the-basics) + - [Support Struct](#support-struct) + - [Support Enum Property](#support-enum-property) + - [Optional/ImplicitlyUnwrappedOptional/Collections/...](#optionalimplicitlyunwrappedoptionalcollections) + - [Designated Path](#designated-path) + - [Composition Object](#composition-object) + - [Inheritance Object](#inheritance-object) + - [JSON Array](#json-array) + - [Mapping From Dictionary](#mapping-from-dictionary) + - [Custom Mapping](#custom-mapping) + - [Date/Data/URL/Decimal/Color](#datedataurldecimalcolor) + - [Exclude Property](#exclude-property) + - [Update Existing Model](#update-existing-model) + - [Supported Property Type](#supported-property-type) +- [Serialization](#serialization) + - [The Basics](#the-basics) + - [Mapping And Excluding](#mapping-and-excluding) +- [FAQ](#faq) +- [To Do](#to-do) + +# Features + +* Serialize/Deserialize Object/JSON to/From JSON/Object + +* Naturally use object property name for mapping, no need to specify a mapping relationship + +* Support almost all types in Swift, including enum + +* Support struct + +* Custom transformations + +* Type-Adaption, such as string json field maps to int property, int json field maps to string property + +An overview of types supported can be found at file: [BasicTypes.swift](./HandyJSONTest/BasicTypes.swift) + +# Requirements + +* iOS 8.0+/OSX 10.9+/watchOS 2.0+/tvOS 9.0+ + +* Swift 3.0+ / Swift 4.0+ / Swift 5.0+ + +# Installation + +**To use with Swift 5.0/5.1 ( Xcode 10.2+/11.0+ ), version == 5.0.1** + +**To use with Swift 4.2 ( Xcode 10 ), version == 4.2.0** + +**To use with Swift 4.0, version >= 4.1.1** + +**To use with Swift 3.x, version >= 1.8.0** + +For Legacy Swift2.x support, take a look at the [swift2 branch](https://github.com/alibaba/HandyJSON/tree/master_for_swift_2x). + +## Cocoapods + +Add the following line to your `Podfile`: + +``` +pod 'HandyJSON', '~> 5.0.1' +``` + +Then, run the following command: + +``` +$ pod install +``` + +## Carthage + +You can add a dependency on `HandyJSON` by adding the following line to your `Cartfile`: + +``` +github "alibaba/HandyJSON" ~> 5.0.1 +``` + +## Manually + +You can integrate `HandyJSON` into your project manually by doing the following steps: + +* Open up `Terminal`, `cd` into your top-level project directory, and add `HandyJSON` as a submodule: + +``` +git init && git submodule add https://github.com/alibaba/HandyJSON.git +``` + +* Open the new `HandyJSON` folder, drag the `HandyJSON.xcodeproj` into the `Project Navigator` of your project. + +* Select your application project in the `Project Navigator`, open the `General` panel in the right window. + +* Click on the `+` button under the `Embedded Binaries` section. + +* You will see two different `HandyJSON.xcodeproj` folders each with four different versions of the HandyJSON.framework nested inside a Products folder. +> It does not matter which Products folder you choose from, but it does matter which HandyJSON.framework you choose. + +* Select one of the four `HandyJSON.framework` which matches the platform your Application should run on. + +* Congratulations! + +# Deserialization + +## The Basics + +To support deserialization from JSON, a class/struct need to conform to 'HandyJSON' protocol. It's truly protocol, not some class inherited from NSObject. + +To conform to 'HandyJSON', a class need to implement an empty initializer. + +```swift +class BasicTypes: HandyJSON { + var int: Int = 2 + var doubleOptional: Double? + var stringImplicitlyUnwrapped: String! + + required init() {} +} + +let jsonString = "{\"doubleOptional\":1.1,\"stringImplicitlyUnwrapped\":\"hello\",\"int\":1}" +if let object = BasicTypes.deserialize(from: jsonString) { + // … +} +``` + +## Support Struct + +For struct, since the compiler provide a default empty initializer, we use it for free. + +```swift +struct BasicTypes: HandyJSON { + var int: Int = 2 + var doubleOptional: Double? + var stringImplicitlyUnwrapped: String! +} + +let jsonString = "{\"doubleOptional\":1.1,\"stringImplicitlyUnwrapped\":\"hello\",\"int\":1}" +if let object = BasicTypes.deserialize(from: jsonString) { + // … +} +``` + +But also notice that, if you have a designated initializer to override the default one in the struct, you should explicitly declare an empty one(no `required` modifier need). + +## Support Enum Property + +To be convertable, An `enum` must conform to `HandyJSONEnum` protocol. Nothing special need to do now. + +```swift +enum AnimalType: String, HandyJSONEnum { + case Cat = "cat" + case Dog = "dog" + case Bird = "bird" +} + +struct Animal: HandyJSON { + var name: String? + var type: AnimalType? +} + +let jsonString = "{\"type\":\"cat\",\"name\":\"Tom\"}" +if let animal = Animal.deserialize(from: jsonString) { + print(animal.type?.rawValue) +} +``` + +## Optional/ImplicitlyUnwrappedOptional/Collections/... + +'HandyJSON' support classes/structs composed of `optional`, `implicitlyUnwrappedOptional`, `array`, `dictionary`, `objective-c base type`, `nested type` etc. properties. + +```swift +class BasicTypes: HandyJSON { + var bool: Bool = true + var intOptional: Int? + var doubleImplicitlyUnwrapped: Double! + var anyObjectOptional: Any? + + var arrayInt: Array = [] + var arrayStringOptional: Array? + var setInt: Set? + var dictAnyObject: Dictionary = [:] + + var nsNumber = 2 + var nsString: NSString? + + required init() {} +} + +let object = BasicTypes() +object.intOptional = 1 +object.doubleImplicitlyUnwrapped = 1.1 +object.anyObjectOptional = "StringValue" +object.arrayInt = [1, 2] +object.arrayStringOptional = ["a", "b"] +object.setInt = [1, 2] +object.dictAnyObject = ["key1": 1, "key2": "stringValue"] +object.nsNumber = 2 +object.nsString = "nsStringValue" + +let jsonString = object.toJSONString()! + +if let object = BasicTypes.deserialize(from: jsonString) { + // ... +} +``` + +## Designated Path + +`HandyJSON` supports deserialization from designated path of JSON. + +```swift +class Cat: HandyJSON { + var id: Int64! + var name: String! + + required init() {} +} + +let jsonString = "{\"code\":200,\"msg\":\"success\",\"data\":{\"cat\":{\"id\":12345,\"name\":\"Kitty\"}}}" + +if let cat = Cat.deserialize(from: jsonString, designatedPath: "data.cat") { + print(cat.name) +} +``` + +## Composition Object + +Notice that all the properties of a class/struct need to deserialized should be type conformed to `HandyJSON`. + +```swift +class Component: HandyJSON { + var aInt: Int? + var aString: String? + + required init() {} +} + +class Composition: HandyJSON { + var aInt: Int? + var comp1: Component? + var comp2: Component? + + required init() {} +} + +let jsonString = "{\"num\":12345,\"comp1\":{\"aInt\":1,\"aString\":\"aaaaa\"},\"comp2\":{\"aInt\":2,\"aString\":\"bbbbb\"}}" + +if let composition = Composition.deserialize(from: jsonString) { + print(composition) +} +``` + +## Inheritance Object + +A subclass need deserialization, it's superclass need to conform to `HandyJSON`. + +```swift +class Animal: HandyJSON { + var id: Int? + var color: String? + + required init() {} +} + +class Cat: Animal { + var name: String? + + required init() {} +} + +let jsonString = "{\"id\":12345,\"color\":\"black\",\"name\":\"cat\"}" + +if let cat = Cat.deserialize(from: jsonString) { + print(cat) +} +``` + +## JSON Array + +If the first level of a JSON text is an array, we turn it to objects array. + +```swift +class Cat: HandyJSON { + var name: String? + var id: String? + + required init() {} +} + +let jsonArrayString: String? = "[{\"name\":\"Bob\",\"id\":\"1\"}, {\"name\":\"Lily\",\"id\":\"2\"}, {\"name\":\"Lucy\",\"id\":\"3\"}]" +if let cats = [Cat].deserialize(from: jsonArrayString) { + cats.forEach({ (cat) in + // ... + }) +} +``` + +## Mapping From Dictionary + +`HandyJSON` support mapping swift dictionary to model. + +```swift +var dict = [String: Any]() +dict["doubleOptional"] = 1.1 +dict["stringImplicitlyUnwrapped"] = "hello" +dict["int"] = 1 +if let object = BasicTypes.deserialize(from: dict) { + // ... +} +``` + +## Custom Mapping + +`HandyJSON` let you customize the key mapping to JSON fields, or parsing method of any property. All you need to do is implementing an optional `mapping` function, do things in it. + +We bring the transformer from [`ObjectMapper`](https://github.com/Hearst-DD/ObjectMapper). If you are familiar with it, it’s almost the same here. + +```swift +class Cat: HandyJSON { + var id: Int64! + var name: String! + var parent: (String, String)? + var friendName: String? + + required init() {} + + func mapping(mapper: HelpingMapper) { + // specify 'cat_id' field in json map to 'id' property in object + mapper <<< + self.id <-- "cat_id" + + // specify 'parent' field in json parse as following to 'parent' property in object + mapper <<< + self.parent <-- TransformOf<(String, String), String>(fromJSON: { (rawString) -> (String, String)? in + if let parentNames = rawString?.characters.split(separator: "/").map(String.init) { + return (parentNames[0], parentNames[1]) + } + return nil + }, toJSON: { (tuple) -> String? in + if let _tuple = tuple { + return "\(_tuple.0)/\(_tuple.1)" + } + return nil + }) + + // specify 'friend.name' path field in json map to 'friendName' property + mapper <<< + self.friendName <-- "friend.name" + } +} + +let jsonString = "{\"cat_id\":12345,\"name\":\"Kitty\",\"parent\":\"Tom/Lily\",\"friend\":{\"id\":54321,\"name\":\"Lily\"}}" + +if let cat = Cat.deserialize(from: jsonString) { + print(cat.id) + print(cat.parent) + print(cat.friendName) +} +``` + +## Date/Data/URL/Decimal/Color + +`HandyJSON` prepare some useful transformer for some none-basic type. + +```swift +class ExtendType: HandyJSON { + var date: Date? + var decimal: NSDecimalNumber? + var url: URL? + var data: Data? + var color: UIColor? + + func mapping(mapper: HelpingMapper) { + mapper <<< + date <-- CustomDateFormatTransform(formatString: "yyyy-MM-dd") + + mapper <<< + decimal <-- NSDecimalNumberTransform() + + mapper <<< + url <-- URLTransform(shouldEncodeURLString: false) + + mapper <<< + data <-- DataTransform() + + mapper <<< + color <-- HexColorTransform() + } + + public required init() {} +} + +let object = ExtendType() +object.date = Date() +object.decimal = NSDecimalNumber(string: "1.23423414371298437124391243") +object.url = URL(string: "https://www.aliyun.com") +object.data = Data(base64Encoded: "aGVsbG8sIHdvcmxkIQ==") +object.color = UIColor.blue + +print(object.toJSONString()!) +// it prints: +// {"date":"2017-09-11","decimal":"1.23423414371298437124391243","url":"https:\/\/www.aliyun.com","data":"aGVsbG8sIHdvcmxkIQ==","color":"0000FF"} + +let mappedObject = ExtendType.deserialize(from: object.toJSONString()!)! +print(mappedObject.date) +... +``` + +## Exclude Property + +If any non-basic property of a class/struct could not conform to `HandyJSON`/`HandyJSONEnum` or you just do not want to do the deserialization with it, you should exclude it in the mapping function. + +```swift +class NotHandyJSONType { + var dummy: String? +} + +class Cat: HandyJSON { + var id: Int64! + var name: String! + var notHandyJSONTypeProperty: NotHandyJSONType? + var basicTypeButNotWantedProperty: String? + + required init() {} + + func mapping(mapper: HelpingMapper) { + mapper >>> self.notHandyJSONTypeProperty + mapper >>> self.basicTypeButNotWantedProperty + } +} + +let jsonString = "{\"name\":\"cat\",\"id\":\"12345\"}" + +if let cat = Cat.deserialize(from: jsonString) { + print(cat) +} +``` + +## Update Existing Model + +`HandyJSON` support updating an existing model with given json string or dictionary. + +```swift +class BasicTypes: HandyJSON { + var int: Int = 2 + var doubleOptional: Double? + var stringImplicitlyUnwrapped: String! + + required init() {} +} + +var object = BasicTypes() +object.int = 1 +object.doubleOptional = 1.1 + +let jsonString = "{\"doubleOptional\":2.2}" +JSONDeserializer.update(object: &object, from: jsonString) +print(object.int) +print(object.doubleOptional) +``` + +## Supported Property Type + +* `Int`/`Bool`/`Double`/`Float`/`String`/`NSNumber`/`NSString` + +* `RawRepresentable` enum + +* `NSArray/NSDictionary` + +* `Int8/Int16/Int32/Int64`/`UInt8/UInt16/UInt23/UInt64` + +* `Optional/ImplicitUnwrappedOptional` // T is one of the above types + +* `Array` // T is one of the above types + +* `Dictionary` // T is one of the above types + +* Nested of aboves + +# Serialization + +## The Basics + +Now, a class/model which need to serialize to JSON should also conform to `HandyJSON` protocol. + +```swift +class BasicTypes: HandyJSON { + var int: Int = 2 + var doubleOptional: Double? + var stringImplicitlyUnwrapped: String! + + required init() {} +} + +let object = BasicTypes() +object.int = 1 +object.doubleOptional = 1.1 +object.stringImplicitlyUnwrapped = “hello" + +print(object.toJSON()!) // serialize to dictionary +print(object.toJSONString()!) // serialize to JSON string +print(object.toJSONString(prettyPrint: true)!) // serialize to pretty JSON string +``` + +## Mapping And Excluding + +It’s all like what we do on deserialization. A property which is excluded, it will not take part in neither deserialization nor serialization. And the mapper items define both the deserializing rules and serializing rules. Refer to the usage above. + +# FAQ + +## Q: Why the mapping function is not working in the inheritance object? + +A: For some reason, you should define an empty mapping function in the super class(the root class if more than one layer), and override it in the subclass. + +It's the same with `didFinishMapping` function. + +## Q: Why my didSet/willSet is not working? + +A: Since `HandyJSON` assign properties by writing value to memory directly, it doesn't trigger any observing function. You need to call the `didSet/willSet` logic explicitly after/before the deserialization. + +But since version `1.8.0`, `HandyJSON` handle dynamic properties by the `KVC` mechanism which will trigger the `KVO`. That means, if you do really need the `didSet/willSet`, you can define your model like follow: + +```swift +class BasicTypes: NSObject, HandyJSON { + dynamic var int: Int = 0 { + didSet { + print("oldValue: ", oldValue) + } + willSet { + print("newValue: ", newValue) + } + } + + public override required init() {} +} +``` + +In this situation, `NSObject` and `dynamic` are both needed. + +And in versions since `1.8.0`, `HandyJSON` offer a `didFinishMapping` function to allow you to fill some observing logic. + +```swift +class BasicTypes: HandyJSON { + var int: Int? + + required init() {} + + func didFinishMapping() { + print("you can fill some observing logic here") + } +} + +``` + +It may help. + +## Q: How to support Enum property? + +It your enum conform to `RawRepresentable` protocol, please look into [Support Enum Property](#support-enum-property). Or use the `EnumTransform`: + +```swift +enum EnumType: String { + case type1, type2 +} + +class BasicTypes: HandyJSON { + var type: EnumType? + + func mapping(mapper: HelpingMapper) { + mapper <<< + type <-- EnumTransform() + } + + required init() {} +} + +let object = BasicTypes() +object.type = EnumType.type2 +print(object.toJSONString()!) +let mappedObject = BasicTypes.deserialize(from: object.toJSONString()!)! +print(mappedObject.type) +``` + +Otherwise, you should implement your custom mapping function. + +```swift +enum EnumType { + case type1, type2 +} + +class BasicTypes: HandyJSON { + var type: EnumType? + + func mapping(mapper: HelpingMapper) { + mapper <<< + type <-- TransformOf(fromJSON: { (rawString) -> EnumType? in + if let _str = rawString { + switch (_str) { + case "type1": + return EnumType.type1 + case "type2": + return EnumType.type2 + default: + return nil + } + } + return nil + }, toJSON: { (enumType) -> String? in + if let _type = enumType { + switch (_type) { + case EnumType.type1: + return "type1" + case EnumType.type2: + return "type2" + } + } + return nil + }) + } + + required init() {} +} +``` + +# Credit + +* [reflection](https://github.com/Zewo/Reflection): After the first version which used the swift mirror mechanism, HandyJSON had imported the reflection library and rewrote some code for class properties inspecting. +* [ObjectMapper](https://github.com/tristanhimmelman/ObjectMapper): To make HandyJSON more compatible with the general style, the Mapper function support Transform which designed by ObjectMapper. And we import some testcases from ObjectMapper. + +# License + +HandyJSON is released under the Apache License, Version 2.0. See LICENSE for details. diff --git a/Pods/HandyJSON/Source/AnyExtensions.swift b/Pods/HandyJSON/Source/AnyExtensions.swift new file mode 100644 index 0000000..8977e8f --- /dev/null +++ b/Pods/HandyJSON/Source/AnyExtensions.swift @@ -0,0 +1,89 @@ +/* + * Copyright 1999-2101 Alibaba Group. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +// +// AnyExtension.swift +// HandyJSON +// +// Created by zhouzhuo on 08/01/2017. +// + +protocol AnyExtensions {} + +extension AnyExtensions { + + public static func isValueTypeOrSubtype(_ value: Any) -> Bool { + return value is Self + } + + public static func value(from storage: UnsafeRawPointer) -> Any { + return storage.assumingMemoryBound(to: self).pointee + } + + public static func write(_ value: Any, to storage: UnsafeMutableRawPointer) { + guard let this = value as? Self else { + return + } + storage.assumingMemoryBound(to: self).pointee = this + } + + public static func takeValue(from anyValue: Any) -> Self? { + return anyValue as? Self + } +} + +func extensions(of type: Any.Type) -> AnyExtensions.Type { + struct Extensions : AnyExtensions {} + var extensions: AnyExtensions.Type = Extensions.self + withUnsafePointer(to: &extensions) { pointer in + UnsafeMutableRawPointer(mutating: pointer).assumingMemoryBound(to: Any.Type.self).pointee = type + } + return extensions +} + +func extensions(of value: Any) -> AnyExtensions { + struct Extensions : AnyExtensions {} + var extensions: AnyExtensions = Extensions() + withUnsafePointer(to: &extensions) { pointer in + UnsafeMutableRawPointer(mutating: pointer).assumingMemoryBound(to: Any.self).pointee = value + } + return extensions +} + +/// Tests if `value` is `type` or a subclass of `type` +func value(_ value: Any, is type: Any.Type) -> Bool { + return extensions(of: type).isValueTypeOrSubtype(value) +} + +/// Tests equality of any two existential types +func == (lhs: Any.Type, rhs: Any.Type) -> Bool { + return Metadata(type: lhs) == Metadata(type: rhs) +} + +// MARK: AnyExtension + Storage +extension AnyExtensions { + + mutating func storage() -> UnsafeRawPointer { + if type(of: self) is AnyClass { + let opaquePointer = Unmanaged.passUnretained(self as AnyObject).toOpaque() + return UnsafeRawPointer(opaquePointer) + } else { + return withUnsafePointer(to: &self) { pointer in + return UnsafeRawPointer(pointer) + } + } + } +} diff --git a/Pods/HandyJSON/Source/BuiltInBasicType.swift b/Pods/HandyJSON/Source/BuiltInBasicType.swift new file mode 100644 index 0000000..8e44c18 --- /dev/null +++ b/Pods/HandyJSON/Source/BuiltInBasicType.swift @@ -0,0 +1,279 @@ +/* + * Copyright 1999-2101 Alibaba Group. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +// Created by zhouzhuo on 7/7/16. +// + +import Foundation + +protocol _BuiltInBasicType: _Transformable { + + static func _transform(from object: Any) -> Self? + func _plainValue() -> Any? +} + +// Suppport integer type + +protocol IntegerPropertyProtocol: FixedWidthInteger, _BuiltInBasicType { + init?(_ text: String, radix: Int) + init(_ number: NSNumber) +} + +extension IntegerPropertyProtocol { + + static func _transform(from object: Any) -> Self? { + switch object { + case let str as String: + return Self(str, radix: 10) + case let num as NSNumber: + return Self(num) + default: + return nil + } + } + + func _plainValue() -> Any? { + return self + } +} + +extension Int: IntegerPropertyProtocol {} +extension UInt: IntegerPropertyProtocol {} +extension Int8: IntegerPropertyProtocol {} +extension Int16: IntegerPropertyProtocol {} +extension Int32: IntegerPropertyProtocol {} +extension Int64: IntegerPropertyProtocol {} +extension UInt8: IntegerPropertyProtocol {} +extension UInt16: IntegerPropertyProtocol {} +extension UInt32: IntegerPropertyProtocol {} +extension UInt64: IntegerPropertyProtocol {} + +extension Bool: _BuiltInBasicType { + + static func _transform(from object: Any) -> Bool? { + switch object { + case let str as NSString: + let lowerCase = str.lowercased + if ["0", "false"].contains(lowerCase) { + return false + } + if ["1", "true"].contains(lowerCase) { + return true + } + return nil + case let num as NSNumber: + return num.boolValue + default: + return nil + } + } + + func _plainValue() -> Any? { + return self + } +} + +// Support float type + +protocol FloatPropertyProtocol: _BuiltInBasicType, LosslessStringConvertible { + init(_ number: NSNumber) +} + +extension FloatPropertyProtocol { + + static func _transform(from object: Any) -> Self? { + switch object { + case let str as String: + return Self(str) + case let num as NSNumber: + return Self(num) + default: + return nil + } + } + + func _plainValue() -> Any? { + return self + } +} + +extension Float: FloatPropertyProtocol {} +extension Double: FloatPropertyProtocol {} + +fileprivate let formatter: NumberFormatter = { + let formatter = NumberFormatter() + formatter.usesGroupingSeparator = false + formatter.numberStyle = .decimal + formatter.maximumFractionDigits = 16 + return formatter +}() + +extension String: _BuiltInBasicType { + + static func _transform(from object: Any) -> String? { + switch object { + case let str as String: + return str + case let num as NSNumber: + // Boolean Type Inside + if NSStringFromClass(type(of: num)) == "__NSCFBoolean" { + if num.boolValue { + return "true" + } else { + return "false" + } + } + return formatter.string(from: num) + case _ as NSNull: + return nil + default: + return "\(object)" + } + } + + func _plainValue() -> Any? { + return self + } +} + +// MARK: Optional Support + +extension Optional: _BuiltInBasicType { + + static func _transform(from object: Any) -> Optional? { + if let value = (Wrapped.self as? _Transformable.Type)?.transform(from: object) as? Wrapped { + return Optional(value) + } else if let value = object as? Wrapped { + return Optional(value) + } + return nil + } + + func _getWrappedValue() -> Any? { + return self.map( { (wrapped) -> Any in + return wrapped as Any + }) + } + + func _plainValue() -> Any? { + if let value = _getWrappedValue() { + if let transformable = value as? _Transformable { + return transformable.plainValue() + } else { + return value + } + } + return nil + } +} + +// MARK: Collection Support : Array & Set + +extension Collection { + + static func _collectionTransform(from object: Any) -> [Iterator.Element]? { + guard let arr = object as? [Any] else { + InternalLogger.logDebug("Expect object to be an array but it's not") + return nil + } + typealias Element = Iterator.Element + var result: [Element] = [Element]() + arr.forEach { (each) in + if let element = (Element.self as? _Transformable.Type)?.transform(from: each) as? Element { + result.append(element) + } else if let element = each as? Element { + result.append(element) + } + } + return result + } + + func _collectionPlainValue() -> Any? { + typealias Element = Iterator.Element + var result: [Any] = [Any]() + self.forEach { (each) in + if let transformable = each as? _Transformable, let transValue = transformable.plainValue() { + result.append(transValue) + } else { + InternalLogger.logError("value: \(each) isn't transformable type!") + } + } + return result + } +} + +extension Array: _BuiltInBasicType { + + static func _transform(from object: Any) -> [Element]? { + return self._collectionTransform(from: object) + } + + func _plainValue() -> Any? { + return self._collectionPlainValue() + } +} + +extension Set: _BuiltInBasicType { + + static func _transform(from object: Any) -> Set? { + if let arr = self._collectionTransform(from: object) { + return Set(arr) + } + return nil + } + + func _plainValue() -> Any? { + return self._collectionPlainValue() + } +} + +// MARK: Dictionary Support + +extension Dictionary: _BuiltInBasicType { + + static func _transform(from object: Any) -> [Key: Value]? { + guard let dict = object as? [String: Any] else { + InternalLogger.logDebug("Expect object to be an NSDictionary but it's not") + return nil + } + var result = [Key: Value]() + for (key, value) in dict { + if let sKey = key as? Key { + if let nValue = (Value.self as? _Transformable.Type)?.transform(from: value) as? Value { + result[sKey] = nValue + } else if let nValue = value as? Value { + result[sKey] = nValue + } + } + } + return result + } + + func _plainValue() -> Any? { + var result = [String: Any]() + for (key, value) in self { + if let key = key as? String { + if let transformable = value as? _Transformable { + if let transValue = transformable.plainValue() { + result[key] = transValue + } + } + } + } + return result + } +} + diff --git a/Pods/HandyJSON/Source/BuiltInBridgeType.swift b/Pods/HandyJSON/Source/BuiltInBridgeType.swift new file mode 100644 index 0000000..53fadd6 --- /dev/null +++ b/Pods/HandyJSON/Source/BuiltInBridgeType.swift @@ -0,0 +1,79 @@ +// +// BuiltInBridgeType.swift +// HandyJSON +// +// Created by zhouzhuo on 15/07/2017. +// Copyright © 2017 aliyun. All rights reserved. +// + +import Foundation + +protocol _BuiltInBridgeType: _Transformable { + + static func _transform(from object: Any) -> _BuiltInBridgeType? + func _plainValue() -> Any? +} + +extension NSString: _BuiltInBridgeType { + + static func _transform(from object: Any) -> _BuiltInBridgeType? { + if let str = String.transform(from: object) { + return NSString(string: str) + } + return nil + } + + func _plainValue() -> Any? { + return self + } +} + +extension NSNumber: _BuiltInBridgeType { + + static func _transform(from object: Any) -> _BuiltInBridgeType? { + switch object { + case let num as NSNumber: + return num + case let str as NSString: + let lowercase = str.lowercased + if lowercase == "true" { + return NSNumber(booleanLiteral: true) + } else if lowercase == "false" { + return NSNumber(booleanLiteral: false) + } else { + // normal number + let formatter = NumberFormatter() + formatter.numberStyle = .decimal + return formatter.number(from: str as String) + } + default: + return nil + } + } + + func _plainValue() -> Any? { + return self + } +} + +extension NSArray: _BuiltInBridgeType { + + static func _transform(from object: Any) -> _BuiltInBridgeType? { + return object as? NSArray + } + + func _plainValue() -> Any? { + return (self as? Array)?.plainValue() + } +} + +extension NSDictionary: _BuiltInBridgeType { + + static func _transform(from object: Any) -> _BuiltInBridgeType? { + return object as? NSDictionary + } + + func _plainValue() -> Any? { + return (self as? Dictionary)?.plainValue() + } +} diff --git a/Pods/HandyJSON/Source/CBridge.swift b/Pods/HandyJSON/Source/CBridge.swift new file mode 100644 index 0000000..e2ead32 --- /dev/null +++ b/Pods/HandyJSON/Source/CBridge.swift @@ -0,0 +1,37 @@ +/* + * Copyright 1999-2101 Alibaba Group. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +// +// CBridge.swift +// HandyJSON +// +// Created by chantu on 2018/7/15. +// Copyright © 2018 aliyun. All rights reserved. +// + +import Foundation + +@_silgen_name("swift_getTypeByMangledNameInContext") +public func _getTypeByMangledNameInContext( + _ name: UnsafePointer, + _ nameLength: Int, + genericContext: UnsafeRawPointer?, + genericArguments: UnsafeRawPointer?) + -> Any.Type? + + +@_silgen_name("swift_getTypeContextDescriptor") +public func _swift_getTypeContextDescriptor(_ metadata: UnsafeRawPointer?) -> UnsafeRawPointer? diff --git a/Pods/HandyJSON/Source/Configuration.swift b/Pods/HandyJSON/Source/Configuration.swift new file mode 100644 index 0000000..f7c4f2e --- /dev/null +++ b/Pods/HandyJSON/Source/Configuration.swift @@ -0,0 +1,56 @@ +/* + * Copyright 1999-2101 Alibaba Group. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +// +// Configuration.swift +// HandyJSON +// +// Created by zhouzhuo on 08/01/2017. +// + +public struct DeserializeOptions: OptionSet { + public let rawValue: Int + + public static let caseInsensitive = DeserializeOptions(rawValue: 1 << 0) + + public static let defaultOptions: DeserializeOptions = [] + + public init(rawValue: Int) { + self.rawValue = rawValue + } +} + +public enum DebugMode: Int { + case verbose = 0 + case debug = 1 + case error = 2 + case none = 3 +} + +public struct HandyJSONConfiguration { + + private static var _mode = DebugMode.error + public static var debugMode: DebugMode { + get { + return _mode + } + set { + _mode = newValue + } + } + + public static var deserializeOptions: DeserializeOptions = .defaultOptions +} diff --git a/Pods/HandyJSON/Source/ContextDescriptorType.swift b/Pods/HandyJSON/Source/ContextDescriptorType.swift new file mode 100644 index 0000000..d2c964f --- /dev/null +++ b/Pods/HandyJSON/Source/ContextDescriptorType.swift @@ -0,0 +1,170 @@ +/* + * Copyright 1999-2101 Alibaba Group. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +// +// Created by zhouzhuo on 07/01/2017. +// + +protocol ContextDescriptorType : MetadataType { + var contextDescriptorOffsetLocation: Int { get } +} + +extension ContextDescriptorType { + + var contextDescriptor: ContextDescriptorProtocol? { + let pointer = UnsafePointer(self.pointer) + let base = pointer.advanced(by: contextDescriptorOffsetLocation) + if base.pointee == 0 { + // swift class created dynamically in objc-runtime didn't have valid contextDescriptor + return nil + } + if self.kind == .class { + return ContextDescriptor<_ClassContextDescriptor>(pointer: relativePointer(base: base, offset: base.pointee - Int(bitPattern: base))) + } else { + return ContextDescriptor<_StructContextDescriptor>(pointer: relativePointer(base: base, offset: base.pointee - Int(bitPattern: base))) + } + } + + var contextDescriptorPointer: UnsafeRawPointer? { + let pointer = UnsafePointer(self.pointer) + let base = pointer.advanced(by: contextDescriptorOffsetLocation) + if base.pointee == 0 { + return nil + } + return UnsafeRawPointer(bitPattern: base.pointee) + } + +// var genericArgumentVector: UnsafeRawPointer? { +// let pointer = UnsafePointer(self.pointer) +// let base = pointer.advanced(by: 19) +// if base.pointee == 0 { +// return nil +// } +// return UnsafeRawPointer(base) +// } + + var mangledName: String { + let pointer = UnsafePointer(self.pointer) + let base = pointer.advanced(by: contextDescriptorOffsetLocation) + let mangledNameAddress = base.pointee + 2 * 4 // 2 properties in front + if let offset = contextDescriptor?.mangledName, + let cString = UnsafePointer(bitPattern: mangledNameAddress + offset) { + return String(cString: cString) + } + return "" + } + + var numberOfFields: Int { + return contextDescriptor?.numberOfFields ?? 0 + } + + var fieldOffsets: [Int]? { + guard let contextDescriptor = self.contextDescriptor else { + return nil + } + let vectorOffset = contextDescriptor.fieldOffsetVector + guard vectorOffset != 0 else { + return nil + } + if self.kind == .class { + return (0..(pointer)[vectorOffset + $0] + } + } else { + return (0..(pointer)[vectorOffset * (is64BitPlatform ? 2 : 1) + $0]) + } + } + } + + var reflectionFieldDescriptor: FieldDescriptor? { + guard let contextDescriptor = self.contextDescriptor else { + return nil + } + let pointer = UnsafePointer(self.pointer) + let base = pointer.advanced(by: contextDescriptorOffsetLocation) + let offset = contextDescriptor.reflectionFieldDescriptor + let address = base.pointee + 4 * 4 // (4 properties in front) * (sizeof Int32) + guard let fieldDescriptorPtr = UnsafePointer<_FieldDescriptor>(bitPattern: address + offset) else { + return nil + } + return FieldDescriptor(pointer: fieldDescriptorPtr) + } +} + +protocol ContextDescriptorProtocol { + var mangledName: Int { get } + var numberOfFields: Int { get } + var fieldOffsetVector: Int { get } + var reflectionFieldDescriptor: Int { get } +} + +struct ContextDescriptor: ContextDescriptorProtocol, PointerType { + + var pointer: UnsafePointer + + var mangledName: Int { + return Int(pointer.pointee.mangledNameOffset) + } + + var numberOfFields: Int { + return Int(pointer.pointee.numberOfFields) + } + + var fieldOffsetVector: Int { + return Int(pointer.pointee.fieldOffsetVector) + } + + var fieldTypesAccessor: Int { + return Int(pointer.pointee.fieldTypesAccessor) + } + + var reflectionFieldDescriptor: Int { + return Int(pointer.pointee.reflectionFieldDescriptor) + } +} + +protocol _ContextDescriptorProtocol { + var mangledNameOffset: Int32 { get } + var numberOfFields: Int32 { get } + var fieldOffsetVector: Int32 { get } + var fieldTypesAccessor: Int32 { get } + var reflectionFieldDescriptor: Int32 { get } +} + +struct _StructContextDescriptor: _ContextDescriptorProtocol { + var flags: Int32 + var parent: Int32 + var mangledNameOffset: Int32 + var fieldTypesAccessor: Int32 + var reflectionFieldDescriptor: Int32 + var numberOfFields: Int32 + var fieldOffsetVector: Int32 +} + +struct _ClassContextDescriptor: _ContextDescriptorProtocol { + var flags: Int32 + var parent: Int32 + var mangledNameOffset: Int32 + var fieldTypesAccessor: Int32 + var reflectionFieldDescriptor: Int32 + var superClsRef: Int32 + var metadataNegativeSizeInWords: Int32 + var metadataPositiveSizeInWords: Int32 + var numImmediateMembers: Int32 + var numberOfFields: Int32 + var fieldOffsetVector: Int32 +} diff --git a/Pods/HandyJSON/Source/CustomDateFormatTransform.swift b/Pods/HandyJSON/Source/CustomDateFormatTransform.swift new file mode 100644 index 0000000..7d9818c --- /dev/null +++ b/Pods/HandyJSON/Source/CustomDateFormatTransform.swift @@ -0,0 +1,40 @@ +// +// CustomDateFormatTransform.swift +// ObjectMapper +// +// Created by Dan McCracken on 3/8/15. +// +// The MIT License (MIT) +// +// Copyright (c) 2014-2016 Hearst +// +// Permission is hereby granted, free of charge, to any person obtaining a copy +// of this software and associated documentation files (the "Software"), to deal +// in the Software without restriction, including without limitation the rights +// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +// copies of the Software, and to permit persons to whom the Software is +// furnished to do so, subject to the following conditions: +// +// The above copyright notice and this permission notice shall be included in +// all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN +// THE SOFTWARE. + +import Foundation + +open class CustomDateFormatTransform: DateFormatterTransform { + + public init(formatString: String) { + let formatter = DateFormatter() + formatter.locale = Locale(identifier: "en_US_POSIX") + formatter.dateFormat = formatString + + super.init(dateFormatter: formatter) + } +} diff --git a/Pods/HandyJSON/Source/DataTransform.swift b/Pods/HandyJSON/Source/DataTransform.swift new file mode 100644 index 0000000..fd0ca67 --- /dev/null +++ b/Pods/HandyJSON/Source/DataTransform.swift @@ -0,0 +1,50 @@ +// +// DataTransform.swift +// ObjectMapper +// +// Created by Yagrushkin, Evgeny on 8/30/16. +// +// The MIT License (MIT) +// +// Copyright (c) 2014-2016 Hearst +// +// Permission is hereby granted, free of charge, to any person obtaining a copy +// of this software and associated documentation files (the "Software"), to deal +// in the Software without restriction, including without limitation the rights +// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +// copies of the Software, and to permit persons to whom the Software is +// furnished to do so, subject to the following conditions: +// +// The above copyright notice and this permission notice shall be included in +// all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN +// THE SOFTWARE. + +import Foundation + +open class DataTransform: TransformType { + public typealias Object = Data + public typealias JSON = String + + public init() {} + + open func transformFromJSON(_ value: Any?) -> Data? { + guard let string = value as? String else{ + return nil + } + return Data(base64Encoded: string) + } + + open func transformToJSON(_ value: Data?) -> String? { + guard let data = value else{ + return nil + } + return data.base64EncodedString() + } +} diff --git a/Pods/HandyJSON/Source/DateFormatterTransform.swift b/Pods/HandyJSON/Source/DateFormatterTransform.swift new file mode 100644 index 0000000..94edf9d --- /dev/null +++ b/Pods/HandyJSON/Source/DateFormatterTransform.swift @@ -0,0 +1,54 @@ +// +// DateFormatterTransform.swift +// ObjectMapper +// +// Created by Tristan Himmelman on 2015-03-09. +// +// The MIT License (MIT) +// +// Copyright (c) 2014-2016 Hearst +// +// Permission is hereby granted, free of charge, to any person obtaining a copy +// of this software and associated documentation files (the "Software"), to deal +// in the Software without restriction, including without limitation the rights +// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +// copies of the Software, and to permit persons to whom the Software is +// furnished to do so, subject to the following conditions: +// +// The above copyright notice and this permission notice shall be included in +// all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN +// THE SOFTWARE. + +import Foundation + +open class DateFormatterTransform: TransformType { + public typealias Object = Date + public typealias JSON = String + + public let dateFormatter: DateFormatter + + public init(dateFormatter: DateFormatter) { + self.dateFormatter = dateFormatter + } + + open func transformFromJSON(_ value: Any?) -> Date? { + if let dateString = value as? String { + return dateFormatter.date(from: dateString) + } + return nil + } + + open func transformToJSON(_ value: Date?) -> String? { + if let date = value { + return dateFormatter.string(from: date) + } + return nil + } +} diff --git a/Pods/HandyJSON/Source/DateTransform.swift b/Pods/HandyJSON/Source/DateTransform.swift new file mode 100644 index 0000000..af56a94 --- /dev/null +++ b/Pods/HandyJSON/Source/DateTransform.swift @@ -0,0 +1,55 @@ +// +// DateTransform.swift +// ObjectMapper +// +// Created by Tristan Himmelman on 2014-10-13. +// +// The MIT License (MIT) +// +// Copyright (c) 2014-2016 Hearst +// +// Permission is hereby granted, free of charge, to any person obtaining a copy +// of this software and associated documentation files (the "Software"), to deal +// in the Software without restriction, including without limitation the rights +// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +// copies of the Software, and to permit persons to whom the Software is +// furnished to do so, subject to the following conditions: +// +// The above copyright notice and this permission notice shall be included in +// all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN +// THE SOFTWARE. + +import Foundation + +open class DateTransform: TransformType { + public typealias Object = Date + public typealias JSON = Double + + public init() {} + + open func transformFromJSON(_ value: Any?) -> Date? { + if let timeInt = value as? Double { + return Date(timeIntervalSince1970: TimeInterval(timeInt)) + } + + if let timeStr = value as? String { + return Date(timeIntervalSince1970: TimeInterval(atof(timeStr))) + } + + return nil + } + + open func transformToJSON(_ value: Date?) -> Double? { + if let date = value { + return Double(date.timeIntervalSince1970) + } + return nil + } +} diff --git a/Pods/HandyJSON/Source/Deserializer.swift b/Pods/HandyJSON/Source/Deserializer.swift new file mode 100644 index 0000000..150c929 --- /dev/null +++ b/Pods/HandyJSON/Source/Deserializer.swift @@ -0,0 +1,181 @@ +/* + * Copyright 1999-2101 Alibaba Group. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +// Created by zhouzhuo on 7/7/16. +// + +import Foundation + +public extension HandyJSON { + + /// Finds the internal dictionary in `dict` as the `designatedPath` specified, and converts it to a Model + /// `designatedPath` is a string like `result.data.orderInfo`, which each element split by `.` represents key of each layer + static func deserialize(from dict: NSDictionary?, designatedPath: String? = nil) -> Self? { + return deserialize(from: dict as? [String: Any], designatedPath: designatedPath) + } + + /// Finds the internal dictionary in `dict` as the `designatedPath` specified, and converts it to a Model + /// `designatedPath` is a string like `result.data.orderInfo`, which each element split by `.` represents key of each layer + static func deserialize(from dict: [String: Any]?, designatedPath: String? = nil) -> Self? { + return JSONDeserializer.deserializeFrom(dict: dict, designatedPath: designatedPath) + } + + /// Finds the internal JSON field in `json` as the `designatedPath` specified, and converts it to a Model + /// `designatedPath` is a string like `result.data.orderInfo`, which each element split by `.` represents key of each layer + static func deserialize(from json: String?, designatedPath: String? = nil) -> Self? { + return JSONDeserializer.deserializeFrom(json: json, designatedPath: designatedPath) + } +} + +public extension Array where Element: HandyJSON { + + /// if the JSON field finded by `designatedPath` in `json` is representing a array, such as `[{...}, {...}, {...}]`, + /// this method converts it to a Models array + static func deserialize(from json: String?, designatedPath: String? = nil) -> [Element?]? { + return JSONDeserializer.deserializeModelArrayFrom(json: json, designatedPath: designatedPath) + } + + /// deserialize model array from NSArray + static func deserialize(from array: NSArray?) -> [Element?]? { + return JSONDeserializer.deserializeModelArrayFrom(array: array) + } + + /// deserialize model array from array + static func deserialize(from array: [Any]?) -> [Element?]? { + return JSONDeserializer.deserializeModelArrayFrom(array: array) + } +} + +public class JSONDeserializer { + + /// Finds the internal dictionary in `dict` as the `designatedPath` specified, and map it to a Model + /// `designatedPath` is a string like `result.data.orderInfo`, which each element split by `.` represents key of each layer, or nil + public static func deserializeFrom(dict: NSDictionary?, designatedPath: String? = nil) -> T? { + return deserializeFrom(dict: dict as? [String: Any], designatedPath: designatedPath) + } + + /// Finds the internal dictionary in `dict` as the `designatedPath` specified, and map it to a Model + /// `designatedPath` is a string like `result.data.orderInfo`, which each element split by `.` represents key of each layer, or nil + public static func deserializeFrom(dict: [String: Any]?, designatedPath: String? = nil) -> T? { + var targetDict = dict + if let path = designatedPath { + targetDict = getInnerObject(inside: targetDict, by: path) as? [String: Any] + } + if let _dict = targetDict { + return T._transform(dict: _dict) as? T + } + return nil + } + + /// Finds the internal JSON field in `json` as the `designatedPath` specified, and converts it to Model + /// `designatedPath` is a string like `result.data.orderInfo`, which each element split by `.` represents key of each layer, or nil + public static func deserializeFrom(json: String?, designatedPath: String? = nil) -> T? { + guard let _json = json else { + return nil + } + do { + let jsonObject = try JSONSerialization.jsonObject(with: _json.data(using: String.Encoding.utf8)!, options: .allowFragments) + if let jsonDict = jsonObject as? NSDictionary { + return self.deserializeFrom(dict: jsonDict, designatedPath: designatedPath) + } + } catch let error { + InternalLogger.logError(error) + } + return nil + } + + /// Finds the internal dictionary in `dict` as the `designatedPath` specified, and use it to reassign an exist model + /// `designatedPath` is a string like `result.data.orderInfo`, which each element split by `.` represents key of each layer, or nil + public static func update(object: inout T, from dict: [String: Any]?, designatedPath: String? = nil) { + var targetDict = dict + if let path = designatedPath { + targetDict = getInnerObject(inside: targetDict, by: path) as? [String: Any] + } + if let _dict = targetDict { + T._transform(dict: _dict, to: &object) + } + } + + /// Finds the internal JSON field in `json` as the `designatedPath` specified, and use it to reassign an exist model + /// `designatedPath` is a string like `result.data.orderInfo`, which each element split by `.` represents key of each layer, or nil + public static func update(object: inout T, from json: String?, designatedPath: String? = nil) { + guard let _json = json else { + return + } + do { + let jsonObject = try JSONSerialization.jsonObject(with: _json.data(using: String.Encoding.utf8)!, options: .allowFragments) + if let jsonDict = jsonObject as? [String: Any] { + update(object: &object, from: jsonDict, designatedPath: designatedPath) + } + } catch let error { + InternalLogger.logError(error) + } + } + + /// if the JSON field found by `designatedPath` in `json` is representing a array, such as `[{...}, {...}, {...}]`, + /// this method converts it to a Models array + public static func deserializeModelArrayFrom(json: String?, designatedPath: String? = nil) -> [T?]? { + guard let _json = json else { + return nil + } + do { + let jsonObject = try JSONSerialization.jsonObject(with: _json.data(using: String.Encoding.utf8)!, options: .allowFragments) + if let jsonArray = getInnerObject(inside: jsonObject, by: designatedPath) as? [Any] { + return jsonArray.map({ (item) -> T? in + return self.deserializeFrom(dict: item as? [String: Any]) + }) + } + } catch let error { + InternalLogger.logError(error) + } + return nil + } + + /// mapping raw array to Models array + public static func deserializeModelArrayFrom(array: NSArray?) -> [T?]? { + return deserializeModelArrayFrom(array: array as? [Any]) + } + + /// mapping raw array to Models array + public static func deserializeModelArrayFrom(array: [Any]?) -> [T?]? { + guard let _arr = array else { + return nil + } + return _arr.map({ (item) -> T? in + return self.deserializeFrom(dict: item as? NSDictionary) + }) + } +} + +fileprivate func getInnerObject(inside object: Any?, by designatedPath: String?) -> Any? { + var result: Any? = object + var abort = false + if let paths = designatedPath?.components(separatedBy: "."), paths.count > 0 { + var next = object as? [String: Any] + paths.forEach({ (seg) in + if seg.trimmingCharacters(in: CharacterSet.whitespacesAndNewlines) == "" || abort { + return + } + if let _next = next?[seg] { + result = _next + next = _next as? [String: Any] + } else { + abort = true + } + }) + } + return abort ? nil : result +} diff --git a/Pods/HandyJSON/Source/EnumTransform.swift b/Pods/HandyJSON/Source/EnumTransform.swift new file mode 100644 index 0000000..352fcbe --- /dev/null +++ b/Pods/HandyJSON/Source/EnumTransform.swift @@ -0,0 +1,50 @@ +// +// EnumTransform.swift +// ObjectMapper +// +// Created by Kaan Dedeoglu on 3/20/15. +// +// The MIT License (MIT) +// +// Copyright (c) 2014-2016 Hearst +// +// Permission is hereby granted, free of charge, to any person obtaining a copy +// of this software and associated documentation files (the "Software"), to deal +// in the Software without restriction, including without limitation the rights +// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +// copies of the Software, and to permit persons to whom the Software is +// furnished to do so, subject to the following conditions: +// +// The above copyright notice and this permission notice shall be included in +// all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN +// THE SOFTWARE. + +import Foundation + +open class EnumTransform: TransformType { + public typealias Object = T + public typealias JSON = T.RawValue + + public init() {} + + open func transformFromJSON(_ value: Any?) -> T? { + if let raw = value as? T.RawValue { + return T(rawValue: raw) + } + return nil + } + + open func transformToJSON(_ value: T?) -> T.RawValue? { + if let obj = value { + return obj.rawValue + } + return nil + } +} diff --git a/Pods/HandyJSON/Source/EnumType.swift b/Pods/HandyJSON/Source/EnumType.swift new file mode 100644 index 0000000..378546f --- /dev/null +++ b/Pods/HandyJSON/Source/EnumType.swift @@ -0,0 +1,31 @@ +// +// EnumType.swift +// HandyJSON +// +// Created by zhouzhuo on 16/07/2017. +// Copyright © 2017 aliyun. All rights reserved. +// + +import Foundation + +public protocol _RawEnumProtocol: _Transformable { + + static func _transform(from object: Any) -> Self? + func _plainValue() -> Any? +} + +extension RawRepresentable where Self: _RawEnumProtocol { + + public static func _transform(from object: Any) -> Self? { + if let transformableType = RawValue.self as? _Transformable.Type { + if let typedValue = transformableType.transform(from: object) { + return Self(rawValue: typedValue as! RawValue) + } + } + return nil + } + + public func _plainValue() -> Any? { + return self.rawValue + } +} diff --git a/Pods/HandyJSON/Source/Export.swift b/Pods/HandyJSON/Source/Export.swift new file mode 100644 index 0000000..cef2a10 --- /dev/null +++ b/Pods/HandyJSON/Source/Export.swift @@ -0,0 +1,15 @@ +// +// Export.swift +// HandyJSON +// +// Created by zhouzhuo on 16/07/2017. +// Copyright © 2017 aliyun. All rights reserved. +// + +import Foundation + +public protocol HandyJSONCustomTransformable: _ExtendCustomBasicType {} + +public protocol HandyJSON: _ExtendCustomModelType {} + +public protocol HandyJSONEnum: _RawEnumProtocol {} diff --git a/Pods/HandyJSON/Source/ExtendCustomBasicType.swift b/Pods/HandyJSON/Source/ExtendCustomBasicType.swift new file mode 100644 index 0000000..9ee9610 --- /dev/null +++ b/Pods/HandyJSON/Source/ExtendCustomBasicType.swift @@ -0,0 +1,28 @@ +/* + * Copyright 1999-2101 Alibaba Group. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +// +// ExtendCustomBasicType.swift +// HandyJSON +// +// Created by zhouzhuo on 05/09/2017. +// + +public protocol _ExtendCustomBasicType: _Transformable { + + static func _transform(from object: Any) -> Self? + func _plainValue() -> Any? +} diff --git a/Pods/HandyJSON/Source/ExtendCustomModelType.swift b/Pods/HandyJSON/Source/ExtendCustomModelType.swift new file mode 100644 index 0000000..fbe7289 --- /dev/null +++ b/Pods/HandyJSON/Source/ExtendCustomModelType.swift @@ -0,0 +1,277 @@ +// +// ExtendCustomType.swift +// HandyJSON +// +// Created by zhouzhuo on 16/07/2017. +// Copyright © 2017 aliyun. All rights reserved. +// + +import Foundation + +public protocol _ExtendCustomModelType: _Transformable { + init() + mutating func willStartMapping() + mutating func mapping(mapper: HelpingMapper) + mutating func didFinishMapping() +} + +extension _ExtendCustomModelType { + + public mutating func willStartMapping() {} + public mutating func mapping(mapper: HelpingMapper) {} + public mutating func didFinishMapping() {} +} + +fileprivate func convertKeyIfNeeded(dict: [String: Any]) -> [String: Any] { + if HandyJSONConfiguration.deserializeOptions.contains(.caseInsensitive) { + var newDict = [String: Any]() + dict.forEach({ (kvPair) in + let (key, value) = kvPair + newDict[key.lowercased()] = value + }) + return newDict + } + return dict +} + +fileprivate func getRawValueFrom(dict: [String: Any], property: PropertyInfo, mapper: HelpingMapper) -> Any? { + let address = Int(bitPattern: property.address) + if let mappingHandler = mapper.getMappingHandler(key: address) { + if let mappingPaths = mappingHandler.mappingPaths, mappingPaths.count > 0 { + for mappingPath in mappingPaths { + if let _value = dict.findValueBy(path: mappingPath) { + return _value + } + } + return nil + } + } + if HandyJSONConfiguration.deserializeOptions.contains(.caseInsensitive) { + return dict[property.key.lowercased()] + } + return dict[property.key] +} + +fileprivate func convertValue(rawValue: Any, property: PropertyInfo, mapper: HelpingMapper) -> Any? { + if rawValue is NSNull { return nil } + if let mappingHandler = mapper.getMappingHandler(key: Int(bitPattern: property.address)), let transformer = mappingHandler.assignmentClosure { + return transformer(rawValue) + } + if let transformableType = property.type as? _Transformable.Type { + return transformableType.transform(from: rawValue) + } else { + return extensions(of: property.type).takeValue(from: rawValue) + } +} + +fileprivate func assignProperty(convertedValue: Any, instance: _ExtendCustomModelType, property: PropertyInfo) { + if property.bridged { + (instance as! NSObject).setValue(convertedValue, forKey: property.key) + } else { + extensions(of: property.type).write(convertedValue, to: property.address) + } +} + +fileprivate func readAllChildrenFrom(mirror: Mirror) -> [(String, Any)] { + var children = [(label: String?, value: Any)]() + let mirrorChildrenCollection = AnyRandomAccessCollection(mirror.children)! + children += mirrorChildrenCollection + + var currentMirror = mirror + while let superclassChildren = currentMirror.superclassMirror?.children { + let randomCollection = AnyRandomAccessCollection(superclassChildren)! + children += randomCollection + currentMirror = currentMirror.superclassMirror! + } + var result = [(String, Any)]() + children.forEach { (child) in + if let _label = child.label { + result.append((_label, child.value)) + } + } + return result +} + +fileprivate func merge(children: [(String, Any)], propertyInfos: [PropertyInfo]) -> [String: (Any, PropertyInfo?)] { + var infoDict = [String: PropertyInfo]() + propertyInfos.forEach { (info) in + infoDict[info.key] = info + } + + var result = [String: (Any, PropertyInfo?)]() + children.forEach { (child) in + result[child.0] = (child.1, infoDict[child.0]) + } + return result +} + +// this's a workaround before https://bugs.swift.org/browse/SR-5223 fixed +extension NSObject { + static func createInstance() -> NSObject { + return self.init() + } +} + +extension _ExtendCustomModelType { + + static func _transform(from object: Any) -> Self? { + if let dict = object as? [String: Any] { + // nested object, transform recursively + return self._transform(dict: dict) as? Self + } + return nil + } + + static func _transform(dict: [String: Any]) -> _ExtendCustomModelType? { + + var instance: Self + if let _nsType = Self.self as? NSObject.Type { + instance = _nsType.createInstance() as! Self + } else { + instance = Self.init() + } + instance.willStartMapping() + _transform(dict: dict, to: &instance) + instance.didFinishMapping() + return instance + } + + static func _transform(dict: [String: Any], to instance: inout Self) { + guard let properties = getProperties(forType: Self.self) else { + InternalLogger.logDebug("Failed when try to get properties from type: \(type(of: Self.self))") + return + } + + // do user-specified mapping first + let mapper = HelpingMapper() + instance.mapping(mapper: mapper) + + // get head addr + let rawPointer = instance.headPointer() + InternalLogger.logVerbose("instance start at: ", Int(bitPattern: rawPointer)) + + // process dictionary + let _dict = convertKeyIfNeeded(dict: dict) + + let instanceIsNsObject = instance.isNSObjectType() + let bridgedPropertyList = instance.getBridgedPropertyList() + + for property in properties { + let isBridgedProperty = instanceIsNsObject && bridgedPropertyList.contains(property.key) + + let propAddr = rawPointer.advanced(by: property.offset) + InternalLogger.logVerbose(property.key, "address at: ", Int(bitPattern: propAddr)) + if mapper.propertyExcluded(key: Int(bitPattern: propAddr)) { + InternalLogger.logDebug("Exclude property: \(property.key)") + continue + } + + let propertyDetail = PropertyInfo(key: property.key, type: property.type, address: propAddr, bridged: isBridgedProperty) + InternalLogger.logVerbose("field: ", property.key, " offset: ", property.offset, " isBridgeProperty: ", isBridgedProperty) + + if let rawValue = getRawValueFrom(dict: _dict, property: propertyDetail, mapper: mapper) { + if let convertedValue = convertValue(rawValue: rawValue, property: propertyDetail, mapper: mapper) { + assignProperty(convertedValue: convertedValue, instance: instance, property: propertyDetail) + continue + } + } + InternalLogger.logDebug("Property: \(property.key) hasn't been written in") + } + } +} + +extension _ExtendCustomModelType { + + func _plainValue() -> Any? { + return Self._serializeAny(object: self) + } + + static func _serializeAny(object: _Transformable) -> Any? { + + let mirror = Mirror(reflecting: object) + + guard let displayStyle = mirror.displayStyle else { + return object.plainValue() + } + + // after filtered by protocols above, now we expect the type is pure struct/class + switch displayStyle { + case .class, .struct: + let mapper = HelpingMapper() + // do user-specified mapping first + if !(object is _ExtendCustomModelType) { + InternalLogger.logDebug("This model of type: \(type(of: object)) is not mappable but is class/struct type") + return object + } + + let children = readAllChildrenFrom(mirror: mirror) + + guard let properties = getProperties(forType: type(of: object)) else { + InternalLogger.logError("Can not get properties info for type: \(type(of: object))") + return nil + } + + var mutableObject = object as! _ExtendCustomModelType + let instanceIsNsObject = mutableObject.isNSObjectType() + let head = mutableObject.headPointer() + let bridgedProperty = mutableObject.getBridgedPropertyList() + let propertyInfos = properties.map({ (desc) -> PropertyInfo in + return PropertyInfo(key: desc.key, type: desc.type, address: head.advanced(by: desc.offset), + bridged: instanceIsNsObject && bridgedProperty.contains(desc.key)) + }) + + mutableObject.mapping(mapper: mapper) + + let requiredInfo = merge(children: children, propertyInfos: propertyInfos) + + return _serializeModelObject(instance: mutableObject, properties: requiredInfo, mapper: mapper) as Any + default: + return object.plainValue() + } + } + + static func _serializeModelObject(instance: _ExtendCustomModelType, properties: [String: (Any, PropertyInfo?)], mapper: HelpingMapper) -> [String: Any] { + + var dict = [String: Any]() + for (key, property) in properties { + var realKey = key + var realValue = property.0 + + if let info = property.1 { + if info.bridged, let _value = (instance as! NSObject).value(forKey: key) { + realValue = _value + } + + if mapper.propertyExcluded(key: Int(bitPattern: info.address)) { + continue + } + + if let mappingHandler = mapper.getMappingHandler(key: Int(bitPattern: info.address)) { + // if specific key is set, replace the label + if let mappingPaths = mappingHandler.mappingPaths, mappingPaths.count > 0 { + // take the first path, last segment if more than one + realKey = mappingPaths[0].segments.last! + } + + if let transformer = mappingHandler.takeValueClosure { + if let _transformedValue = transformer(realValue) { + dict[realKey] = _transformedValue + } + continue + } + } + } + + if let typedValue = realValue as? _Transformable { + if let result = self._serializeAny(object: typedValue) { + dict[realKey] = result + continue + } + } + + InternalLogger.logDebug("The value for key: \(key) is not transformable type") + } + return dict + } +} + diff --git a/Pods/HandyJSON/Source/FieldDescriptor.swift b/Pods/HandyJSON/Source/FieldDescriptor.swift new file mode 100644 index 0000000..589be59 --- /dev/null +++ b/Pods/HandyJSON/Source/FieldDescriptor.swift @@ -0,0 +1,97 @@ +// +// FieldDescriptor.swift +// HandyJSON +// +// Created by chantu on 2019/1/31. +// Copyright © 2019 aliyun. All rights reserved. +// + +import Foundation + +enum FieldDescriptorKind : UInt16 { + // Swift nominal types. + case Struct = 0 + case Class + case Enum + + // Fixed-size multi-payload enums have a special descriptor format that + // encodes spare bits. + // + // FIXME: Actually implement this. For now, a descriptor with this kind + // just means we also have a builtin descriptor from which we get the + // size and alignment. + case MultiPayloadEnum + + // A Swift opaque protocol. There are no fields, just a record for the + // type itself. + case `Protocol` + + // A Swift class-bound protocol. + case ClassProtocol + + // An Objective-C protocol, which may be imported or defined in Swift. + case ObjCProtocol + + // An Objective-C class, which may be imported or defined in Swift. + // In the former case, field type metadata is not emitted, and + // must be obtained from the Objective-C runtime. + case ObjCClass +} + +struct FieldDescriptor: PointerType { + + var pointer: UnsafePointer<_FieldDescriptor> + + var fieldRecordSize: Int { + return Int(pointer.pointee.fieldRecordSize) + } + + var numFields: Int { + return Int(pointer.pointee.numFields) + } + + var fieldRecords: [FieldRecord] { + return (0.. FieldRecord in + return FieldRecord(pointer: UnsafePointer<_FieldRecord>(pointer + 1) + i) + }) + } +} + +struct _FieldDescriptor { + var mangledTypeNameOffset: Int32 + var superClassOffset: Int32 + var fieldDescriptorKind: FieldDescriptorKind + var fieldRecordSize: Int16 + var numFields: Int32 +} + +struct FieldRecord: PointerType { + + var pointer: UnsafePointer<_FieldRecord> + + var fieldRecordFlags: Int { + return Int(pointer.pointee.fieldRecordFlags) + } + + var mangledTypeName: UnsafePointer? { + let address = Int(bitPattern: pointer) + 1 * 4 + let offset = Int(pointer.pointee.mangledTypeNameOffset) + let cString = UnsafePointer(bitPattern: address + offset) + return cString + } + + var fieldName: String { + let address = Int(bitPattern: pointer) + 2 * 4 + let offset = Int(pointer.pointee.fieldNameOffset) + if let cString = UnsafePointer(bitPattern: address + offset) { + return String(cString: cString) + } + return "" + } +} + +struct _FieldRecord { + var fieldRecordFlags: Int32 + var mangledTypeNameOffset: Int32 + var fieldNameOffset: Int32 +} diff --git a/Pods/HandyJSON/Source/HandyJSON.h b/Pods/HandyJSON/Source/HandyJSON.h new file mode 100644 index 0000000..596db89 --- /dev/null +++ b/Pods/HandyJSON/Source/HandyJSON.h @@ -0,0 +1,30 @@ +/* + * Copyright 1999-2101 Alibaba Group. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +// Created by zhouzhuo on 7/11/16. +// + +@import Foundation; + +//! Project version number for HandyJSON. +FOUNDATION_EXPORT double HandyJSONVersionNumber; + +//! Project version string for HandyJSON. +FOUNDATION_EXPORT const unsigned char HandyJSONVersionString[]; + +// In this header, you should import all the public headers of your framework using statements like #import + + diff --git a/Pods/HandyJSON/Source/HelpingMapper.swift b/Pods/HandyJSON/Source/HelpingMapper.swift new file mode 100644 index 0000000..209f1e5 --- /dev/null +++ b/Pods/HandyJSON/Source/HelpingMapper.swift @@ -0,0 +1,219 @@ +/* + * Copyright 1999-2101 Alibaba Group. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +// Created by zhouzhuo on 9/20/16. +// + +import Foundation + +public typealias CustomMappingKeyValueTuple = (Int, MappingPropertyHandler) + +struct MappingPath { + var segments: [String] + + static func buildFrom(rawPath: String) -> MappingPath { + let regex = try! NSRegularExpression(pattern: "(? Any? { + var currentDict: [String: Any]? = self + var lastValue: Any? + path.segments.forEach { (segment) in + lastValue = currentDict?[segment] + currentDict = currentDict?[segment] as? [String: Any] + } + return lastValue + } +} + +public class MappingPropertyHandler { + var mappingPaths: [MappingPath]? + var assignmentClosure: ((Any?) -> (Any?))? + var takeValueClosure: ((Any?) -> (Any?))? + + public init(rawPaths: [String]?, assignmentClosure: ((Any?) -> (Any?))?, takeValueClosure: ((Any?) -> (Any?))?) { + let mappingPaths = rawPaths?.map({ (rawPath) -> MappingPath in + if HandyJSONConfiguration.deserializeOptions.contains(.caseInsensitive) { + return MappingPath.buildFrom(rawPath: rawPath.lowercased()) + } + return MappingPath.buildFrom(rawPath: rawPath) + }).filter({ (mappingPath) -> Bool in + return mappingPath.segments.count > 0 + }) + if let count = mappingPaths?.count, count > 0 { + self.mappingPaths = mappingPaths + } + self.assignmentClosure = assignmentClosure + self.takeValueClosure = takeValueClosure + } +} + +public class HelpingMapper { + + private var mappingHandlers = [Int: MappingPropertyHandler]() + private var excludeProperties = [Int]() + + internal func getMappingHandler(key: Int) -> MappingPropertyHandler? { + return self.mappingHandlers[key] + } + + internal func propertyExcluded(key: Int) -> Bool { + return self.excludeProperties.contains(key) + } + + public func specify(property: inout T, name: String) { + self.specify(property: &property, name: name, converter: nil) + } + + public func specify(property: inout T, converter: @escaping (String) -> T) { + self.specify(property: &property, name: nil, converter: converter) + } + + public func specify(property: inout T, name: String?, converter: ((String) -> T)?) { + let pointer = withUnsafePointer(to: &property, { return $0 }) + let key = Int(bitPattern: pointer) + let names = (name == nil ? nil : [name!]) + + if let _converter = converter { + let assignmentClosure = { (jsonValue: Any?) -> Any? in + if let _value = jsonValue{ + if let object = _value as? NSObject { + if let str = String.transform(from: object){ + return _converter(str) + } + } + } + return nil + } + self.mappingHandlers[key] = MappingPropertyHandler(rawPaths: names, assignmentClosure: assignmentClosure, takeValueClosure: nil) + } else { + self.mappingHandlers[key] = MappingPropertyHandler(rawPaths: names, assignmentClosure: nil, takeValueClosure: nil) + } + } + + public func exclude(property: inout T) { + self._exclude(property: &property) + } + + fileprivate func addCustomMapping(key: Int, mappingInfo: MappingPropertyHandler) { + self.mappingHandlers[key] = mappingInfo + } + + fileprivate func _exclude(property: inout T) { + let pointer = withUnsafePointer(to: &property, { return $0 }) + self.excludeProperties.append(Int(bitPattern: pointer)) + } +} + +infix operator <-- : LogicalConjunctionPrecedence + +public func <-- (property: inout T, name: String) -> CustomMappingKeyValueTuple { + return property <-- [name] +} + +public func <-- (property: inout T, names: [String]) -> CustomMappingKeyValueTuple { + let pointer = withUnsafePointer(to: &property, { return $0 }) + let key = Int(bitPattern: pointer) + return (key, MappingPropertyHandler(rawPaths: names, assignmentClosure: nil, takeValueClosure: nil)) +} + +// MARK: non-optional properties +public func <-- (property: inout Transform.Object, transformer: Transform) -> CustomMappingKeyValueTuple { + return property <-- (nil, transformer) +} + +public func <-- (property: inout Transform.Object, transformer: (String?, Transform?)) -> CustomMappingKeyValueTuple { + let names = (transformer.0 == nil ? [] : [transformer.0!]) + return property <-- (names, transformer.1) +} + +public func <-- (property: inout Transform.Object, transformer: ([String], Transform?)) -> CustomMappingKeyValueTuple { + let pointer = withUnsafePointer(to: &property, { return $0 }) + let key = Int(bitPattern: pointer) + let assignmentClosure = { (jsonValue: Any?) -> Transform.Object? in + return transformer.1?.transformFromJSON(jsonValue) + } + let takeValueClosure = { (objectValue: Any?) -> Any? in + if let _value = objectValue as? Transform.Object { + return transformer.1?.transformToJSON(_value) as Any + } + return nil + } + return (key, MappingPropertyHandler(rawPaths: transformer.0, assignmentClosure: assignmentClosure, takeValueClosure: takeValueClosure)) +} + +// MARK: optional properties +public func <-- (property: inout Transform.Object?, transformer: Transform) -> CustomMappingKeyValueTuple { + return property <-- (nil, transformer) +} + +public func <-- (property: inout Transform.Object?, transformer: (String?, Transform?)) -> CustomMappingKeyValueTuple { + let names = (transformer.0 == nil ? [] : [transformer.0!]) + return property <-- (names, transformer.1) +} + +public func <-- (property: inout Transform.Object?, transformer: ([String], Transform?)) -> CustomMappingKeyValueTuple { + let pointer = withUnsafePointer(to: &property, { return $0 }) + let key = Int(bitPattern: pointer) + let assignmentClosure = { (jsonValue: Any?) -> Any? in + return transformer.1?.transformFromJSON(jsonValue) + } + let takeValueClosure = { (objectValue: Any?) -> Any? in + if let _value = objectValue as? Transform.Object { + return transformer.1?.transformToJSON(_value) as Any + } + return nil + } + return (key, MappingPropertyHandler(rawPaths: transformer.0, assignmentClosure: assignmentClosure, takeValueClosure: takeValueClosure)) +} + +infix operator <<< : AssignmentPrecedence + +public func <<< (mapper: HelpingMapper, mapping: CustomMappingKeyValueTuple) { + mapper.addCustomMapping(key: mapping.0, mappingInfo: mapping.1) +} + +public func <<< (mapper: HelpingMapper, mappings: [CustomMappingKeyValueTuple]) { + mappings.forEach { (mapping) in + mapper.addCustomMapping(key: mapping.0, mappingInfo: mapping.1) + } +} + +infix operator >>> : AssignmentPrecedence + +public func >>> (mapper: HelpingMapper, property: inout T) { + mapper._exclude(property: &property) +} diff --git a/Pods/HandyJSON/Source/HexColorTransform.swift b/Pods/HandyJSON/Source/HexColorTransform.swift new file mode 100644 index 0000000..11fbc1d --- /dev/null +++ b/Pods/HandyJSON/Source/HexColorTransform.swift @@ -0,0 +1,115 @@ +// +// HexColorTransform.swift +// ObjectMapper +// +// Created by Vitaliy Kuzmenko on 10/10/16. +// Copyright © 2016 hearst. All rights reserved. +// + +#if os(iOS) || os(tvOS) || os(watchOS) +import UIKit +#else +import Cocoa +#endif + +open class HexColorTransform: TransformType { + + #if os(iOS) || os(tvOS) || os(watchOS) + public typealias Object = UIColor + #else + public typealias Object = NSColor + #endif + + public typealias JSON = String + + var prefix: Bool = false + + var alpha: Bool = false + + public init(prefixToJSON: Bool = false, alphaToJSON: Bool = false) { + alpha = alphaToJSON + prefix = prefixToJSON + } + + open func transformFromJSON(_ value: Any?) -> Object? { + if let rgba = value as? String { + if rgba.hasPrefix("#") { + let index = rgba.index(rgba.startIndex, offsetBy: 1) + let hex = String(rgba[index...]) + return getColor(hex: hex) + } else { + return getColor(hex: rgba) + } + } + return nil + } + + open func transformToJSON(_ value: Object?) -> JSON? { + if let value = value { + return hexString(color: value) + } + return nil + } + + fileprivate func hexString(color: Object) -> String { + let comps = color.cgColor.components! + let r = Int(comps[0] * 255) + let g = Int(comps[1] * 255) + let b = Int(comps[2] * 255) + let a = Int(comps[3] * 255) + var hexString: String = "" + if prefix { + hexString = "#" + } + hexString += String(format: "%02X%02X%02X", r, g, b) + + if alpha { + hexString += String(format: "%02X", a) + } + return hexString + } + + fileprivate func getColor(hex: String) -> Object? { + var red: CGFloat = 0.0 + var green: CGFloat = 0.0 + var blue: CGFloat = 0.0 + var alpha: CGFloat = 1.0 + + let scanner = Scanner(string: hex) + var hexValue: CUnsignedLongLong = 0 + if scanner.scanHexInt64(&hexValue) { + switch (hex.count) { + case 3: + red = CGFloat((hexValue & 0xF00) >> 8) / 15.0 + green = CGFloat((hexValue & 0x0F0) >> 4) / 15.0 + blue = CGFloat(hexValue & 0x00F) / 15.0 + case 4: + red = CGFloat((hexValue & 0xF000) >> 12) / 15.0 + green = CGFloat((hexValue & 0x0F00) >> 8) / 15.0 + blue = CGFloat((hexValue & 0x00F0) >> 4) / 15.0 + alpha = CGFloat(hexValue & 0x000F) / 15.0 + case 6: + red = CGFloat((hexValue & 0xFF0000) >> 16) / 255.0 + green = CGFloat((hexValue & 0x00FF00) >> 8) / 255.0 + blue = CGFloat(hexValue & 0x0000FF) / 255.0 + case 8: + red = CGFloat((hexValue & 0xFF000000) >> 24) / 255.0 + green = CGFloat((hexValue & 0x00FF0000) >> 16) / 255.0 + blue = CGFloat((hexValue & 0x0000FF00) >> 8) / 255.0 + alpha = CGFloat(hexValue & 0x000000FF) / 255.0 + default: + // Invalid RGB string, number of characters after '#' should be either 3, 4, 6 or 8 + return nil + } + } else { + // "Scan hex error + return nil + } + #if os(iOS) || os(tvOS) || os(watchOS) + return UIColor(red: red, green: green, blue: blue, alpha: alpha) + #else + return NSColor(calibratedRed: red, green: green, blue: blue, alpha: alpha) + #endif + } +} + diff --git a/Pods/HandyJSON/Source/ISO8601DateTransform.swift b/Pods/HandyJSON/Source/ISO8601DateTransform.swift new file mode 100644 index 0000000..c80ad8b --- /dev/null +++ b/Pods/HandyJSON/Source/ISO8601DateTransform.swift @@ -0,0 +1,41 @@ +// +// ISO8601DateTransform.swift +// ObjectMapper +// +// Created by Jean-Pierre Mouilleseaux on 21 Nov 2014. +// +// The MIT License (MIT) +// +// Copyright (c) 2014-2016 Hearst +// +// Permission is hereby granted, free of charge, to any person obtaining a copy +// of this software and associated documentation files (the "Software"), to deal +// in the Software without restriction, including without limitation the rights +// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +// copies of the Software, and to permit persons to whom the Software is +// furnished to do so, subject to the following conditions: +// +// The above copyright notice and this permission notice shall be included in +// all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN +// THE SOFTWARE. + +import Foundation + +open class ISO8601DateTransform: DateFormatterTransform { + + public init() { + let formatter = DateFormatter() + formatter.locale = Locale(identifier: "en_US_POSIX") + formatter.dateFormat = "yyyy-MM-dd'T'HH:mm:ssZZZZZ" + + super.init(dateFormatter: formatter) + } + +} diff --git a/Pods/HandyJSON/Source/Logger.swift b/Pods/HandyJSON/Source/Logger.swift new file mode 100644 index 0000000..9a69281 --- /dev/null +++ b/Pods/HandyJSON/Source/Logger.swift @@ -0,0 +1,43 @@ +/* + * Copyright 1999-2101 Alibaba Group. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +// +// Logger.swift +// HandyJSON +// +// Created by zhouzhuo on 08/01/2017. +// + +struct InternalLogger { + + static func logError(_ items: Any..., separator: String = " ", terminator: String = "\n") { + if HandyJSONConfiguration.debugMode.rawValue <= DebugMode.error.rawValue { + print(items, separator: separator, terminator: terminator) + } + } + + static func logDebug(_ items: Any..., separator: String = " ", terminator: String = "\n") { + if HandyJSONConfiguration.debugMode.rawValue <= DebugMode.debug.rawValue { + print(items, separator: separator, terminator: terminator) + } + } + + static func logVerbose(_ items: Any..., separator: String = " ", terminator: String = "\n") { + if HandyJSONConfiguration.debugMode.rawValue <= DebugMode.verbose.rawValue { + print(items, separator: separator, terminator: terminator) + } + } +} diff --git a/Pods/HandyJSON/Source/MangledName.swift b/Pods/HandyJSON/Source/MangledName.swift new file mode 100644 index 0000000..5b95504 --- /dev/null +++ b/Pods/HandyJSON/Source/MangledName.swift @@ -0,0 +1,15 @@ +// +// MangledName.swift +// HandyJSON +// +// Created by chantu on 2019/2/2. +// Copyright © 2019 aliyun. All rights reserved. +// + +import Foundation + + // mangled name might contain 0 but it is not the end, do not just use strlen +func getMangledTypeNameSize(_ mangledName: UnsafePointer) -> Int { + // TODO: should find the actually size + return 256 +} diff --git a/Pods/HandyJSON/Source/Measuable.swift b/Pods/HandyJSON/Source/Measuable.swift new file mode 100644 index 0000000..9d9c6e5 --- /dev/null +++ b/Pods/HandyJSON/Source/Measuable.swift @@ -0,0 +1,95 @@ +// +// Measuable.swift +// HandyJSON +// +// Created by zhouzhuo on 15/07/2017. +// Copyright © 2017 aliyun. All rights reserved. +// + +import Foundation + +typealias Byte = Int8 + +public protocol _Measurable {} + +extension _Measurable { + + // locate the head of a struct type object in memory + mutating func headPointerOfStruct() -> UnsafeMutablePointer { + + return withUnsafeMutablePointer(to: &self) { + return UnsafeMutableRawPointer($0).bindMemory(to: Byte.self, capacity: MemoryLayout.stride) + } + } + + // locating the head of a class type object in memory + mutating func headPointerOfClass() -> UnsafeMutablePointer { + + let opaquePointer = Unmanaged.passUnretained(self as AnyObject).toOpaque() + let mutableTypedPointer = opaquePointer.bindMemory(to: Byte.self, capacity: MemoryLayout.stride) + return UnsafeMutablePointer(mutableTypedPointer) + } + + // locating the head of an object + mutating func headPointer() -> UnsafeMutablePointer { + if Self.self is AnyClass { + return self.headPointerOfClass() + } else { + return self.headPointerOfStruct() + } + } + + func isNSObjectType() -> Bool { + return (type(of: self) as? NSObject.Type) != nil + } + + func getBridgedPropertyList() -> Set { + if let anyClass = type(of: self) as? AnyClass { + return _getBridgedPropertyList(anyClass: anyClass) + } + return [] + } + + func _getBridgedPropertyList(anyClass: AnyClass) -> Set { + if !(anyClass is HandyJSON.Type) { + return [] + } + var propertyList = Set() + if let superClass = class_getSuperclass(anyClass), superClass != NSObject.self { + propertyList = propertyList.union(_getBridgedPropertyList(anyClass: superClass)) + } + let count = UnsafeMutablePointer.allocate(capacity: 1) + if let props = class_copyPropertyList(anyClass, count) { + for i in 0 ..< count.pointee { + let name = String(cString: property_getName(props.advanced(by: Int(i)).pointee)) + propertyList.insert(name) + } + free(props) + } + #if swift(>=4.1) + count.deallocate() + #else + count.deallocate(capacity: 1) + #endif + return propertyList + } + + // memory size occupy by self object + static func size() -> Int { + return MemoryLayout.size + } + + // align + static func align() -> Int { + return MemoryLayout.alignment + } + + // Returns the offset to the next integer that is greater than + // or equal to Value and is a multiple of Align. Align must be + // non-zero. + static func offsetToAlignment(value: Int, align: Int) -> Int { + let m = value % align + return m == 0 ? 0 : (align - m) + } +} + diff --git a/Pods/HandyJSON/Source/Metadata.swift b/Pods/HandyJSON/Source/Metadata.swift new file mode 100755 index 0000000..1d846a2 --- /dev/null +++ b/Pods/HandyJSON/Source/Metadata.swift @@ -0,0 +1,332 @@ +/* + * Copyright 1999-2101 Alibaba Group. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +// +// Created by zhouzhuo on 07/01/2017. +// + +struct _class_rw_t { + var flags: Int32 + var version: Int32 + var ro: UInt + // other fields we don't care + + // reference: include/swift/Remote/MetadataReader.h/readObjcRODataPtr + func class_ro_t() -> UnsafePointer<_class_ro_t>? { + var addr: UInt = self.ro + if (self.ro & UInt(1)) != 0 { + if let ptr = UnsafePointer(bitPattern: self.ro ^ 1) { + addr = ptr.pointee + } + } + return UnsafePointer<_class_ro_t>(bitPattern: addr) + } +} + +struct _class_ro_t { + var flags: Int32 + var instanceStart: Int32 + var instanceSize: Int32 + // other fields we don't care +} + +// MARK: MetadataType +protocol MetadataType : PointerType { + static var kind: Metadata.Kind? { get } +} + +extension MetadataType { + + var kind: Metadata.Kind { + return Metadata.Kind(flag: UnsafePointer(pointer).pointee) + } + + init?(anyType: Any.Type) { + self.init(pointer: unsafeBitCast(anyType, to: UnsafePointer.self)) + if let kind = type(of: self).kind, kind != self.kind { + return nil + } + } +} + +// MARK: Metadata +struct Metadata : MetadataType { + var pointer: UnsafePointer + + init(type: Any.Type) { + self.init(pointer: unsafeBitCast(type, to: UnsafePointer.self)) + } +} + +struct _Metadata {} + +var is64BitPlatform: Bool { + return MemoryLayout.size == MemoryLayout.size +} + +// MARK: Metadata + Kind +// include/swift/ABI/MetadataKind.def +let MetadataKindIsNonHeap = 0x200 +let MetadataKindIsRuntimePrivate = 0x100 +let MetadataKindIsNonType = 0x400 +extension Metadata { + static let kind: Kind? = nil + + enum Kind { + case `struct` + case `enum` + case optional + case opaque + case foreignClass + case tuple + case function + case existential + case metatype + case objCClassWrapper + case existentialMetatype + case heapLocalVariable + case heapGenericLocalVariable + case errorObject + case `class` // The kind only valid for non-class metadata + init(flag: Int) { + switch flag { + case (0 | MetadataKindIsNonHeap): self = .struct + case (1 | MetadataKindIsNonHeap): self = .enum + case (2 | MetadataKindIsNonHeap): self = .optional + case (3 | MetadataKindIsNonHeap): self = .foreignClass + case (0 | MetadataKindIsRuntimePrivate | MetadataKindIsNonHeap): self = .opaque + case (1 | MetadataKindIsRuntimePrivate | MetadataKindIsNonHeap): self = .tuple + case (2 | MetadataKindIsRuntimePrivate | MetadataKindIsNonHeap): self = .function + case (3 | MetadataKindIsRuntimePrivate | MetadataKindIsNonHeap): self = .existential + case (4 | MetadataKindIsRuntimePrivate | MetadataKindIsNonHeap): self = .metatype + case (5 | MetadataKindIsRuntimePrivate | MetadataKindIsNonHeap): self = .objCClassWrapper + case (6 | MetadataKindIsRuntimePrivate | MetadataKindIsNonHeap): self = .existentialMetatype + case (0 | MetadataKindIsNonType): self = .heapLocalVariable + case (0 | MetadataKindIsNonType | MetadataKindIsRuntimePrivate): self = .heapGenericLocalVariable + case (1 | MetadataKindIsNonType | MetadataKindIsRuntimePrivate): self = .errorObject + default: self = .class + } + } + } +} + +// MARK: Metadata + Class +extension Metadata { + struct Class : ContextDescriptorType { + + static let kind: Kind? = .class + var pointer: UnsafePointer<_Metadata._Class> + + var isSwiftClass: Bool { + get { + // see include/swift/Runtime/Config.h macro SWIFT_CLASS_IS_SWIFT_MASK + // it can be 1 or 2 depending on environment + let lowbit = self.pointer.pointee.rodataPointer & 3 + return lowbit != 0 + } + } + + var contextDescriptorOffsetLocation: Int { + return is64BitPlatform ? 8 : 11 + } + + var superclass: Class? { + guard let superclass = pointer.pointee.superclass else { + return nil + } + + // If the superclass doesn't conform to handyjson/handyjsonenum protocol, + // we should ignore the properties inside + if !(superclass is HandyJSON.Type) && !(superclass is HandyJSONEnum.Type) { + return nil + } + + // ignore objc-runtime layer + guard let metaclass = Metadata.Class(anyType: superclass) else { + return nil + } + + return metaclass + } + + var vTableSize: Int { + // memory size after ivar destroyer + return Int(pointer.pointee.classObjectSize - pointer.pointee.classObjectAddressPoint) - (contextDescriptorOffsetLocation + 2) * MemoryLayout.size + } + + // reference: https://github.com/apple/swift/blob/master/docs/ABI/TypeMetadata.rst#generic-argument-vector + var genericArgumentVector: UnsafeRawPointer? { + let pointer = UnsafePointer(self.pointer) + var superVTableSize = 0 + if let _superclass = self.superclass { + superVTableSize = _superclass.vTableSize / MemoryLayout.size + } + let base = pointer.advanced(by: contextDescriptorOffsetLocation + 2 + superVTableSize) + if base.pointee == 0 { + return nil + } + return UnsafeRawPointer(base) + } + + func _propertyDescriptionsAndStartPoint() -> ([Property.Description], Int32?)? { + let instanceStart = pointer.pointee.class_rw_t()?.pointee.class_ro_t()?.pointee.instanceStart + var result: [Property.Description] = [] + if let fieldOffsets = self.fieldOffsets, let fieldRecords = self.reflectionFieldDescriptor?.fieldRecords { + class NameAndType { + var name: String? + var type: Any.Type? + } + + for i in 0.. 0 { + + return (superclassProperties.0 + result, superclassProperties.1) + } + return (result, instanceStart) + } + + func propertyDescriptions() -> [Property.Description]? { + let propsAndStp = _propertyDescriptionsAndStartPoint() + if let firstInstanceStart = propsAndStp?.1, + let firstProperty = propsAndStp?.0.first?.offset { + return propsAndStp?.0.map({ (propertyDesc) -> Property.Description in + let offset = propertyDesc.offset - firstProperty + Int(firstInstanceStart) + return Property.Description(key: propertyDesc.key, type: propertyDesc.type, offset: offset) + }) + } else { + return propsAndStp?.0 + } + } + } +} + +extension _Metadata { + struct _Class { + var kind: Int + var superclass: Any.Type? + var reserveword1: Int + var reserveword2: Int + var rodataPointer: UInt + var classFlags: UInt32 + var instanceAddressPoint: UInt32 + var instanceSize: UInt32 + var instanceAlignmentMask: UInt16 + var runtimeReservedField: UInt16 + var classObjectSize: UInt32 + var classObjectAddressPoint: UInt32 + var nominalTypeDescriptor: Int + var ivarDestroyer: Int + // other fields we don't care + + func class_rw_t() -> UnsafePointer<_class_rw_t>? { + if MemoryLayout.size == MemoryLayout.size { + let fast_data_mask: UInt64 = 0x00007ffffffffff8 + let databits_t: UInt64 = UInt64(self.rodataPointer) + return UnsafePointer<_class_rw_t>(bitPattern: UInt(databits_t & fast_data_mask)) + } else { + return UnsafePointer<_class_rw_t>(bitPattern: self.rodataPointer & 0xfffffffc) + } + } + } +} + +// MARK: Metadata + Struct +extension Metadata { + struct Struct : ContextDescriptorType { + static let kind: Kind? = .struct + var pointer: UnsafePointer<_Metadata._Struct> + var contextDescriptorOffsetLocation: Int { + return 1 + } + + var genericArgumentOffsetLocation: Int { + return 2 + } + + var genericArgumentVector: UnsafeRawPointer? { + let pointer = UnsafePointer(self.pointer) + let base = pointer.advanced(by: genericArgumentOffsetLocation) + if base.pointee == 0 { + return nil + } + return UnsafeRawPointer(base) + } + + func propertyDescriptions() -> [Property.Description]? { + guard let fieldOffsets = self.fieldOffsets, let fieldRecords = self.reflectionFieldDescriptor?.fieldRecords else { + return [] + } + var result: [Property.Description] = [] + class NameAndType { + var name: String? + var type: Any.Type? + } + for i in 0.. + var contextDescriptorOffsetLocation: Int { + return is64BitPlatform ? 8 : 11 + } + + var targetType: Any.Type? { + get { + return pointer.pointee.targetType + } + } + } +} + +extension _Metadata { + struct _ObjcClassWrapper { + var kind: Int + var targetType: Any.Type? + } +} diff --git a/Pods/HandyJSON/Source/NSDecimalNumberTransform.swift b/Pods/HandyJSON/Source/NSDecimalNumberTransform.swift new file mode 100644 index 0000000..3b3ebab --- /dev/null +++ b/Pods/HandyJSON/Source/NSDecimalNumberTransform.swift @@ -0,0 +1,51 @@ +// +// TransformOf.swift +// ObjectMapper +// +// Created by Tristan Himmelman on 8/22/16. +// +// The MIT License (MIT) +// +// Copyright (c) 2014-2016 Hearst +// +// Permission is hereby granted, free of charge, to any person obtaining a copy +// of this software and associated documentation files (the "Software"), to deal +// in the Software without restriction, including without limitation the rights +// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +// copies of the Software, and to permit persons to whom the Software is +// furnished to do so, subject to the following conditions: +// +// The above copyright notice and this permission notice shall be included in +// all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN +// THE SOFTWARE. + +import Foundation + +open class NSDecimalNumberTransform: TransformType { + public typealias Object = NSDecimalNumber + public typealias JSON = String + + public init() {} + + open func transformFromJSON(_ value: Any?) -> NSDecimalNumber? { + if let string = value as? String { + return NSDecimalNumber(string: string) + } + if let double = value as? Double { + return NSDecimalNumber(value: double) + } + return nil + } + + open func transformToJSON(_ value: NSDecimalNumber?) -> String? { + guard let value = value else { return nil } + return value.description + } +} diff --git a/Pods/HandyJSON/Source/OtherExtension.swift b/Pods/HandyJSON/Source/OtherExtension.swift new file mode 100644 index 0000000..3834211 --- /dev/null +++ b/Pods/HandyJSON/Source/OtherExtension.swift @@ -0,0 +1,76 @@ +/* + * Copyright 1999-2101 Alibaba Group. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +// +// OtherExtension.swift +// HandyJSON +// +// Created by zhouzhuo on 08/01/2017. +// + +protocol UTF8Initializable { + init?(validatingUTF8: UnsafePointer) +} + +extension String : UTF8Initializable {} + +extension Array where Element : UTF8Initializable { + + init(utf8Strings: UnsafePointer) { + var strings = [Element]() + var pointer = utf8Strings + while let string = Element(validatingUTF8: pointer) { + strings.append(string) + while pointer.pointee != 0 { + pointer.advance() + } + pointer.advance() + guard pointer.pointee != 0 else { + break + } + } + self = strings + } +} + +extension Strideable { + mutating func advance() { + self = advanced(by: 1) + } +} + +extension UnsafePointer { + + init(_ pointer: UnsafePointer) { + self = UnsafeRawPointer(pointer).assumingMemoryBound(to: Pointee.self) + } +} + +func relativePointer(base: UnsafePointer, offset: U) -> UnsafePointer where U : FixedWidthInteger { + return UnsafeRawPointer(base).advanced(by: Int(integer: offset)).assumingMemoryBound(to: V.self) +} + +extension Int { + fileprivate init(integer: T) { + switch integer { + case let value as Int: self = value + case let value as Int32: self = Int(value) + case let value as Int16: self = Int(value) + case let value as Int8: self = Int(value) + default: self = 0 + } + } +} diff --git a/Pods/HandyJSON/Source/PointerType.swift b/Pods/HandyJSON/Source/PointerType.swift new file mode 100644 index 0000000..d46646f --- /dev/null +++ b/Pods/HandyJSON/Source/PointerType.swift @@ -0,0 +1,37 @@ +/* + * Copyright 1999-2101 Alibaba Group. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +// +// Created by zhouzhuo on 07/01/2017. +// + +protocol PointerType : Equatable { + associatedtype Pointee + var pointer: UnsafePointer { get set } +} + +extension PointerType { + init(pointer: UnsafePointer) { + func cast(_ value: T) -> U { + return unsafeBitCast(value, to: U.self) + } + self = cast(UnsafePointer(pointer)) + } +} + +func == (lhs: T, rhs: T) -> Bool { + return lhs.pointer == rhs.pointer +} diff --git a/Pods/HandyJSON/Source/Properties.swift b/Pods/HandyJSON/Source/Properties.swift new file mode 100644 index 0000000..7f2512d --- /dev/null +++ b/Pods/HandyJSON/Source/Properties.swift @@ -0,0 +1,68 @@ +/* + * Copyright 1999-2101 Alibaba Group. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +// +// Created by zhouzhuo on 07/01/2017. +// + + +/// An instance property +struct Property { + let key: String + let value: Any + + /// An instance property description + struct Description { + public let key: String + public let type: Any.Type + public let offset: Int + public func write(_ value: Any, to storage: UnsafeMutableRawPointer) { + return extensions(of: type).write(value, to: storage.advanced(by: offset)) + } + } +} + +/// Retrieve properties for `instance` +func getProperties(forInstance instance: Any) -> [Property]? { + if let props = getProperties(forType: type(of: instance)) { + var copy = extensions(of: instance) + let storage = copy.storage() + return props.map { + nextProperty(description: $0, storage: storage) + } + } + return nil +} + +private func nextProperty(description: Property.Description, storage: UnsafeRawPointer) -> Property { + return Property( + key: description.key, + value: extensions(of: description.type).value(from: storage.advanced(by: description.offset)) + ) +} + +/// Retrieve property descriptions for `type` +func getProperties(forType type: Any.Type) -> [Property.Description]? { + if let structDescriptor = Metadata.Struct(anyType: type) { + return structDescriptor.propertyDescriptions() + } else if let classDescriptor = Metadata.Class(anyType: type) { + return classDescriptor.propertyDescriptions() + } else if let objcClassDescriptor = Metadata.ObjcClassWrapper(anyType: type), + let targetType = objcClassDescriptor.targetType { + return getProperties(forType: targetType) + } + return nil +} diff --git a/Pods/HandyJSON/Source/PropertyInfo.swift b/Pods/HandyJSON/Source/PropertyInfo.swift new file mode 100644 index 0000000..c914cf1 --- /dev/null +++ b/Pods/HandyJSON/Source/PropertyInfo.swift @@ -0,0 +1,29 @@ +/* + * Copyright 1999-2101 Alibaba Group. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +// +// PropertyInfo.swift +// HandyJSON +// +// Created by zhouzhuo on 20/08/2017. +// + +struct PropertyInfo { + let key: String + let type: Any.Type + let address: UnsafeMutableRawPointer + let bridged: Bool +} diff --git a/Pods/HandyJSON/Source/ReflectionHelper.swift b/Pods/HandyJSON/Source/ReflectionHelper.swift new file mode 100644 index 0000000..c958463 --- /dev/null +++ b/Pods/HandyJSON/Source/ReflectionHelper.swift @@ -0,0 +1,42 @@ +/* + * Copyright 1999-2101 Alibaba Group. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +// +// Helper.swift +// HandyJSON +// +// Created by zhouzhuo on 07/01/2017. +// + +struct ReflectionHelper { + + static func mutableStorage(instance: inout T) -> UnsafeMutableRawPointer { + return UnsafeMutableRawPointer(mutating: storage(instance: &instance)) + } + + static func storage(instance: inout T) -> UnsafeRawPointer { + if type(of: instance) is AnyClass { + let opaquePointer = Unmanaged.passUnretained(instance as AnyObject).toOpaque() + return UnsafeRawPointer(opaquePointer) + } else { + return withUnsafePointer(to: &instance) { pointer in + return UnsafeRawPointer(pointer) + } + } + } +} + + diff --git a/Pods/HandyJSON/Source/Serializer.swift b/Pods/HandyJSON/Source/Serializer.swift new file mode 100644 index 0000000..e05f563 --- /dev/null +++ b/Pods/HandyJSON/Source/Serializer.swift @@ -0,0 +1,84 @@ +/* + * Copyright 1999-2101 Alibaba Group. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +// +// JSONSerializer.swift +// HandyJSON +// +// Created by zhouzhuo on 9/30/16. +// + +import Foundation + +public extension HandyJSON { + + func toJSON() -> [String: Any]? { + if let dict = Self._serializeAny(object: self) as? [String: Any] { + return dict + } + return nil + } + + func toJSONString(prettyPrint: Bool = false) -> String? { + + if let anyObject = self.toJSON() { + if JSONSerialization.isValidJSONObject(anyObject) { + do { + let jsonData: Data + if prettyPrint { + jsonData = try JSONSerialization.data(withJSONObject: anyObject, options: [.prettyPrinted]) + } else { + jsonData = try JSONSerialization.data(withJSONObject: anyObject, options: []) + } + return String(data: jsonData, encoding: .utf8) + } catch let error { + InternalLogger.logError(error) + } + } else { + InternalLogger.logDebug("\(anyObject)) is not a valid JSON Object") + } + } + return nil + } +} + +public extension Collection where Iterator.Element: HandyJSON { + + func toJSON() -> [[String: Any]?] { + return self.map{ $0.toJSON() } + } + + func toJSONString(prettyPrint: Bool = false) -> String? { + + let anyArray = self.toJSON() + if JSONSerialization.isValidJSONObject(anyArray) { + do { + let jsonData: Data + if prettyPrint { + jsonData = try JSONSerialization.data(withJSONObject: anyArray, options: [.prettyPrinted]) + } else { + jsonData = try JSONSerialization.data(withJSONObject: anyArray, options: []) + } + return String(data: jsonData, encoding: .utf8) + } catch let error { + InternalLogger.logError(error) + } + } else { + InternalLogger.logDebug("\(self.toJSON()) is not a valid JSON Object") + } + return nil + } +} diff --git a/Pods/HandyJSON/Source/TransformOf.swift b/Pods/HandyJSON/Source/TransformOf.swift new file mode 100644 index 0000000..97056c6 --- /dev/null +++ b/Pods/HandyJSON/Source/TransformOf.swift @@ -0,0 +1,48 @@ +// +// TransformOf.swift +// ObjectMapper +// +// Created by Syo Ikeda on 1/23/15. +// +// The MIT License (MIT) +// +// Copyright (c) 2014-2016 Hearst +// +// Permission is hereby granted, free of charge, to any person obtaining a copy +// of this software and associated documentation files (the "Software"), to deal +// in the Software without restriction, including without limitation the rights +// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +// copies of the Software, and to permit persons to whom the Software is +// furnished to do so, subject to the following conditions: +// +// The above copyright notice and this permission notice shall be included in +// all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN +// THE SOFTWARE. + +open class TransformOf: TransformType { + public typealias Object = ObjectType + public typealias JSON = JSONType + + private let fromJSON: (JSONType?) -> ObjectType? + private let toJSON: (ObjectType?) -> JSONType? + + public init(fromJSON: @escaping(JSONType?) -> ObjectType?, toJSON: @escaping(ObjectType?) -> JSONType?) { + self.fromJSON = fromJSON + self.toJSON = toJSON + } + + open func transformFromJSON(_ value: Any?) -> ObjectType? { + return fromJSON(value as? JSONType) + } + + open func transformToJSON(_ value: ObjectType?) -> JSONType? { + return toJSON(value) + } +} diff --git a/Pods/HandyJSON/Source/TransformType.swift b/Pods/HandyJSON/Source/TransformType.swift new file mode 100644 index 0000000..61578c3 --- /dev/null +++ b/Pods/HandyJSON/Source/TransformType.swift @@ -0,0 +1,35 @@ +// +// TransformType.swift +// ObjectMapper +// +// Created by Syo Ikeda on 2/4/15. +// +// The MIT License (MIT) +// +// Copyright (c) 2014-2016 Hearst +// +// Permission is hereby granted, free of charge, to any person obtaining a copy +// of this software and associated documentation files (the "Software"), to deal +// in the Software without restriction, including without limitation the rights +// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +// copies of the Software, and to permit persons to whom the Software is +// furnished to do so, subject to the following conditions: +// +// The above copyright notice and this permission notice shall be included in +// all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN +// THE SOFTWARE. + +public protocol TransformType { + associatedtype Object + associatedtype JSON + + func transformFromJSON(_ value: Any?) -> Object? + func transformToJSON(_ value: Object?) -> JSON? +} diff --git a/Pods/HandyJSON/Source/Transformable.swift b/Pods/HandyJSON/Source/Transformable.swift new file mode 100644 index 0000000..d03bb31 --- /dev/null +++ b/Pods/HandyJSON/Source/Transformable.swift @@ -0,0 +1,52 @@ +// +// Transformable.swift +// HandyJSON +// +// Created by zhouzhuo on 15/07/2017. +// Copyright © 2017 aliyun. All rights reserved. +// + +import Foundation + +public protocol _Transformable: _Measurable {} + +extension _Transformable { + + static func transform(from object: Any) -> Self? { + if let typedObject = object as? Self { + return typedObject + } + switch self { + case let type as _ExtendCustomBasicType.Type: + return type._transform(from: object) as? Self + case let type as _BuiltInBridgeType.Type: + return type._transform(from: object) as? Self + case let type as _BuiltInBasicType.Type: + return type._transform(from: object) as? Self + case let type as _RawEnumProtocol.Type: + return type._transform(from: object) as? Self + case let type as _ExtendCustomModelType.Type: + return type._transform(from: object) as? Self + default: + return nil + } + } + + func plainValue() -> Any? { + switch self { + case let rawValue as _ExtendCustomBasicType: + return rawValue._plainValue() + case let rawValue as _BuiltInBridgeType: + return rawValue._plainValue() + case let rawValue as _BuiltInBasicType: + return rawValue._plainValue() + case let rawValue as _RawEnumProtocol: + return rawValue._plainValue() + case let rawValue as _ExtendCustomModelType: + return rawValue._plainValue() + default: + return nil + } + } +} + diff --git a/Pods/HandyJSON/Source/URLTransform.swift b/Pods/HandyJSON/Source/URLTransform.swift new file mode 100644 index 0000000..ac9723b --- /dev/null +++ b/Pods/HandyJSON/Source/URLTransform.swift @@ -0,0 +1,65 @@ +// +// URLTransform.swift +// ObjectMapper +// +// Created by Tristan Himmelman on 2014-10-27. +// +// The MIT License (MIT) +// +// Copyright (c) 2014-2016 Hearst +// +// Permission is hereby granted, free of charge, to any person obtaining a copy +// of this software and associated documentation files (the "Software"), to deal +// in the Software without restriction, including without limitation the rights +// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +// copies of the Software, and to permit persons to whom the Software is +// furnished to do so, subject to the following conditions: +// +// The above copyright notice and this permission notice shall be included in +// all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN +// THE SOFTWARE. + +import Foundation + +open class URLTransform: TransformType { + public typealias Object = URL + public typealias JSON = String + private let shouldEncodeURLString: Bool + + /** + Initializes the URLTransform with an option to encode URL strings before converting them to an NSURL + - parameter shouldEncodeUrlString: when true (the default) the string is encoded before passing + to `NSURL(string:)` + - returns: an initialized transformer + */ + public init(shouldEncodeURLString: Bool = true) { + self.shouldEncodeURLString = shouldEncodeURLString + } + + open func transformFromJSON(_ value: Any?) -> URL? { + guard let URLString = value as? String else { return nil } + + if !shouldEncodeURLString { + return URL(string: URLString) + } + + guard let escapedURLString = URLString.addingPercentEncoding(withAllowedCharacters: CharacterSet.urlQueryAllowed) else { + return nil + } + return URL(string: escapedURLString) + } + + open func transformToJSON(_ value: URL?) -> String? { + if let URL = value { + return URL.absoluteString + } + return nil + } +} diff --git a/Pods/Kingfisher/LICENSE b/Pods/Kingfisher/LICENSE new file mode 100644 index 0000000..80888ba --- /dev/null +++ b/Pods/Kingfisher/LICENSE @@ -0,0 +1,22 @@ +The MIT License (MIT) + +Copyright (c) 2019 Wei Wang + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +SOFTWARE. + diff --git a/Pods/Kingfisher/README.md b/Pods/Kingfisher/README.md new file mode 100644 index 0000000..fcddcb5 --- /dev/null +++ b/Pods/Kingfisher/README.md @@ -0,0 +1,259 @@ +

+Kingfisher +

+ +

+ + + + + +

+ +Kingfisher is a powerful, pure-Swift library for downloading and caching images from the web. It provides you a chance to use a pure-Swift way to work with remote images in your next app. + +## Features + +- [x] Asynchronous image downloading and caching. +- [x] Loading image from either `URLSession`-based networking or local provided data. +- [x] Useful image processors and filters provided. +- [x] Multiple-layer hybrid cache for both memory and disk. +- [x] Fine control on cache behavior. Customizable expiration date and size limit. +- [x] Cancelable downloading and auto-reusing previous downloaded content to improve performance. +- [x] Independent components. Use the downloader, caching system, and image processors separately as you need. +- [x] Prefetching images and showing them from the cache to boost your app. +- [x] Extensions for `UIImageView`, `NSImageView`, `NSButton`, `UIButton`, `NSTextAttachment`, `WKInterfaceImage`, `TVMonogramView` and `CPListItem` to directly set an image from a URL. +- [x] Built-in transition animation when setting images. +- [x] Customizable placeholder and indicator while loading images. +- [x] Extensible image processing and image format easily. +- [x] Low Data Mode support. +- [x] SwiftUI support. + +### Kingfisher 101 + +The simplest use-case is setting an image to an image view with the `UIImageView` extension: + +```swift +import Kingfisher + +let url = URL(string: "https://example.com/image.png") +imageView.kf.setImage(with: url) +``` + +Kingfisher will download the image from `url`, send it to both memory cache and disk cache, and display it in `imageView`. +When you set it with the same URL later, the image will be retrieved from the cache and shown immediately. + +It also works if you use SwiftUI: + +```swift +var body: some View { + KFImage(URL(string: "https://example.com/image.png")!) +} +``` + +### A More Advanced Example + +With the powerful options, you can do hard tasks with Kingfisher in a simple way. For example, the code below: + +1. Downloads a high-resolution image. +2. Downsamples it to match the image view size. +3. Makes it round cornered with a given radius. +4. Shows a system indicator and a placeholder image while downloading. +5. When prepared, it animates the small thumbnail image with a "fade in" effect. +6. The original large image is also cached to disk for later use, to get rid of downloading it again in a detail view. +7. A console log is printed when the task finishes, either for success or failure. + +```swift +let url = URL(string: "https://example.com/high_resolution_image.png") +let processor = DownsamplingImageProcessor(size: imageView.bounds.size) + |> RoundCornerImageProcessor(cornerRadius: 20) +imageView.kf.indicatorType = .activity +imageView.kf.setImage( + with: url, + placeholder: UIImage(named: "placeholderImage"), + options: [ + .processor(processor), + .scaleFactor(UIScreen.main.scale), + .transition(.fade(1)), + .cacheOriginalImage + ]) +{ + result in + switch result { + case .success(let value): + print("Task done for: \(value.source.url?.absoluteString ?? "")") + case .failure(let error): + print("Job failed: \(error.localizedDescription)") + } +} +``` + +It is a common situation I can meet in my daily work. Think about how many lines you need to write without +Kingfisher! + +### Method Chaining + +If you are not a fan of the `kf` extension, you can also prefer to use the `KF` builder and chained the method +invocations. The code below is doing the same thing: + +```swift +// Use `kf` extension +imageView.kf.setImage( + with: url, + placeholder: placeholderImage, + options: [ + .processor(processor), + .loadDiskFileSynchronously, + .cacheOriginalImage, + .transition(.fade(0.25)), + .lowDataMode(.network(lowResolutionURL)) + ], + progressBlock: { receivedSize, totalSize in + // Progress updated + }, + completionHandler: { result in + // Done + } +) + +// Use `KF` builder +KF.url(url) + .placeholder(placeholderImage) + .setProcessor(processor) + .loadDiskFileSynchronously() + .cacheMemoryOnly() + .fade(duration: 0.25) + .lowDataModeSource(.network(lowResolutionURL)) + .onProgress { receivedSize, totalSize in } + .onSuccess { result in } + .onFailure { error in } + .set(to: imageView) +``` + +And even better, if later you want to switch to SwiftUI, just change the `KF` above to `KFImage`, and you've done: + +```swift +struct ContentView: View { + var body: some View { + KFImage.url(url) + .placeholder(placeholderImage) + .setProcessor(processor) + .loadDiskFileSynchronously() + .cacheMemoryOnly() + .fade(duration: 0.25) + .lowDataModeSource(.network(lowResolutionURL)) + .onProgress { receivedSize, totalSize in } + .onSuccess { result in } + .onFailure { error in } + } +} +``` + +### Learn More + +To learn the use of Kingfisher by more examples, take a look at the well-prepared [Cheat Sheet](https://github.com/onevcat/Kingfisher/wiki/Cheat-Sheet). +There we summarized the most common tasks in Kingfisher, you can get a better idea of what this framework can do. +There are also some performance tips, remember to check them too. + +## Requirements + +- iOS 12.0+ / macOS 10.14+ / tvOS 12.0+ / watchOS 5.0+ (if you use only UIKit/AppKit) +- iOS 14.0+ / macOS 11.0+ / tvOS 14.0+ / watchOS 7.0+ (if you use it in SwiftUI) +- Swift 5.0+ + +> If you need support from iOS 10 (UIKit/AppKit) or iOS 13 (SwiftUI), use Kingfisher version 6.x. But it won't work +> with Xcode 13.0 and Xcode 13.1 [#1802](https://github.com/onevcat/Kingfisher/issues/1802). +> +> If you need to use Xcode 13.0 and 13.1 but cannot upgrade to v7, use the `version6-xcode13` branch. However, you have to drop +> iOS 10 support due to another Xcode 13 bug. +> +> | UIKit | SwiftUI | Xcode | Kingfisher | +> |---|---|---|---| +> | iOS 10+ | iOS 13+ | 12 | ~> 6.3.1 | +> | iOS 11+ | iOS 13+ | 13 | `version6-xcode13` | +> | iOS 12+ | iOS 14+ | 13 | ~> 7.0 | + +### Installation + +A detailed guide for installation can be found in [Installation Guide](https://github.com/onevcat/Kingfisher/wiki/Installation-Guide). + +#### Swift Package Manager + +- File > Swift Packages > Add Package Dependency +- Add `https://github.com/onevcat/Kingfisher.git` +- Select "Up to Next Major" with "7.0.0" + +#### CocoaPods + +```ruby +source 'https://github.com/CocoaPods/Specs.git' +platform :ios, '12.0' +use_frameworks! + +target 'MyApp' do + pod 'Kingfisher', '~> 7.0' +end +``` + +#### Carthage + +``` +github "onevcat/Kingfisher" ~> 7.0 +``` + + +### Migrating + +[Kingfisher 7.0 Migration](https://github.com/onevcat/Kingfisher/wiki/Kingfisher-7.0-Migration-Guide) - Kingfisher 7.x is NOT fully compatible with the previous version. However, changes should be trivial or not required at all. Please follow the [migration guide](https://github.com/onevcat/Kingfisher/wiki/Kingfisher-7.0-Migration-Guide) when you prepare to upgrade Kingfisher in your project. + +If you are using an even earlier version, see the guides below to know the steps for migrating. + +> - [Kingfisher 6.0 Migration](https://github.com/onevcat/Kingfisher/wiki/Kingfisher-6.0-Migration-Guide) - Kingfisher 6.x is NOT fully compatible with the previous version. However, migration is not difficult. Depending on your use cases, it may take no effect or several minutes to modify your existing code for the new version. Please follow the [migration guide](https://github.com/onevcat/Kingfisher/wiki/Kingfisher-6.0-Migration-Guide) when you prepare to upgrade Kingfisher in your project. +> - [Kingfisher 5.0 Migration](https://github.com/onevcat/Kingfisher/wiki/Kingfisher-5.0-Migration-Guide) - If you are upgrading to Kingfisher 5.x from 4.x, please read this for more information. +> - Kingfisher 4.0 Migration - Kingfisher 3.x should be source compatible to Kingfisher 4. The reason for a major update is that we need to specify the Swift version explicitly for Xcode. All deprecated methods in Kingfisher 3 were removed, so please ensure you have no warning left before you migrate from Kingfisher 3 with Kingfisher 4. If you have any trouble when migrating, please open an issue to discuss. +> - [Kingfisher 3.0 Migration](https://github.com/onevcat/Kingfisher/wiki/Kingfisher-3.0-Migration-Guide) - If you are upgrading to Kingfisher 3.x from an earlier version, please read this for more information. + +## Next Steps + +We prepared a [wiki page](https://github.com/onevcat/Kingfisher/wiki). You can find tons of useful things there. + +* [Installation Guide](https://github.com/onevcat/Kingfisher/wiki/Installation-Guide) - Follow it to integrate Kingfisher into your project. +* [Cheat Sheet](https://github.com/onevcat/Kingfisher/wiki/Cheat-Sheet)- Curious about what Kingfisher could do and how would it look like when used in your project? See this page for useful code snippets. If you are already familiar with Kingfisher, you could also learn new tricks to improve the way you use Kingfisher! +* [API Reference](https://swiftpackageindex.com/onevcat/Kingfisher/master/documentation/kingfisher) - Lastly, please remember to read the full API reference whenever you need more detailed documentation. + +## Other + +### Future of Kingfisher + +I want to keep Kingfisher lightweight. This framework focuses on providing a simple solution for downloading and caching images. This doesn’t mean the framework can’t be improved. Kingfisher is far from perfect, so necessary and useful updates will be made to make it better. + +### Developments and Tests + +Any contributing and pull requests are warmly welcome. However, before you plan to implement some features or try to fix an uncertain issue, it is recommended to open a discussion first. It would be appreciated if your pull requests could build with all tests green. :) + +### About the logo + +The logo of Kingfisher is inspired by [Tangram (七巧板)](http://en.wikipedia.org/wiki/Tangram), a dissection puzzle consisting of seven flat shapes from China. I believe she's a kingfisher bird instead of a swift, but someone insists that she is a pigeon. I guess I should give her a name. Hi, guys, do you have any suggestions? + +### Contact + +Follow and contact me on [Twitter](http://twitter.com/onevcat) or [Sina Weibo](http://weibo.com/onevcat). If you find an issue, [open a ticket](https://github.com/onevcat/Kingfisher/issues/new). Pull requests are warmly welcome as well. + +## Backers & Sponsors + +Open-source projects cannot live long without your help. If you find Kingfisher to be useful, please consider supporting this +project by becoming a sponsor. Your user icon or company logo shows up [on my blog](https://onevcat.com/tabs/about/) with a link to your home page. + +Become a sponsor through [GitHub Sponsors](https://github.com/sponsors/onevcat). :heart: + +Special thanks to: + +[![imgly](https://user-images.githubusercontent.com/1812216/106253726-271ed000-6218-11eb-98e0-c9c681925770.png)](https://img.ly/) + +[![emergetools](https://github-production-user-asset-6210df.s3.amazonaws.com/1019875/254794187-d44f6f50-993f-42e3-b79c-960f69c4adc1.png)](https://www.emergetools.com) + + + +### License + +Kingfisher is released under the MIT license. See LICENSE for details. diff --git a/Pods/Kingfisher/Sources/Cache/CacheSerializer.swift b/Pods/Kingfisher/Sources/Cache/CacheSerializer.swift new file mode 100644 index 0000000..c84913f --- /dev/null +++ b/Pods/Kingfisher/Sources/Cache/CacheSerializer.swift @@ -0,0 +1,137 @@ +// +// CacheSerializer.swift +// Kingfisher +// +// Created by Wei Wang on 2016/09/02. +// +// Copyright (c) 2019 Wei Wang +// +// Permission is hereby granted, free of charge, to any person obtaining a copy +// of this software and associated documentation files (the "Software"), to deal +// in the Software without restriction, including without limitation the rights +// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +// copies of the Software, and to permit persons to whom the Software is +// furnished to do so, subject to the following conditions: +// +// The above copyright notice and this permission notice shall be included in +// all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN +// THE SOFTWARE. + +import Foundation +import CoreGraphics +#if os(macOS) +import AppKit +#else +import UIKit +#endif + +/// An `CacheSerializer` is used to convert some data to an image object after +/// retrieving it from disk storage, and vice versa, to convert an image to data object +/// for storing to the disk storage. +public protocol CacheSerializer { + + /// Gets the serialized data from a provided image + /// and optional original data for caching to disk. + /// + /// - Parameters: + /// - image: The image needed to be serialized. + /// - original: The original data which is just downloaded. + /// If the image is retrieved from cache instead of + /// downloaded, it will be `nil`. + /// - Returns: The data object for storing to disk, or `nil` when no valid + /// data could be serialized. + func data(with image: KFCrossPlatformImage, original: Data?) -> Data? + + /// Gets an image from provided serialized data. + /// + /// - Parameters: + /// - data: The data from which an image should be deserialized. + /// - options: The parsed options for deserialization. + /// - Returns: An image deserialized or `nil` when no valid image + /// could be deserialized. + func image(with data: Data, options: KingfisherParsedOptionsInfo) -> KFCrossPlatformImage? + + /// Whether this serializer prefers to cache the original data in its implementation. + /// If `true`, after creating the image from the disk data, Kingfisher will continue to apply the processor to get + /// the final image. + /// + /// By default, it is `false` and the actual processed image is assumed to be serialized to the disk. + var originalDataUsed: Bool { get } +} + +public extension CacheSerializer { + var originalDataUsed: Bool { false } +} + +/// Represents a basic and default `CacheSerializer` used in Kingfisher disk cache system. +/// It could serialize and deserialize images in PNG, JPEG and GIF format. For +/// image other than these formats, a normalized `pngRepresentation` will be used. +public struct DefaultCacheSerializer: CacheSerializer { + + /// The default general cache serializer used across Kingfisher's cache. + public static let `default` = DefaultCacheSerializer() + + /// The compression quality when converting image to a lossy format data. Default is 1.0. + public var compressionQuality: CGFloat = 1.0 + + /// Whether the original data should be preferred when serializing the image. + /// If `true`, the input original data will be checked first and used unless the data is `nil`. + /// In that case, the serialization will fall back to creating data from image. + public var preferCacheOriginalData: Bool = false + + /// Returnes the `preferCacheOriginalData` value. When the original data is used, Kingfisher needs to re-apply the + /// processors to get the desired final image. + public var originalDataUsed: Bool { preferCacheOriginalData } + + /// Creates a cache serializer that serialize and deserialize images in PNG, JPEG and GIF format. + /// + /// - Note: + /// Use `DefaultCacheSerializer.default` unless you need to specify your own properties. + /// + public init() { } + + /// - Parameters: + /// - image: The image needed to be serialized. + /// - original: The original data which is just downloaded. + /// If the image is retrieved from cache instead of + /// downloaded, it will be `nil`. + /// - Returns: The data object for storing to disk, or `nil` when no valid + /// data could be serialized. + /// + /// - Note: + /// Only when `original` contains valid PNG, JPEG and GIF format data, the `image` will be + /// converted to the corresponding data type. Otherwise, if the `original` is provided but it is not + /// If `original` is `nil`, the input `image` will be encoded as PNG data. + public func data(with image: KFCrossPlatformImage, original: Data?) -> Data? { + if preferCacheOriginalData { + return original ?? + image.kf.data( + format: original?.kf.imageFormat ?? .unknown, + compressionQuality: compressionQuality + ) + } else { + return image.kf.data( + format: original?.kf.imageFormat ?? .unknown, + compressionQuality: compressionQuality + ) + } + } + + /// Gets an image deserialized from provided data. + /// + /// - Parameters: + /// - data: The data from which an image should be deserialized. + /// - options: Options for deserialization. + /// - Returns: An image deserialized or `nil` when no valid image + /// could be deserialized. + public func image(with data: Data, options: KingfisherParsedOptionsInfo) -> KFCrossPlatformImage? { + return KingfisherWrapper.image(data: data, options: options.imageCreatingOptions) + } +} diff --git a/Pods/Kingfisher/Sources/Cache/DiskStorage.swift b/Pods/Kingfisher/Sources/Cache/DiskStorage.swift new file mode 100644 index 0000000..56ff8ab --- /dev/null +++ b/Pods/Kingfisher/Sources/Cache/DiskStorage.swift @@ -0,0 +1,616 @@ +// +// DiskStorage.swift +// Kingfisher +// +// Created by Wei Wang on 2018/10/15. +// +// Copyright (c) 2019 Wei Wang +// +// Permission is hereby granted, free of charge, to any person obtaining a copy +// of this software and associated documentation files (the "Software"), to deal +// in the Software without restriction, including without limitation the rights +// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +// copies of the Software, and to permit persons to whom the Software is +// furnished to do so, subject to the following conditions: +// +// The above copyright notice and this permission notice shall be included in +// all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN +// THE SOFTWARE. + +import Foundation + + +/// Represents a set of conception related to storage which stores a certain type of value in disk. +/// This is a namespace for the disk storage types. A `Backend` with a certain `Config` will be used to describe the +/// storage. See these composed types for more information. +public enum DiskStorage { + + /// Represents a storage back-end for the `DiskStorage`. The value is serialized to data + /// and stored as file in the file system under a specified location. + /// + /// You can config a `DiskStorage.Backend` in its initializer by passing a `DiskStorage.Config` value. + /// or modifying the `config` property after it being created. `DiskStorage` will use file's attributes to keep + /// track of a file for its expiration or size limitation. + public class Backend { + /// The config used for this disk storage. + public var config: Config + + // The final storage URL on disk, with `name` and `cachePathBlock` considered. + public let directoryURL: URL + + let metaChangingQueue: DispatchQueue + + var maybeCached : Set? + let maybeCachedCheckingQueue = DispatchQueue(label: "com.onevcat.Kingfisher.maybeCachedCheckingQueue") + + // `false` if the storage initialized with an error. This prevents unexpected forcibly crash when creating + // storage in the default cache. + private var storageReady: Bool = true + + /// Creates a disk storage with the given `DiskStorage.Config`. + /// + /// - Parameter config: The config used for this disk storage. + /// - Throws: An error if the folder for storage cannot be got or created. + public convenience init(config: Config) throws { + self.init(noThrowConfig: config, creatingDirectory: false) + try prepareDirectory() + } + + // If `creatingDirectory` is `false`, the directory preparation will be skipped. + // We need to call `prepareDirectory` manually after this returns. + init(noThrowConfig config: Config, creatingDirectory: Bool) { + var config = config + + let creation = Creation(config) + self.directoryURL = creation.directoryURL + + // Break any possible retain cycle set by outside. + config.cachePathBlock = nil + self.config = config + + metaChangingQueue = DispatchQueue(label: creation.cacheName) + setupCacheChecking() + + if creatingDirectory { + try? prepareDirectory() + } + } + + private func setupCacheChecking() { + maybeCachedCheckingQueue.async { + do { + self.maybeCached = Set() + try self.config.fileManager.contentsOfDirectory(atPath: self.directoryURL.path).forEach { fileName in + self.maybeCached?.insert(fileName) + } + } catch { + // Just disable the functionality if we fail to initialize it properly. This will just revert to + // the behavior which is to check file existence on disk directly. + self.maybeCached = nil + } + } + } + + // Creates the storage folder. + private func prepareDirectory() throws { + let fileManager = config.fileManager + let path = directoryURL.path + + guard !fileManager.fileExists(atPath: path) else { return } + + do { + try fileManager.createDirectory( + atPath: path, + withIntermediateDirectories: true, + attributes: nil) + } catch { + self.storageReady = false + throw KingfisherError.cacheError(reason: .cannotCreateDirectory(path: path, error: error)) + } + } + + /// Stores a value to the storage under the specified key and expiration policy. + /// - Parameters: + /// - value: The value to be stored. + /// - key: The key to which the `value` will be stored. If there is already a value under the key, + /// the old value will be overwritten by `value`. + /// - expiration: The expiration policy used by this store action. + /// - writeOptions: Data writing options used the new files. + /// - Throws: An error during converting the value to a data format or during writing it to disk. + public func store( + value: T, + forKey key: String, + expiration: StorageExpiration? = nil, + writeOptions: Data.WritingOptions = []) throws + { + guard storageReady else { + throw KingfisherError.cacheError(reason: .diskStorageIsNotReady(cacheURL: directoryURL)) + } + + let expiration = expiration ?? config.expiration + // The expiration indicates that already expired, no need to store. + guard !expiration.isExpired else { return } + + let data: Data + do { + data = try value.toData() + } catch { + throw KingfisherError.cacheError(reason: .cannotConvertToData(object: value, error: error)) + } + + let fileURL = cacheFileURL(forKey: key) + do { + try data.write(to: fileURL, options: writeOptions) + } catch { + if error.isFolderMissing { + // The whole cache folder is deleted. Try to recreate it and write file again. + do { + try prepareDirectory() + try data.write(to: fileURL, options: writeOptions) + } catch { + throw KingfisherError.cacheError( + reason: .cannotCreateCacheFile(fileURL: fileURL, key: key, data: data, error: error) + ) + } + } else { + throw KingfisherError.cacheError( + reason: .cannotCreateCacheFile(fileURL: fileURL, key: key, data: data, error: error) + ) + } + } + + let now = Date() + let attributes: [FileAttributeKey : Any] = [ + // The last access date. + .creationDate: now.fileAttributeDate, + // The estimated expiration date. + .modificationDate: expiration.estimatedExpirationSinceNow.fileAttributeDate + ] + do { + try config.fileManager.setAttributes(attributes, ofItemAtPath: fileURL.path) + } catch { + try? config.fileManager.removeItem(at: fileURL) + throw KingfisherError.cacheError( + reason: .cannotSetCacheFileAttribute( + filePath: fileURL.path, + attributes: attributes, + error: error + ) + ) + } + + maybeCachedCheckingQueue.async { + self.maybeCached?.insert(fileURL.lastPathComponent) + } + } + + /// Gets a value from the storage. + /// - Parameters: + /// - key: The cache key of value. + /// - extendingExpiration: The expiration policy used by this getting action. + /// - Throws: An error during converting the data to a value or during operation of disk files. + /// - Returns: The value under `key` if it is valid and found in the storage. Otherwise, `nil`. + public func value(forKey key: String, extendingExpiration: ExpirationExtending = .cacheTime) throws -> T? { + return try value(forKey: key, referenceDate: Date(), actuallyLoad: true, extendingExpiration: extendingExpiration) + } + + func value( + forKey key: String, + referenceDate: Date, + actuallyLoad: Bool, + extendingExpiration: ExpirationExtending) throws -> T? + { + guard storageReady else { + throw KingfisherError.cacheError(reason: .diskStorageIsNotReady(cacheURL: directoryURL)) + } + + let fileManager = config.fileManager + let fileURL = cacheFileURL(forKey: key) + let filePath = fileURL.path + + let fileMaybeCached = maybeCachedCheckingQueue.sync { + return maybeCached?.contains(fileURL.lastPathComponent) ?? true + } + guard fileMaybeCached else { + return nil + } + guard fileManager.fileExists(atPath: filePath) else { + return nil + } + + let meta: FileMeta + do { + let resourceKeys: Set = [.contentModificationDateKey, .creationDateKey] + meta = try FileMeta(fileURL: fileURL, resourceKeys: resourceKeys) + } catch { + throw KingfisherError.cacheError( + reason: .invalidURLResource(error: error, key: key, url: fileURL)) + } + + if meta.expired(referenceDate: referenceDate) { + return nil + } + if !actuallyLoad { return T.empty } + + do { + let data = try Data(contentsOf: fileURL) + let obj = try T.fromData(data) + metaChangingQueue.async { + meta.extendExpiration(with: fileManager, extendingExpiration: extendingExpiration) + } + return obj + } catch { + throw KingfisherError.cacheError(reason: .cannotLoadDataFromDisk(url: fileURL, error: error)) + } + } + + /// Whether there is valid cached data under a given key. + /// - Parameter key: The cache key of value. + /// - Returns: If there is valid data under the key, `true`. Otherwise, `false`. + /// + /// - Note: + /// This method does not actually load the data from disk, so it is faster than directly loading the cached value + /// by checking the nullability of `value(forKey:extendingExpiration:)` method. + /// + public func isCached(forKey key: String) -> Bool { + return isCached(forKey: key, referenceDate: Date()) + } + + /// Whether there is valid cached data under a given key and a reference date. + /// - Parameters: + /// - key: The cache key of value. + /// - referenceDate: A reference date to check whether the cache is still valid. + /// - Returns: If there is valid data under the key, `true`. Otherwise, `false`. + /// + /// - Note: + /// If you pass `Date()` to `referenceDate`, this method is identical to `isCached(forKey:)`. Use the + /// `referenceDate` to determine whether the cache is still valid for a future date. + public func isCached(forKey key: String, referenceDate: Date) -> Bool { + do { + let result = try value( + forKey: key, + referenceDate: referenceDate, + actuallyLoad: false, + extendingExpiration: .none + ) + return result != nil + } catch { + return false + } + } + + /// Removes a value from a specified key. + /// - Parameter key: The cache key of value. + /// - Throws: An error during removing the value. + public func remove(forKey key: String) throws { + let fileURL = cacheFileURL(forKey: key) + try removeFile(at: fileURL) + } + + func removeFile(at url: URL) throws { + try config.fileManager.removeItem(at: url) + } + + /// Removes all values in this storage. + /// - Throws: An error during removing the values. + public func removeAll() throws { + try removeAll(skipCreatingDirectory: false) + } + + func removeAll(skipCreatingDirectory: Bool) throws { + try config.fileManager.removeItem(at: directoryURL) + if !skipCreatingDirectory { + try prepareDirectory() + } + } + + /// The URL of the cached file with a given computed `key`. + /// + /// - Parameter key: The final computed key used when caching the image. Please note that usually this is not + /// the `cacheKey` of an image `Source`. It is the computed key with processor identifier considered. + /// + /// - Note: + /// This method does not guarantee there is an image already cached in the returned URL. It just gives your + /// the URL that the image should be if it exists in disk storage, with the give key. + /// + public func cacheFileURL(forKey key: String) -> URL { + let fileName = cacheFileName(forKey: key) + return directoryURL.appendingPathComponent(fileName, isDirectory: false) + } + + func cacheFileName(forKey key: String) -> String { + if config.usesHashedFileName { + let hashedKey = key.kf.md5 + if let ext = config.pathExtension { + return "\(hashedKey).\(ext)" + } else if config.autoExtAfterHashedFileName, + let ext = key.kf.ext { + return "\(hashedKey).\(ext)" + } + return hashedKey + } else { + if let ext = config.pathExtension { + return "\(key).\(ext)" + } + return key + } + } + + func allFileURLs(for propertyKeys: [URLResourceKey]) throws -> [URL] { + let fileManager = config.fileManager + + guard let directoryEnumerator = fileManager.enumerator( + at: directoryURL, includingPropertiesForKeys: propertyKeys, options: .skipsHiddenFiles) else + { + throw KingfisherError.cacheError(reason: .fileEnumeratorCreationFailed(url: directoryURL)) + } + + guard let urls = directoryEnumerator.allObjects as? [URL] else { + throw KingfisherError.cacheError(reason: .invalidFileEnumeratorContent(url: directoryURL)) + } + return urls + } + + /// Removes all expired values from this storage. + /// - Throws: A file manager error during removing the file. + /// - Returns: The URLs for removed files. + public func removeExpiredValues() throws -> [URL] { + return try removeExpiredValues(referenceDate: Date()) + } + + func removeExpiredValues(referenceDate: Date) throws -> [URL] { + let propertyKeys: [URLResourceKey] = [ + .isDirectoryKey, + .contentModificationDateKey + ] + + let urls = try allFileURLs(for: propertyKeys) + let keys = Set(propertyKeys) + let expiredFiles = urls.filter { fileURL in + do { + let meta = try FileMeta(fileURL: fileURL, resourceKeys: keys) + if meta.isDirectory { + return false + } + return meta.expired(referenceDate: referenceDate) + } catch { + return true + } + } + try expiredFiles.forEach { url in + try removeFile(at: url) + } + return expiredFiles + } + + /// Removes all size exceeded values from this storage. + /// - Throws: A file manager error during removing the file. + /// - Returns: The URLs for removed files. + /// + /// - Note: This method checks `config.sizeLimit` and remove cached files in an LRU (Least Recently Used) way. + func removeSizeExceededValues() throws -> [URL] { + + if config.sizeLimit == 0 { return [] } // Back compatible. 0 means no limit. + + var size = try totalSize() + if size < config.sizeLimit { return [] } + + let propertyKeys: [URLResourceKey] = [ + .isDirectoryKey, + .creationDateKey, + .fileSizeKey + ] + let keys = Set(propertyKeys) + + let urls = try allFileURLs(for: propertyKeys) + var pendings: [FileMeta] = urls.compactMap { fileURL in + guard let meta = try? FileMeta(fileURL: fileURL, resourceKeys: keys) else { + return nil + } + return meta + } + // Sort by last access date. Most recent file first. + pendings.sort(by: FileMeta.lastAccessDate) + + var removed: [URL] = [] + let target = config.sizeLimit / 2 + while size > target, let meta = pendings.popLast() { + size -= UInt(meta.fileSize) + try removeFile(at: meta.url) + removed.append(meta.url) + } + return removed + } + + /// Gets the total file size of the folder in bytes. + public func totalSize() throws -> UInt { + let propertyKeys: [URLResourceKey] = [.fileSizeKey] + let urls = try allFileURLs(for: propertyKeys) + let keys = Set(propertyKeys) + let totalSize: UInt = urls.reduce(0) { size, fileURL in + do { + let meta = try FileMeta(fileURL: fileURL, resourceKeys: keys) + return size + UInt(meta.fileSize) + } catch { + return size + } + } + return totalSize + } + } +} + +extension DiskStorage { + /// Represents the config used in a `DiskStorage`. + public struct Config { + + /// The file size limit on disk of the storage in bytes. 0 means no limit. + public var sizeLimit: UInt + + /// The `StorageExpiration` used in this disk storage. Default is `.days(7)`, + /// means that the disk cache would expire in one week. + public var expiration: StorageExpiration = .days(7) + + /// The preferred extension of cache item. It will be appended to the file name as its extension. + /// Default is `nil`, means that the cache file does not contain a file extension. + public var pathExtension: String? = nil + + /// Default is `true`, means that the cache file name will be hashed before storing. + public var usesHashedFileName = true + + /// Default is `false` + /// If set to `true`, image extension will be extracted from original file name and append to + /// the hased file name and used as the cache key on disk. + public var autoExtAfterHashedFileName = false + + /// Closure that takes in initial directory path and generates + /// the final disk cache path. You can use it to fully customize your cache path. + public var cachePathBlock: ((_ directory: URL, _ cacheName: String) -> URL)! = { + (directory, cacheName) in + return directory.appendingPathComponent(cacheName, isDirectory: true) + } + + let name: String + let fileManager: FileManager + let directory: URL? + + /// Creates a config value based on given parameters. + /// + /// - Parameters: + /// - name: The name of cache. It is used as a part of storage folder. It is used to identify the disk + /// storage. Two storages with the same `name` would share the same folder in disk, and it should + /// be prevented. + /// - sizeLimit: The size limit in bytes for all existing files in the disk storage. + /// - fileManager: The `FileManager` used to manipulate files on disk. Default is `FileManager.default`. + /// - directory: The URL where the disk storage should live. The storage will use this as the root folder, + /// and append a path which is constructed by input `name`. Default is `nil`, indicates that + /// the cache directory under user domain mask will be used. + public init( + name: String, + sizeLimit: UInt, + fileManager: FileManager = .default, + directory: URL? = nil) + { + self.name = name + self.fileManager = fileManager + self.directory = directory + self.sizeLimit = sizeLimit + } + } +} + +extension DiskStorage { + struct FileMeta { + + let url: URL + + let lastAccessDate: Date? + let estimatedExpirationDate: Date? + let isDirectory: Bool + let fileSize: Int + + static func lastAccessDate(lhs: FileMeta, rhs: FileMeta) -> Bool { + return lhs.lastAccessDate ?? .distantPast > rhs.lastAccessDate ?? .distantPast + } + + init(fileURL: URL, resourceKeys: Set) throws { + let meta = try fileURL.resourceValues(forKeys: resourceKeys) + self.init( + fileURL: fileURL, + lastAccessDate: meta.creationDate, + estimatedExpirationDate: meta.contentModificationDate, + isDirectory: meta.isDirectory ?? false, + fileSize: meta.fileSize ?? 0) + } + + init( + fileURL: URL, + lastAccessDate: Date?, + estimatedExpirationDate: Date?, + isDirectory: Bool, + fileSize: Int) + { + self.url = fileURL + self.lastAccessDate = lastAccessDate + self.estimatedExpirationDate = estimatedExpirationDate + self.isDirectory = isDirectory + self.fileSize = fileSize + } + + func expired(referenceDate: Date) -> Bool { + return estimatedExpirationDate?.isPast(referenceDate: referenceDate) ?? true + } + + func extendExpiration(with fileManager: FileManager, extendingExpiration: ExpirationExtending) { + guard let lastAccessDate = lastAccessDate, + let lastEstimatedExpiration = estimatedExpirationDate else + { + return + } + + let attributes: [FileAttributeKey : Any] + + switch extendingExpiration { + case .none: + // not extending expiration time here + return + case .cacheTime: + let originalExpiration: StorageExpiration = + .seconds(lastEstimatedExpiration.timeIntervalSince(lastAccessDate)) + attributes = [ + .creationDate: Date().fileAttributeDate, + .modificationDate: originalExpiration.estimatedExpirationSinceNow.fileAttributeDate + ] + case .expirationTime(let expirationTime): + attributes = [ + .creationDate: Date().fileAttributeDate, + .modificationDate: expirationTime.estimatedExpirationSinceNow.fileAttributeDate + ] + } + + try? fileManager.setAttributes(attributes, ofItemAtPath: url.path) + } + } +} + +extension DiskStorage { + struct Creation { + let directoryURL: URL + let cacheName: String + + init(_ config: Config) { + let url: URL + if let directory = config.directory { + url = directory + } else { + url = config.fileManager.urls(for: .cachesDirectory, in: .userDomainMask)[0] + } + + cacheName = "com.onevcat.Kingfisher.ImageCache.\(config.name)" + directoryURL = config.cachePathBlock(url, cacheName) + } + } +} + +fileprivate extension Error { + var isFolderMissing: Bool { + let nsError = self as NSError + guard nsError.domain == NSCocoaErrorDomain, nsError.code == 4 else { + return false + } + guard let underlyingError = nsError.userInfo[NSUnderlyingErrorKey] as? NSError else { + return false + } + guard underlyingError.domain == NSPOSIXErrorDomain, underlyingError.code == 2 else { + return false + } + return true + } +} diff --git a/Pods/Kingfisher/Sources/Cache/FormatIndicatedCacheSerializer.swift b/Pods/Kingfisher/Sources/Cache/FormatIndicatedCacheSerializer.swift new file mode 100644 index 0000000..aebc9c8 --- /dev/null +++ b/Pods/Kingfisher/Sources/Cache/FormatIndicatedCacheSerializer.swift @@ -0,0 +1,123 @@ +// +// RequestModifier.swift +// Kingfisher +// +// Created by Junyu Kuang on 5/28/17. +// +// Copyright (c) 2019 Wei Wang +// +// Permission is hereby granted, free of charge, to any person obtaining a copy +// of this software and associated documentation files (the "Software"), to deal +// in the Software without restriction, including without limitation the rights +// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +// copies of the Software, and to permit persons to whom the Software is +// furnished to do so, subject to the following conditions: +// +// The above copyright notice and this permission notice shall be included in +// all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN +// THE SOFTWARE. + +import Foundation +import CoreGraphics +#if os(macOS) +import AppKit +#else +import UIKit +#endif + +/// `FormatIndicatedCacheSerializer` lets you indicate an image format for serialized caches. +/// +/// It could serialize and deserialize PNG, JPEG and GIF images. For +/// image other than these formats, a normalized `pngRepresentation` will be used. +/// +/// Example: +/// ```` +/// let profileImageSize = CGSize(width: 44, height: 44) +/// +/// // A round corner image. +/// let imageProcessor = RoundCornerImageProcessor( +/// cornerRadius: profileImageSize.width / 2, targetSize: profileImageSize) +/// +/// let optionsInfo: KingfisherOptionsInfo = [ +/// .cacheSerializer(FormatIndicatedCacheSerializer.png), +/// .processor(imageProcessor)] +/// +/// A URL pointing to a JPEG image. +/// let url = URL(string: "https://example.com/image.jpg")! +/// +/// // Image will be always cached as PNG format to preserve alpha channel for round rectangle. +/// // So when you load it from cache again later, it will be still round cornered. +/// // Otherwise, the corner part would be filled by white color (since JPEG does not contain an alpha channel). +/// imageView.kf.setImage(with: url, options: optionsInfo) +/// ```` +public struct FormatIndicatedCacheSerializer: CacheSerializer { + + /// A `FormatIndicatedCacheSerializer` which converts image from and to PNG format. If the image cannot be + /// represented by PNG format, it will fallback to its real format which is determined by `original` data. + public static let png = FormatIndicatedCacheSerializer(imageFormat: .PNG, jpegCompressionQuality: nil) + + /// A `FormatIndicatedCacheSerializer` which converts image from and to JPEG format. If the image cannot be + /// represented by JPEG format, it will fallback to its real format which is determined by `original` data. + /// The compression quality is 1.0 when using this serializer. If you need to set a customized compression quality, + /// use `jpeg(compressionQuality:)`. + public static let jpeg = FormatIndicatedCacheSerializer(imageFormat: .JPEG, jpegCompressionQuality: 1.0) + + /// A `FormatIndicatedCacheSerializer` which converts image from and to JPEG format with a settable compression + /// quality. If the image cannot be represented by JPEG format, it will fallback to its real format which is + /// determined by `original` data. + /// - Parameter compressionQuality: The compression quality when converting image to JPEG data. + public static func jpeg(compressionQuality: CGFloat) -> FormatIndicatedCacheSerializer { + return FormatIndicatedCacheSerializer(imageFormat: .JPEG, jpegCompressionQuality: compressionQuality) + } + + /// A `FormatIndicatedCacheSerializer` which converts image from and to GIF format. If the image cannot be + /// represented by GIF format, it will fallback to its real format which is determined by `original` data. + public static let gif = FormatIndicatedCacheSerializer(imageFormat: .GIF, jpegCompressionQuality: nil) + + /// The indicated image format. + private let imageFormat: ImageFormat + + /// The compression quality used for loss image format (like JPEG). + private let jpegCompressionQuality: CGFloat? + + /// Creates data which represents the given `image` under a format. + public func data(with image: KFCrossPlatformImage, original: Data?) -> Data? { + + func imageData(withFormat imageFormat: ImageFormat) -> Data? { + return autoreleasepool { () -> Data? in + switch imageFormat { + case .PNG: return image.kf.pngRepresentation() + case .JPEG: return image.kf.jpegRepresentation(compressionQuality: jpegCompressionQuality ?? 1.0) + case .GIF: return image.kf.gifRepresentation() + case .unknown: return nil + } + } + } + + // generate data with indicated image format + if let data = imageData(withFormat: imageFormat) { + return data + } + + let originalFormat = original?.kf.imageFormat ?? .unknown + + // generate data with original image's format + if originalFormat != imageFormat, let data = imageData(withFormat: originalFormat) { + return data + } + + return original ?? image.kf.normalized.kf.pngRepresentation() + } + + /// Same implementation as `DefaultCacheSerializer`. + public func image(with data: Data, options: KingfisherParsedOptionsInfo) -> KFCrossPlatformImage? { + return KingfisherWrapper.image(data: data, options: options.imageCreatingOptions) + } +} diff --git a/Pods/Kingfisher/Sources/Cache/ImageCache.swift b/Pods/Kingfisher/Sources/Cache/ImageCache.swift new file mode 100644 index 0000000..508c79a --- /dev/null +++ b/Pods/Kingfisher/Sources/Cache/ImageCache.swift @@ -0,0 +1,882 @@ +// +// ImageCache.swift +// Kingfisher +// +// Created by Wei Wang on 15/4/6. +// +// Copyright (c) 2019 Wei Wang +// +// Permission is hereby granted, free of charge, to any person obtaining a copy +// of this software and associated documentation files (the "Software"), to deal +// in the Software without restriction, including without limitation the rights +// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +// copies of the Software, and to permit persons to whom the Software is +// furnished to do so, subject to the following conditions: +// +// The above copyright notice and this permission notice shall be included in +// all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN +// THE SOFTWARE. + +#if os(macOS) +import AppKit +#else +import UIKit +#endif + +extension Notification.Name { + /// This notification will be sent when the disk cache got cleaned either there are cached files expired or the + /// total size exceeding the max allowed size. The manually invoking of `clearDiskCache` method will not trigger + /// this notification. + /// + /// The `object` of this notification is the `ImageCache` object which sends the notification. + /// A list of removed hashes (files) could be retrieved by accessing the array under + /// `KingfisherDiskCacheCleanedHashKey` key in `userInfo` of the notification object you received. + /// By checking the array, you could know the hash codes of files are removed. + public static let KingfisherDidCleanDiskCache = + Notification.Name("com.onevcat.Kingfisher.KingfisherDidCleanDiskCache") +} + +/// Key for array of cleaned hashes in `userInfo` of `KingfisherDidCleanDiskCacheNotification`. +public let KingfisherDiskCacheCleanedHashKey = "com.onevcat.Kingfisher.cleanedHash" + +/// Cache type of a cached image. +/// - none: The image is not cached yet when retrieving it. +/// - memory: The image is cached in memory. +/// - disk: The image is cached in disk. +public enum CacheType { + /// The image is not cached yet when retrieving it. + case none + /// The image is cached in memory. + case memory + /// The image is cached in disk. + case disk + + /// Whether the cache type represents the image is already cached or not. + public var cached: Bool { + switch self { + case .memory, .disk: return true + case .none: return false + } + } +} + +/// Represents the caching operation result. +public struct CacheStoreResult { + + /// The cache result for memory cache. Caching an image to memory will never fail. + public let memoryCacheResult: Result<(), Never> + + /// The cache result for disk cache. If an error happens during caching operation, + /// you can get it from `.failure` case of this `diskCacheResult`. + public let diskCacheResult: Result<(), KingfisherError> +} + +extension KFCrossPlatformImage: CacheCostCalculable { + /// Cost of an image + public var cacheCost: Int { return kf.cost } +} + +extension Data: DataTransformable { + public func toData() throws -> Data { + return self + } + + public static func fromData(_ data: Data) throws -> Data { + return data + } + + public static let empty = Data() +} + + +/// Represents the getting image operation from the cache. +/// +/// - disk: The image can be retrieved from disk cache. +/// - memory: The image can be retrieved memory cache. +/// - none: The image does not exist in the cache. +public enum ImageCacheResult { + + /// The image can be retrieved from disk cache. + case disk(KFCrossPlatformImage) + + /// The image can be retrieved memory cache. + case memory(KFCrossPlatformImage) + + /// The image does not exist in the cache. + case none + + /// Extracts the image from cache result. It returns the associated `Image` value for + /// `.disk` and `.memory` case. For `.none` case, `nil` is returned. + public var image: KFCrossPlatformImage? { + switch self { + case .disk(let image): return image + case .memory(let image): return image + case .none: return nil + } + } + + /// Returns the corresponding `CacheType` value based on the result type of `self`. + public var cacheType: CacheType { + switch self { + case .disk: return .disk + case .memory: return .memory + case .none: return .none + } + } +} + +/// Represents a hybrid caching system which is composed by a `MemoryStorage.Backend` and a `DiskStorage.Backend`. +/// `ImageCache` is a high level abstract for storing an image as well as its data to memory and disk, and +/// retrieving them back. +/// +/// While a default image cache object will be used if you prefer the extension methods of Kingfisher, you can create +/// your own cache object and configure its storages as your need. This class also provide an interface for you to set +/// the memory and disk storage config. +open class ImageCache { + + // MARK: Singleton + /// The default `ImageCache` object. Kingfisher will use this cache for its related methods if there is no + /// other cache specified. The `name` of this default cache is "default", and you should not use this name + /// for any of your customize cache. + public static let `default` = ImageCache(name: "default") + + + // MARK: Public Properties + /// The `MemoryStorage.Backend` object used in this cache. This storage holds loaded images in memory with a + /// reasonable expire duration and a maximum memory usage. To modify the configuration of a storage, just set + /// the storage `config` and its properties. + public let memoryStorage: MemoryStorage.Backend + + /// The `DiskStorage.Backend` object used in this cache. This storage stores loaded images in disk with a + /// reasonable expire duration and a maximum disk usage. To modify the configuration of a storage, just set + /// the storage `config` and its properties. + public let diskStorage: DiskStorage.Backend + + private let ioQueue: DispatchQueue + + /// Closure that defines the disk cache path from a given path and cacheName. + public typealias DiskCachePathClosure = (URL, String) -> URL + + // MARK: Initializers + + /// Creates an `ImageCache` from a customized `MemoryStorage` and `DiskStorage`. + /// + /// - Parameters: + /// - memoryStorage: The `MemoryStorage.Backend` object to use in the image cache. + /// - diskStorage: The `DiskStorage.Backend` object to use in the image cache. + public init( + memoryStorage: MemoryStorage.Backend, + diskStorage: DiskStorage.Backend) + { + self.memoryStorage = memoryStorage + self.diskStorage = diskStorage + let ioQueueName = "com.onevcat.Kingfisher.ImageCache.ioQueue.\(UUID().uuidString)" + ioQueue = DispatchQueue(label: ioQueueName) + + let notifications: [(Notification.Name, Selector)] + #if !os(macOS) && !os(watchOS) + notifications = [ + (UIApplication.didReceiveMemoryWarningNotification, #selector(clearMemoryCache)), + (UIApplication.willTerminateNotification, #selector(cleanExpiredDiskCache)), + (UIApplication.didEnterBackgroundNotification, #selector(backgroundCleanExpiredDiskCache)) + ] + #elseif os(macOS) + notifications = [ + (NSApplication.willResignActiveNotification, #selector(cleanExpiredDiskCache)), + ] + #else + notifications = [] + #endif + notifications.forEach { + NotificationCenter.default.addObserver(self, selector: $0.1, name: $0.0, object: nil) + } + } + + /// Creates an `ImageCache` with a given `name`. Both `MemoryStorage` and `DiskStorage` will be created + /// with a default config based on the `name`. + /// + /// - Parameter name: The name of cache object. It is used to setup disk cache directories and IO queue. + /// You should not use the same `name` for different caches, otherwise, the disk storage would + /// be conflicting to each other. The `name` should not be an empty string. + public convenience init(name: String) { + self.init(noThrowName: name, cacheDirectoryURL: nil, diskCachePathClosure: nil) + } + + /// Creates an `ImageCache` with a given `name`, cache directory `path` + /// and a closure to modify the cache directory. + /// + /// - Parameters: + /// - name: The name of cache object. It is used to setup disk cache directories and IO queue. + /// You should not use the same `name` for different caches, otherwise, the disk storage would + /// be conflicting to each other. + /// - cacheDirectoryURL: Location of cache directory URL on disk. It will be internally pass to the + /// initializer of `DiskStorage` as the disk cache directory. If `nil`, the cache + /// directory under user domain mask will be used. + /// - diskCachePathClosure: Closure that takes in an optional initial path string and generates + /// the final disk cache path. You could use it to fully customize your cache path. + /// - Throws: An error that happens during image cache creating, such as unable to create a directory at the given + /// path. + public convenience init( + name: String, + cacheDirectoryURL: URL?, + diskCachePathClosure: DiskCachePathClosure? = nil + ) throws + { + if name.isEmpty { + fatalError("[Kingfisher] You should specify a name for the cache. A cache with empty name is not permitted.") + } + + let memoryStorage = ImageCache.createMemoryStorage() + + let config = ImageCache.createConfig( + name: name, cacheDirectoryURL: cacheDirectoryURL, diskCachePathClosure: diskCachePathClosure + ) + let diskStorage = try DiskStorage.Backend(config: config) + self.init(memoryStorage: memoryStorage, diskStorage: diskStorage) + } + + convenience init( + noThrowName name: String, + cacheDirectoryURL: URL?, + diskCachePathClosure: DiskCachePathClosure? + ) + { + if name.isEmpty { + fatalError("[Kingfisher] You should specify a name for the cache. A cache with empty name is not permitted.") + } + + let memoryStorage = ImageCache.createMemoryStorage() + + let config = ImageCache.createConfig( + name: name, cacheDirectoryURL: cacheDirectoryURL, diskCachePathClosure: diskCachePathClosure + ) + let diskStorage = DiskStorage.Backend(noThrowConfig: config, creatingDirectory: true) + self.init(memoryStorage: memoryStorage, diskStorage: diskStorage) + } + + private static func createMemoryStorage() -> MemoryStorage.Backend { + let totalMemory = ProcessInfo.processInfo.physicalMemory + let costLimit = totalMemory / 4 + let memoryStorage = MemoryStorage.Backend(config: + .init(totalCostLimit: (costLimit > Int.max) ? Int.max : Int(costLimit))) + return memoryStorage + } + + private static func createConfig( + name: String, + cacheDirectoryURL: URL?, + diskCachePathClosure: DiskCachePathClosure? = nil + ) -> DiskStorage.Config + { + var diskConfig = DiskStorage.Config( + name: name, + sizeLimit: 0, + directory: cacheDirectoryURL + ) + if let closure = diskCachePathClosure { + diskConfig.cachePathBlock = closure + } + return diskConfig + } + + deinit { + NotificationCenter.default.removeObserver(self) + } + + // MARK: Storing Images + + open func store(_ image: KFCrossPlatformImage, + original: Data? = nil, + forKey key: String, + options: KingfisherParsedOptionsInfo, + toDisk: Bool = true, + completionHandler: ((CacheStoreResult) -> Void)? = nil) + { + let identifier = options.processor.identifier + let callbackQueue = options.callbackQueue + + let computedKey = key.computedKey(with: identifier) + // Memory storage should not throw. + memoryStorage.storeNoThrow(value: image, forKey: computedKey, expiration: options.memoryCacheExpiration) + + guard toDisk else { + if let completionHandler = completionHandler { + let result = CacheStoreResult(memoryCacheResult: .success(()), diskCacheResult: .success(())) + callbackQueue.execute { completionHandler(result) } + } + return + } + + ioQueue.async { + let serializer = options.cacheSerializer + if let data = serializer.data(with: image, original: original) { + self.syncStoreToDisk( + data, + forKey: key, + processorIdentifier: identifier, + callbackQueue: callbackQueue, + expiration: options.diskCacheExpiration, + writeOptions: options.diskStoreWriteOptions, + completionHandler: completionHandler) + } else { + guard let completionHandler = completionHandler else { return } + + let diskError = KingfisherError.cacheError( + reason: .cannotSerializeImage(image: image, original: original, serializer: serializer)) + let result = CacheStoreResult( + memoryCacheResult: .success(()), + diskCacheResult: .failure(diskError)) + callbackQueue.execute { completionHandler(result) } + } + } + } + + /// Stores an image to the cache. + /// + /// - Parameters: + /// - image: The image to be stored. + /// - original: The original data of the image. This value will be forwarded to the provided `serializer` for + /// further use. By default, Kingfisher uses a `DefaultCacheSerializer` to serialize the image to + /// data for caching in disk, it checks the image format based on `original` data to determine in + /// which image format should be used. For other types of `serializer`, it depends on their + /// implementation detail on how to use this original data. + /// - key: The key used for caching the image. + /// - identifier: The identifier of processor being used for caching. If you are using a processor for the + /// image, pass the identifier of processor to this parameter. + /// - serializer: The `CacheSerializer` + /// - toDisk: Whether this image should be cached to disk or not. If `false`, the image is only cached in memory. + /// Otherwise, it is cached in both memory storage and disk storage. Default is `true`. + /// - callbackQueue: The callback queue on which `completionHandler` is invoked. Default is `.untouch`. For case + /// that `toDisk` is `false`, a `.untouch` queue means `callbackQueue` will be invoked from the + /// caller queue of this method. If `toDisk` is `true`, the `completionHandler` will be called + /// from an internal file IO queue. To change this behavior, specify another `CallbackQueue` + /// value. + /// - completionHandler: A closure which is invoked when the cache operation finishes. + open func store(_ image: KFCrossPlatformImage, + original: Data? = nil, + forKey key: String, + processorIdentifier identifier: String = "", + cacheSerializer serializer: CacheSerializer = DefaultCacheSerializer.default, + toDisk: Bool = true, + callbackQueue: CallbackQueue = .untouch, + completionHandler: ((CacheStoreResult) -> Void)? = nil) + { + struct TempProcessor: ImageProcessor { + let identifier: String + func process(item: ImageProcessItem, options: KingfisherParsedOptionsInfo) -> KFCrossPlatformImage? { + return nil + } + } + + let options = KingfisherParsedOptionsInfo([ + .processor(TempProcessor(identifier: identifier)), + .cacheSerializer(serializer), + .callbackQueue(callbackQueue) + ]) + store(image, original: original, forKey: key, options: options, + toDisk: toDisk, completionHandler: completionHandler) + } + + open func storeToDisk( + _ data: Data, + forKey key: String, + processorIdentifier identifier: String = "", + expiration: StorageExpiration? = nil, + callbackQueue: CallbackQueue = .untouch, + completionHandler: ((CacheStoreResult) -> Void)? = nil) + { + ioQueue.async { + self.syncStoreToDisk( + data, + forKey: key, + processorIdentifier: identifier, + callbackQueue: callbackQueue, + expiration: expiration, + completionHandler: completionHandler) + } + } + + private func syncStoreToDisk( + _ data: Data, + forKey key: String, + processorIdentifier identifier: String = "", + callbackQueue: CallbackQueue = .untouch, + expiration: StorageExpiration? = nil, + writeOptions: Data.WritingOptions = [], + completionHandler: ((CacheStoreResult) -> Void)? = nil) + { + let computedKey = key.computedKey(with: identifier) + let result: CacheStoreResult + do { + try self.diskStorage.store(value: data, forKey: computedKey, expiration: expiration, writeOptions: writeOptions) + result = CacheStoreResult(memoryCacheResult: .success(()), diskCacheResult: .success(())) + } catch { + let diskError: KingfisherError + if let error = error as? KingfisherError { + diskError = error + } else { + diskError = .cacheError(reason: .cannotConvertToData(object: data, error: error)) + } + + result = CacheStoreResult( + memoryCacheResult: .success(()), + diskCacheResult: .failure(diskError) + ) + } + if let completionHandler = completionHandler { + callbackQueue.execute { completionHandler(result) } + } + } + + // MARK: Removing Images + + /// Removes the image for the given key from the cache. + /// + /// - Parameters: + /// - key: The key used for caching the image. + /// - identifier: The identifier of processor being used for caching. If you are using a processor for the + /// image, pass the identifier of processor to this parameter. + /// - fromMemory: Whether this image should be removed from memory storage or not. + /// If `false`, the image won't be removed from the memory storage. Default is `true`. + /// - fromDisk: Whether this image should be removed from disk storage or not. + /// If `false`, the image won't be removed from the disk storage. Default is `true`. + /// - callbackQueue: The callback queue on which `completionHandler` is invoked. Default is `.untouch`. + /// - completionHandler: A closure which is invoked when the cache removing operation finishes. + open func removeImage(forKey key: String, + processorIdentifier identifier: String = "", + fromMemory: Bool = true, + fromDisk: Bool = true, + callbackQueue: CallbackQueue = .untouch, + completionHandler: (() -> Void)? = nil) + { + let computedKey = key.computedKey(with: identifier) + + if fromMemory { + memoryStorage.remove(forKey: computedKey) + } + + if fromDisk { + ioQueue.async{ + try? self.diskStorage.remove(forKey: computedKey) + if let completionHandler = completionHandler { + callbackQueue.execute { completionHandler() } + } + } + } else { + if let completionHandler = completionHandler { + callbackQueue.execute { completionHandler() } + } + } + } + + // MARK: Getting Images + + /// Gets an image for a given key from the cache, either from memory storage or disk storage. + /// + /// - Parameters: + /// - key: The key used for caching the image. + /// - options: The `KingfisherParsedOptionsInfo` options setting used for retrieving the image. + /// - callbackQueue: The callback queue on which `completionHandler` is invoked. Default is `.mainCurrentOrAsync`. + /// - completionHandler: A closure which is invoked when the image getting operation finishes. If the + /// image retrieving operation finishes without problem, an `ImageCacheResult` value + /// will be sent to this closure as result. Otherwise, a `KingfisherError` result + /// with detail failing reason will be sent. + open func retrieveImage( + forKey key: String, + options: KingfisherParsedOptionsInfo, + callbackQueue: CallbackQueue = .mainCurrentOrAsync, + completionHandler: ((Result) -> Void)?) + { + // No completion handler. No need to start working and early return. + guard let completionHandler = completionHandler else { return } + + // Try to check the image from memory cache first. + if let image = retrieveImageInMemoryCache(forKey: key, options: options) { + callbackQueue.execute { completionHandler(.success(.memory(image))) } + } else if options.fromMemoryCacheOrRefresh { + callbackQueue.execute { completionHandler(.success(.none)) } + } else { + + // Begin to disk search. + self.retrieveImageInDiskCache(forKey: key, options: options, callbackQueue: callbackQueue) { + result in + switch result { + case .success(let image): + + guard let image = image else { + // No image found in disk storage. + callbackQueue.execute { completionHandler(.success(.none)) } + return + } + + // Cache the disk image to memory. + // We are passing `false` to `toDisk`, the memory cache does not change + // callback queue, we can call `completionHandler` without another dispatch. + var cacheOptions = options + cacheOptions.callbackQueue = .untouch + self.store( + image, + forKey: key, + options: cacheOptions, + toDisk: false) + { + _ in + callbackQueue.execute { completionHandler(.success(.disk(image))) } + } + case .failure(let error): + callbackQueue.execute { completionHandler(.failure(error)) } + } + } + } + } + + /// Gets an image for a given key from the cache, either from memory storage or disk storage. + /// + /// - Parameters: + /// - key: The key used for caching the image. + /// - options: The `KingfisherOptionsInfo` options setting used for retrieving the image. + /// - callbackQueue: The callback queue on which `completionHandler` is invoked. Default is `.mainCurrentOrAsync`. + /// - completionHandler: A closure which is invoked when the image getting operation finishes. If the + /// image retrieving operation finishes without problem, an `ImageCacheResult` value + /// will be sent to this closure as result. Otherwise, a `KingfisherError` result + /// with detail failing reason will be sent. + /// + /// Note: This method is marked as `open` for only compatible purpose. Do not overide this method. Instead, override + /// the version receives `KingfisherParsedOptionsInfo` instead. + open func retrieveImage(forKey key: String, + options: KingfisherOptionsInfo? = nil, + callbackQueue: CallbackQueue = .mainCurrentOrAsync, + completionHandler: ((Result) -> Void)?) + { + retrieveImage( + forKey: key, + options: KingfisherParsedOptionsInfo(options), + callbackQueue: callbackQueue, + completionHandler: completionHandler) + } + + /// Gets an image for a given key from the memory storage. + /// + /// - Parameters: + /// - key: The key used for caching the image. + /// - options: The `KingfisherParsedOptionsInfo` options setting used for retrieving the image. + /// - Returns: The image stored in memory cache, if exists and valid. Otherwise, if the image does not exist or + /// has already expired, `nil` is returned. + open func retrieveImageInMemoryCache( + forKey key: String, + options: KingfisherParsedOptionsInfo) -> KFCrossPlatformImage? + { + let computedKey = key.computedKey(with: options.processor.identifier) + return memoryStorage.value(forKey: computedKey, extendingExpiration: options.memoryCacheAccessExtendingExpiration) + } + + /// Gets an image for a given key from the memory storage. + /// + /// - Parameters: + /// - key: The key used for caching the image. + /// - options: The `KingfisherOptionsInfo` options setting used for retrieving the image. + /// - Returns: The image stored in memory cache, if exists and valid. Otherwise, if the image does not exist or + /// has already expired, `nil` is returned. + /// + /// Note: This method is marked as `open` for only compatible purpose. Do not overide this method. Instead, override + /// the version receives `KingfisherParsedOptionsInfo` instead. + open func retrieveImageInMemoryCache( + forKey key: String, + options: KingfisherOptionsInfo? = nil) -> KFCrossPlatformImage? + { + return retrieveImageInMemoryCache(forKey: key, options: KingfisherParsedOptionsInfo(options)) + } + + func retrieveImageInDiskCache( + forKey key: String, + options: KingfisherParsedOptionsInfo, + callbackQueue: CallbackQueue = .untouch, + completionHandler: @escaping (Result) -> Void) + { + let computedKey = key.computedKey(with: options.processor.identifier) + let loadingQueue: CallbackQueue = options.loadDiskFileSynchronously ? .untouch : .dispatch(ioQueue) + loadingQueue.execute { + do { + var image: KFCrossPlatformImage? = nil + if let data = try self.diskStorage.value(forKey: computedKey, extendingExpiration: options.diskCacheAccessExtendingExpiration) { + image = options.cacheSerializer.image(with: data, options: options) + } + if options.backgroundDecode { + image = image?.kf.decoded(scale: options.scaleFactor) + } + callbackQueue.execute { completionHandler(.success(image)) } + } catch let error as KingfisherError { + callbackQueue.execute { completionHandler(.failure(error)) } + } catch { + assertionFailure("The internal thrown error should be a `KingfisherError`.") + } + } + } + + /// Gets an image for a given key from the disk storage. + /// + /// - Parameters: + /// - key: The key used for caching the image. + /// - options: The `KingfisherOptionsInfo` options setting used for retrieving the image. + /// - callbackQueue: The callback queue on which `completionHandler` is invoked. Default is `.untouch`. + /// - completionHandler: A closure which is invoked when the operation finishes. + open func retrieveImageInDiskCache( + forKey key: String, + options: KingfisherOptionsInfo? = nil, + callbackQueue: CallbackQueue = .untouch, + completionHandler: @escaping (Result) -> Void) + { + retrieveImageInDiskCache( + forKey: key, + options: KingfisherParsedOptionsInfo(options), + callbackQueue: callbackQueue, + completionHandler: completionHandler) + } + + // MARK: Cleaning + /// Clears the memory & disk storage of this cache. This is an async operation. + /// + /// - Parameter handler: A closure which is invoked when the cache clearing operation finishes. + /// This `handler` will be called from the main queue. + public func clearCache(completion handler: (() -> Void)? = nil) { + clearMemoryCache() + clearDiskCache(completion: handler) + } + + /// Clears the memory storage of this cache. + @objc public func clearMemoryCache() { + memoryStorage.removeAll() + } + + /// Clears the disk storage of this cache. This is an async operation. + /// + /// - Parameter handler: A closure which is invoked when the cache clearing operation finishes. + /// This `handler` will be called from the main queue. + open func clearDiskCache(completion handler: (() -> Void)? = nil) { + ioQueue.async { + do { + try self.diskStorage.removeAll() + } catch _ { } + if let handler = handler { + DispatchQueue.main.async { handler() } + } + } + } + + /// Clears the expired images from memory & disk storage. This is an async operation. + open func cleanExpiredCache(completion handler: (() -> Void)? = nil) { + cleanExpiredMemoryCache() + cleanExpiredDiskCache(completion: handler) + } + + /// Clears the expired images from disk storage. + open func cleanExpiredMemoryCache() { + memoryStorage.removeExpired() + } + + /// Clears the expired images from disk storage. This is an async operation. + @objc func cleanExpiredDiskCache() { + cleanExpiredDiskCache(completion: nil) + } + + /// Clears the expired images from disk storage. This is an async operation. + /// + /// - Parameter handler: A closure which is invoked when the cache clearing operation finishes. + /// This `handler` will be called from the main queue. + open func cleanExpiredDiskCache(completion handler: (() -> Void)? = nil) { + ioQueue.async { + do { + var removed: [URL] = [] + let removedExpired = try self.diskStorage.removeExpiredValues() + removed.append(contentsOf: removedExpired) + + let removedSizeExceeded = try self.diskStorage.removeSizeExceededValues() + removed.append(contentsOf: removedSizeExceeded) + + if !removed.isEmpty { + DispatchQueue.main.async { + let cleanedHashes = removed.map { $0.lastPathComponent } + NotificationCenter.default.post( + name: .KingfisherDidCleanDiskCache, + object: self, + userInfo: [KingfisherDiskCacheCleanedHashKey: cleanedHashes]) + } + } + + if let handler = handler { + DispatchQueue.main.async { handler() } + } + } catch {} + } + } + +#if !os(macOS) && !os(watchOS) + /// Clears the expired images from disk storage when app is in background. This is an async operation. + /// In most cases, you should not call this method explicitly. + /// It will be called automatically when `UIApplicationDidEnterBackgroundNotification` received. + @objc public func backgroundCleanExpiredDiskCache() { + // if 'sharedApplication()' is unavailable, then return + guard let sharedApplication = KingfisherWrapper.shared else { return } + + func endBackgroundTask(_ task: inout UIBackgroundTaskIdentifier) { + sharedApplication.endBackgroundTask(task) + task = UIBackgroundTaskIdentifier.invalid + } + + var backgroundTask: UIBackgroundTaskIdentifier! + backgroundTask = sharedApplication.beginBackgroundTask { + endBackgroundTask(&backgroundTask!) + } + + cleanExpiredDiskCache { + endBackgroundTask(&backgroundTask!) + } + } +#endif + + // MARK: Image Cache State + + /// Returns the cache type for a given `key` and `identifier` combination. + /// This method is used for checking whether an image is cached in current cache. + /// It also provides information on which kind of cache can it be found in the return value. + /// + /// - Parameters: + /// - key: The key used for caching the image. + /// - identifier: Processor identifier which used for this image. Default is the `identifier` of + /// `DefaultImageProcessor.default`. + /// - Returns: A `CacheType` instance which indicates the cache status. + /// `.none` means the image is not in cache or it is already expired. + open func imageCachedType( + forKey key: String, + processorIdentifier identifier: String = DefaultImageProcessor.default.identifier) -> CacheType + { + let computedKey = key.computedKey(with: identifier) + if memoryStorage.isCached(forKey: computedKey) { return .memory } + if diskStorage.isCached(forKey: computedKey) { return .disk } + return .none + } + + /// Returns whether the file exists in cache for a given `key` and `identifier` combination. + /// + /// - Parameters: + /// - key: The key used for caching the image. + /// - identifier: Processor identifier which used for this image. Default is the `identifier` of + /// `DefaultImageProcessor.default`. + /// - Returns: A `Bool` which indicates whether a cache could match the given `key` and `identifier` combination. + /// + /// - Note: + /// The return value does not contain information about from which kind of storage the cache matches. + /// To get the information about cache type according `CacheType`, + /// use `imageCachedType(forKey:processorIdentifier:)` instead. + public func isCached( + forKey key: String, + processorIdentifier identifier: String = DefaultImageProcessor.default.identifier) -> Bool + { + return imageCachedType(forKey: key, processorIdentifier: identifier).cached + } + + /// Gets the hash used as cache file name for the key. + /// + /// - Parameters: + /// - key: The key used for caching the image. + /// - identifier: Processor identifier which used for this image. Default is the `identifier` of + /// `DefaultImageProcessor.default`. + /// - Returns: The hash which is used as the cache file name. + /// + /// - Note: + /// By default, for a given combination of `key` and `identifier`, `ImageCache` will use the value + /// returned by this method as the cache file name. You can use this value to check and match cache file + /// if you need. + open func hash( + forKey key: String, + processorIdentifier identifier: String = DefaultImageProcessor.default.identifier) -> String + { + let computedKey = key.computedKey(with: identifier) + return diskStorage.cacheFileName(forKey: computedKey) + } + + /// Calculates the size taken by the disk storage. + /// It is the total file size of all cached files in the `diskStorage` on disk in bytes. + /// + /// - Parameter handler: Called with the size calculating finishes. This closure is invoked from the main queue. + open func calculateDiskStorageSize(completion handler: @escaping ((Result) -> Void)) { + ioQueue.async { + do { + let size = try self.diskStorage.totalSize() + DispatchQueue.main.async { handler(.success(size)) } + } catch let error as KingfisherError { + DispatchQueue.main.async { handler(.failure(error)) } + } catch { + assertionFailure("The internal thrown error should be a `KingfisherError`.") + } + } + } + + #if swift(>=5.5) + #if canImport(_Concurrency) + @available(iOS 13.0, macOS 10.15, tvOS 13.0, watchOS 6.0, *) + open var diskStorageSize: UInt { + get async throws { + try await withCheckedThrowingContinuation { continuation in + calculateDiskStorageSize { result in + continuation.resume(with: result) + } + } + } + } + #endif + #endif + + /// Gets the cache path for the key. + /// It is useful for projects with web view or anyone that needs access to the local file path. + /// + /// i.e. Replacing the `` tag in your HTML. + /// + /// - Parameters: + /// - key: The key used for caching the image. + /// - identifier: Processor identifier which used for this image. Default is the `identifier` of + /// `DefaultImageProcessor.default`. + /// - Returns: The disk path of cached image under the given `key` and `identifier`. + /// + /// - Note: + /// This method does not guarantee there is an image already cached in the returned path. It just gives your + /// the path that the image should be, if it exists in disk storage. + /// + /// You could use `isCached(forKey:)` method to check whether the image is cached under that key in disk. + open func cachePath( + forKey key: String, + processorIdentifier identifier: String = DefaultImageProcessor.default.identifier) -> String + { + let computedKey = key.computedKey(with: identifier) + return diskStorage.cacheFileURL(forKey: computedKey).path + } +} + +#if !os(macOS) && !os(watchOS) +// MARK: - For App Extensions +extension UIApplication: KingfisherCompatible { } +extension KingfisherWrapper where Base: UIApplication { + public static var shared: UIApplication? { + let selector = NSSelectorFromString("sharedApplication") + guard Base.responds(to: selector) else { return nil } + return Base.perform(selector).takeUnretainedValue() as? UIApplication + } +} +#endif + +extension String { + func computedKey(with identifier: String) -> String { + if identifier.isEmpty { + return self + } else { + return appending("@\(identifier)") + } + } +} diff --git a/Pods/Kingfisher/Sources/Cache/MemoryStorage.swift b/Pods/Kingfisher/Sources/Cache/MemoryStorage.swift new file mode 100644 index 0000000..10d92b1 --- /dev/null +++ b/Pods/Kingfisher/Sources/Cache/MemoryStorage.swift @@ -0,0 +1,283 @@ +// +// MemoryStorage.swift +// Kingfisher +// +// Created by Wei Wang on 2018/10/15. +// +// Copyright (c) 2019 Wei Wang +// +// Permission is hereby granted, free of charge, to any person obtaining a copy +// of this software and associated documentation files (the "Software"), to deal +// in the Software without restriction, including without limitation the rights +// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +// copies of the Software, and to permit persons to whom the Software is +// furnished to do so, subject to the following conditions: +// +// The above copyright notice and this permission notice shall be included in +// all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN +// THE SOFTWARE. + +import Foundation + +/// Represents a set of conception related to storage which stores a certain type of value in memory. +/// This is a namespace for the memory storage types. A `Backend` with a certain `Config` will be used to describe the +/// storage. See these composed types for more information. +public enum MemoryStorage { + + /// Represents a storage which stores a certain type of value in memory. It provides fast access, + /// but limited storing size. The stored value type needs to conform to `CacheCostCalculable`, + /// and its `cacheCost` will be used to determine the cost of size for the cache item. + /// + /// You can config a `MemoryStorage.Backend` in its initializer by passing a `MemoryStorage.Config` value. + /// or modifying the `config` property after it being created. The backend of `MemoryStorage` has + /// upper limitation on cost size in memory and item count. All items in the storage has an expiration + /// date. When retrieved, if the target item is already expired, it will be recognized as it does not + /// exist in the storage. The `MemoryStorage` also contains a scheduled self clean task, to evict expired + /// items from memory. + public class Backend { + let storage = NSCache>() + + // Keys trackes the objects once inside the storage. For object removing triggered by user, the corresponding + // key would be also removed. However, for the object removing triggered by cache rule/policy of system, the + // key will be remained there until next `removeExpired` happens. + // + // Breaking the strict tracking could save additional locking behaviors. + // See https://github.com/onevcat/Kingfisher/issues/1233 + var keys = Set() + + private var cleanTimer: Timer? = nil + private let lock = NSLock() + + /// The config used in this storage. It is a value you can set and + /// use to config the storage in air. + public var config: Config { + didSet { + storage.totalCostLimit = config.totalCostLimit + storage.countLimit = config.countLimit + } + } + + /// Creates a `MemoryStorage` with a given `config`. + /// + /// - Parameter config: The config used to create the storage. It determines the max size limitation, + /// default expiration setting and more. + public init(config: Config) { + self.config = config + storage.totalCostLimit = config.totalCostLimit + storage.countLimit = config.countLimit + + cleanTimer = .scheduledTimer(withTimeInterval: config.cleanInterval, repeats: true) { [weak self] _ in + guard let self = self else { return } + self.removeExpired() + } + } + + /// Removes the expired values from the storage. + public func removeExpired() { + lock.lock() + defer { lock.unlock() } + for key in keys { + let nsKey = key as NSString + guard let object = storage.object(forKey: nsKey) else { + // This could happen if the object is moved by cache `totalCostLimit` or `countLimit` rule. + // We didn't remove the key yet until now, since we do not want to introduce additional lock. + // See https://github.com/onevcat/Kingfisher/issues/1233 + keys.remove(key) + continue + } + if object.isExpired { + storage.removeObject(forKey: nsKey) + keys.remove(key) + } + } + } + + /// Stores a value to the storage under the specified key and expiration policy. + /// - Parameters: + /// - value: The value to be stored. + /// - key: The key to which the `value` will be stored. + /// - expiration: The expiration policy used by this store action. + /// - Throws: No error will + public func store( + value: T, + forKey key: String, + expiration: StorageExpiration? = nil) + { + storeNoThrow(value: value, forKey: key, expiration: expiration) + } + + // The no throw version for storing value in cache. Kingfisher knows the detail so it + // could use this version to make syntax simpler internally. + func storeNoThrow( + value: T, + forKey key: String, + expiration: StorageExpiration? = nil) + { + lock.lock() + defer { lock.unlock() } + let expiration = expiration ?? config.expiration + // The expiration indicates that already expired, no need to store. + guard !expiration.isExpired else { return } + + let object: StorageObject + if config.keepWhenEnteringBackground { + object = BackgroundKeepingStorageObject(value, expiration: expiration) + } else { + object = StorageObject(value, expiration: expiration) + } + storage.setObject(object, forKey: key as NSString, cost: value.cacheCost) + keys.insert(key) + } + + /// Gets a value from the storage. + /// + /// - Parameters: + /// - key: The cache key of value. + /// - extendingExpiration: The expiration policy used by this getting action. + /// - Returns: The value under `key` if it is valid and found in the storage. Otherwise, `nil`. + public func value(forKey key: String, extendingExpiration: ExpirationExtending = .cacheTime) -> T? { + guard let object = storage.object(forKey: key as NSString) else { + return nil + } + if object.isExpired { + return nil + } + object.extendExpiration(extendingExpiration) + return object.value + } + + /// Whether there is valid cached data under a given key. + /// - Parameter key: The cache key of value. + /// - Returns: If there is valid data under the key, `true`. Otherwise, `false`. + public func isCached(forKey key: String) -> Bool { + guard let _ = value(forKey: key, extendingExpiration: .none) else { + return false + } + return true + } + + /// Removes a value from a specified key. + /// - Parameter key: The cache key of value. + public func remove(forKey key: String) { + lock.lock() + defer { lock.unlock() } + storage.removeObject(forKey: key as NSString) + keys.remove(key) + } + + /// Removes all values in this storage. + public func removeAll() { + lock.lock() + defer { lock.unlock() } + storage.removeAllObjects() + keys.removeAll() + } + } +} + +extension MemoryStorage { + /// Represents the config used in a `MemoryStorage`. + public struct Config { + + /// Total cost limit of the storage in bytes. + public var totalCostLimit: Int + + /// The item count limit of the memory storage. + public var countLimit: Int = .max + + /// The `StorageExpiration` used in this memory storage. Default is `.seconds(300)`, + /// means that the memory cache would expire in 5 minutes. + public var expiration: StorageExpiration = .seconds(300) + + /// The time interval between the storage do clean work for swiping expired items. + public var cleanInterval: TimeInterval + + /// Whether the newly added items to memory cache should be purged when the app goes to background. + /// + /// By default, the cached items in memory will be purged as soon as the app goes to background to ensure + /// least memory footprint. Enabling this would prevent this behavior and keep the items alive in cache even + /// when your app is not in foreground anymore. + /// + /// Default is `false`. After setting `true`, only the newly added cache objects are affected. Existing + /// objects which are already in the cache while this value was `false` will be still be purged when entering + /// background. + public var keepWhenEnteringBackground: Bool = false + + /// Creates a config from a given `totalCostLimit` value. + /// + /// - Parameters: + /// - totalCostLimit: Total cost limit of the storage in bytes. + /// - cleanInterval: The time interval between the storage do clean work for swiping expired items. + /// Default is 120, means the auto eviction happens once per two minutes. + /// + /// - Note: + /// Other members of `MemoryStorage.Config` will use their default values when created. + public init(totalCostLimit: Int, cleanInterval: TimeInterval = 120) { + self.totalCostLimit = totalCostLimit + self.cleanInterval = cleanInterval + } + } +} + +extension MemoryStorage { + + class BackgroundKeepingStorageObject: StorageObject, NSDiscardableContent { + var accessing = true + func beginContentAccess() -> Bool { + if value != nil { + accessing = true + } else { + accessing = false + } + return accessing + } + + func endContentAccess() { + accessing = false + } + + func discardContentIfPossible() { + value = nil + } + + func isContentDiscarded() -> Bool { + return value == nil + } + } + + class StorageObject { + var value: T? + let expiration: StorageExpiration + + private(set) var estimatedExpiration: Date + + init(_ value: T, expiration: StorageExpiration) { + self.value = value + self.expiration = expiration + + self.estimatedExpiration = expiration.estimatedExpirationSinceNow + } + + func extendExpiration(_ extendingExpiration: ExpirationExtending = .cacheTime) { + switch extendingExpiration { + case .none: + return + case .cacheTime: + self.estimatedExpiration = expiration.estimatedExpirationSinceNow + case .expirationTime(let expirationTime): + self.estimatedExpiration = expirationTime.estimatedExpirationSinceNow + } + } + + var isExpired: Bool { + return estimatedExpiration.isPast + } + } +} diff --git a/Pods/Kingfisher/Sources/Cache/Storage.swift b/Pods/Kingfisher/Sources/Cache/Storage.swift new file mode 100644 index 0000000..ad9d326 --- /dev/null +++ b/Pods/Kingfisher/Sources/Cache/Storage.swift @@ -0,0 +1,110 @@ +// +// Storage.swift +// Kingfisher +// +// Created by Wei Wang on 2018/10/15. +// +// Copyright (c) 2019 Wei Wang +// +// Permission is hereby granted, free of charge, to any person obtaining a copy +// of this software and associated documentation files (the "Software"), to deal +// in the Software without restriction, including without limitation the rights +// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +// copies of the Software, and to permit persons to whom the Software is +// furnished to do so, subject to the following conditions: +// +// The above copyright notice and this permission notice shall be included in +// all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN +// THE SOFTWARE. + +import Foundation + +/// Constants for some time intervals +struct TimeConstants { + static let secondsInOneDay = 86_400 +} + +/// Represents the expiration strategy used in storage. +/// +/// - never: The item never expires. +/// - seconds: The item expires after a time duration of given seconds from now. +/// - days: The item expires after a time duration of given days from now. +/// - date: The item expires after a given date. +public enum StorageExpiration { + /// The item never expires. + case never + /// The item expires after a time duration of given seconds from now. + case seconds(TimeInterval) + /// The item expires after a time duration of given days from now. + case days(Int) + /// The item expires after a given date. + case date(Date) + /// Indicates the item is already expired. Use this to skip cache. + case expired + + func estimatedExpirationSince(_ date: Date) -> Date { + switch self { + case .never: return .distantFuture + case .seconds(let seconds): + return date.addingTimeInterval(seconds) + case .days(let days): + let duration: TimeInterval = TimeInterval(TimeConstants.secondsInOneDay) * TimeInterval(days) + return date.addingTimeInterval(duration) + case .date(let ref): + return ref + case .expired: + return .distantPast + } + } + + var estimatedExpirationSinceNow: Date { + return estimatedExpirationSince(Date()) + } + + var isExpired: Bool { + return timeInterval <= 0 + } + + var timeInterval: TimeInterval { + switch self { + case .never: return .infinity + case .seconds(let seconds): return seconds + case .days(let days): return TimeInterval(TimeConstants.secondsInOneDay) * TimeInterval(days) + case .date(let ref): return ref.timeIntervalSinceNow + case .expired: return -(.infinity) + } + } +} + +/// Represents the expiration extending strategy used in storage to after access. +/// +/// - none: The item expires after the original time, without extending after access. +/// - cacheTime: The item expiration extends by the original cache time after each access. +/// - expirationTime: The item expiration extends by the provided time after each access. +public enum ExpirationExtending { + /// The item expires after the original time, without extending after access. + case none + /// The item expiration extends by the original cache time after each access. + case cacheTime + /// The item expiration extends by the provided time after each access. + case expirationTime(_ expiration: StorageExpiration) +} + +/// Represents types which cost in memory can be calculated. +public protocol CacheCostCalculable { + var cacheCost: Int { get } +} + +/// Represents types which can be converted to and from data. +public protocol DataTransformable { + func toData() throws -> Data + static func fromData(_ data: Data) throws -> Self + static var empty: Self { get } +} diff --git a/Pods/Kingfisher/Sources/Extensions/CPListItem+Kingfisher.swift b/Pods/Kingfisher/Sources/Extensions/CPListItem+Kingfisher.swift new file mode 100644 index 0000000..b34c3b1 --- /dev/null +++ b/Pods/Kingfisher/Sources/Extensions/CPListItem+Kingfisher.swift @@ -0,0 +1,260 @@ + +// +// CPListItem+Kingfisher.swift +// Kingfisher +// +// Created by Wayne Hartman on 2021-08-29. +// +// Copyright (c) 2019 Wei Wang +// +// Permission is hereby granted, free of charge, to any person obtaining a copy +// of this software and associated documentation files (the "Software"), to deal +// in the Software without restriction, including without limitation the rights +// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +// copies of the Software, and to permit persons to whom the Software is +// furnished to do so, subject to the following conditions: +// +// The above copyright notice and this permission notice shall be included in +// all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN +// THE SOFTWARE. + +#if canImport(CarPlay) && !targetEnvironment(macCatalyst) +import CarPlay + +@available(iOS 14.0, *) +extension KingfisherWrapper where Base: CPListItem { + + // MARK: Setting Image + + /// Sets an image to the image view with a source. + /// + /// - Parameters: + /// - source: The `Source` object contains information about the image. + /// - placeholder: A placeholder to show while retrieving the image from the given `resource`. + /// - options: An options set to define image setting behaviors. See `KingfisherOptionsInfo` for more. + /// - progressBlock: Called when the image downloading progress gets updated. If the response does not contain an + /// `expectedContentLength`, this block will not be called. + /// - completionHandler: Called when the image retrieved and set finished. + /// - Returns: A task represents the image downloading. + /// + /// - Note: + /// + /// Internally, this method will use `KingfisherManager` to get the requested source + /// Since this method will perform UI changes, you must call it from the main thread. + /// Both `progressBlock` and `completionHandler` will be also executed in the main thread. + /// + @discardableResult + public func setImage( + with source: Source?, + placeholder: KFCrossPlatformImage? = nil, + options: KingfisherOptionsInfo? = nil, + progressBlock: DownloadProgressBlock? = nil, + completionHandler: ((Result) -> Void)? = nil) -> DownloadTask? + { + let options = KingfisherParsedOptionsInfo(KingfisherManager.shared.defaultOptions + (options ?? [])) + return setImage( + with: source, + placeholder: placeholder, + parsedOptions: options, + progressBlock: progressBlock, + completionHandler: completionHandler + ) + } + + /// Sets an image to the image view with a requested resource. + /// + /// - Parameters: + /// - resource: The `Resource` object contains information about the image. + /// - placeholder: A placeholder to show while retrieving the image from the given `resource`. + /// - options: An options set to define image setting behaviors. See `KingfisherOptionsInfo` for more. + /// - progressBlock: Called when the image downloading progress gets updated. If the response does not contain an + /// `expectedContentLength`, this block will not be called. + /// - completionHandler: Called when the image retrieved and set finished. + /// - Returns: A task represents the image downloading. + /// + /// - Note: + /// + /// Internally, this method will use `KingfisherManager` to get the requested resource, from either cache + /// or network. Since this method will perform UI changes, you must call it from the main thread. + /// Both `progressBlock` and `completionHandler` will be also executed in the main thread. + /// + @discardableResult + public func setImage( + with resource: Resource?, + placeholder: KFCrossPlatformImage? = nil, + options: KingfisherOptionsInfo? = nil, + progressBlock: DownloadProgressBlock? = nil, + completionHandler: ((Result) -> Void)? = nil) -> DownloadTask? + { + return setImage( + with: resource?.convertToSource(), + placeholder: placeholder, + options: options, + progressBlock: progressBlock, + completionHandler: completionHandler) + } + + func setImage( + with source: Source?, + placeholder: KFCrossPlatformImage? = nil, + parsedOptions: KingfisherParsedOptionsInfo, + progressBlock: DownloadProgressBlock? = nil, + completionHandler: ((Result) -> Void)? = nil) -> DownloadTask? + { + var mutatingSelf = self + guard let source = source else { + /** + * In iOS SDK 14.0-14.4 the image param was non-`nil`. The SDK changed in 14.5 + * to allow `nil`. The compiler version 5.4 was introduced in this same SDK, + * which allows >=14.5 SDK to set a `nil` image. This compile check allows + * newer SDK users to set the image to `nil`, while still allowing older SDK + * users to compile the framework. + */ + #if compiler(>=5.4) + self.base.setImage(placeholder) + #else + if let placeholder = placeholder { + self.base.setImage(placeholder) + } + #endif + + mutatingSelf.taskIdentifier = nil + completionHandler?(.failure(KingfisherError.imageSettingError(reason: .emptySource))) + return nil + } + + var options = parsedOptions + if !options.keepCurrentImageWhileLoading { + /** + * In iOS SDK 14.0-14.4 the image param was non-`nil`. The SDK changed in 14.5 + * to allow `nil`. The compiler version 5.4 was introduced in this same SDK, + * which allows >=14.5 SDK to set a `nil` image. This compile check allows + * newer SDK users to set the image to `nil`, while still allowing older SDK + * users to compile the framework. + */ + #if compiler(>=5.4) + self.base.setImage(placeholder) + #else // Let older SDK users deal with the older behavior. + if let placeholder = placeholder { + self.base.setImage(placeholder) + } + #endif + } + + let issuedIdentifier = Source.Identifier.next() + mutatingSelf.taskIdentifier = issuedIdentifier + + if let block = progressBlock { + options.onDataReceived = (options.onDataReceived ?? []) + [ImageLoadingProgressSideEffect(block)] + } + + let task = KingfisherManager.shared.retrieveImage( + with: source, + options: options, + downloadTaskUpdated: { mutatingSelf.imageTask = $0 }, + progressiveImageSetter: { image in + /** + * In iOS SDK 14.0-14.4 the image param was non-`nil`. The SDK changed in 14.5 + * to allow `nil`. The compiler version 5.4 was introduced in this same SDK, + * which allows >=14.5 SDK to set a `nil` image. This compile check allows + * newer SDK users to set the image to `nil`, while still allowing older SDK + * users to compile the framework. + */ + #if compiler(>=5.4) + self.base.setImage(image) + #else // Let older SDK users deal with the older behavior. + if let image = image { + self.base.setImage(image) + } + #endif + }, + referenceTaskIdentifierChecker: { issuedIdentifier == self.taskIdentifier }, + completionHandler: { result in + CallbackQueue.mainCurrentOrAsync.execute { + guard issuedIdentifier == self.taskIdentifier else { + let reason: KingfisherError.ImageSettingErrorReason + do { + let value = try result.get() + reason = .notCurrentSourceTask(result: value, error: nil, source: source) + } catch { + reason = .notCurrentSourceTask(result: nil, error: error, source: source) + } + let error = KingfisherError.imageSettingError(reason: reason) + completionHandler?(.failure(error)) + return + } + + mutatingSelf.imageTask = nil + mutatingSelf.taskIdentifier = nil + + switch result { + case .success(let value): + self.base.setImage(value.image) + completionHandler?(result) + + case .failure: + if let image = options.onFailureImage { + /** + * In iOS SDK 14.0-14.4 the image param was non-`nil`. The SDK changed in 14.5 + * to allow `nil`. The compiler version 5.4 was introduced in this same SDK, + * which allows >=14.5 SDK to set a `nil` image. This compile check allows + * newer SDK users to set the image to `nil`, while still allowing older SDK + * users to compile the framework. + */ + #if compiler(>=5.4) + self.base.setImage(image) + #else // Let older SDK users deal with the older behavior. + if let unwrapped = image { + self.base.setImage(unwrapped) + } + #endif + } + completionHandler?(result) + } + } + } + ) + + mutatingSelf.imageTask = task + return task + } + + // MARK: Cancelling Image + + /// Cancel the image download task bounded to the image view if it is running. + /// Nothing will happen if the downloading has already finished. + public func cancelDownloadTask() { + imageTask?.cancel() + } +} + +private var taskIdentifierKey: Void? +private var imageTaskKey: Void? + +// MARK: Properties +extension KingfisherWrapper where Base: CPListItem { + + public private(set) var taskIdentifier: Source.Identifier.Value? { + get { + let box: Box? = getAssociatedObject(base, &taskIdentifierKey) + return box?.value + } + set { + let box = newValue.map { Box($0) } + setRetainedAssociatedObject(base, &taskIdentifierKey, box) + } + } + + private var imageTask: DownloadTask? { + get { return getAssociatedObject(base, &imageTaskKey) } + set { setRetainedAssociatedObject(base, &imageTaskKey, newValue)} + } +} +#endif diff --git a/Pods/Kingfisher/Sources/Extensions/ImageView+Kingfisher.swift b/Pods/Kingfisher/Sources/Extensions/ImageView+Kingfisher.swift new file mode 100644 index 0000000..9378f19 --- /dev/null +++ b/Pods/Kingfisher/Sources/Extensions/ImageView+Kingfisher.swift @@ -0,0 +1,537 @@ +// +// ImageView+Kingfisher.swift +// Kingfisher +// +// Created by Wei Wang on 15/4/6. +// +// Copyright (c) 2019 Wei Wang +// +// Permission is hereby granted, free of charge, to any person obtaining a copy +// of this software and associated documentation files (the "Software"), to deal +// in the Software without restriction, including without limitation the rights +// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +// copies of the Software, and to permit persons to whom the Software is +// furnished to do so, subject to the following conditions: +// +// The above copyright notice and this permission notice shall be included in +// all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN +// THE SOFTWARE. + +#if !os(watchOS) + +#if os(macOS) +import AppKit +#else +import UIKit +#endif + +extension KingfisherWrapper where Base: KFCrossPlatformImageView { + + // MARK: Setting Image + + /// Sets an image to the image view with a `Source`. + /// + /// - Parameters: + /// - source: The `Source` object defines data information from network or a data provider. + /// - placeholder: A placeholder to show while retrieving the image from the given `resource`. + /// - options: An options set to define image setting behaviors. See `KingfisherOptionsInfo` for more. + /// - progressBlock: Called when the image downloading progress gets updated. If the response does not contain an + /// `expectedContentLength`, this block will not be called. + /// - completionHandler: Called when the image retrieved and set finished. + /// - Returns: A task represents the image downloading. + /// + /// - Note: + /// This is the easiest way to use Kingfisher to boost the image setting process from a source. Since all parameters + /// have a default value except the `source`, you can set an image from a certain URL to an image view like this: + /// + /// ``` + /// // Set image from a network source. + /// let url = URL(string: "https://example.com/image.png")! + /// imageView.kf.setImage(with: .network(url)) + /// + /// // Or set image from a data provider. + /// let provider = LocalFileImageDataProvider(fileURL: fileURL) + /// imageView.kf.setImage(with: .provider(provider)) + /// ``` + /// + /// For both `.network` and `.provider` source, there are corresponding view extension methods. So the code + /// above is equivalent to: + /// + /// ``` + /// imageView.kf.setImage(with: url) + /// imageView.kf.setImage(with: provider) + /// ``` + /// + /// Internally, this method will use `KingfisherManager` to get the source. + /// Since this method will perform UI changes, you must call it from the main thread. + /// Both `progressBlock` and `completionHandler` will be also executed in the main thread. + /// + @discardableResult + public func setImage( + with source: Source?, + placeholder: Placeholder? = nil, + options: KingfisherOptionsInfo? = nil, + progressBlock: DownloadProgressBlock? = nil, + completionHandler: ((Result) -> Void)? = nil) -> DownloadTask? + { + let options = KingfisherParsedOptionsInfo(KingfisherManager.shared.defaultOptions + (options ?? .empty)) + return setImage(with: source, placeholder: placeholder, parsedOptions: options, progressBlock: progressBlock, completionHandler: completionHandler) + } + + /// Sets an image to the image view with a `Source`. + /// + /// - Parameters: + /// - source: The `Source` object defines data information from network or a data provider. + /// - placeholder: A placeholder to show while retrieving the image from the given `resource`. + /// - options: An options set to define image setting behaviors. See `KingfisherOptionsInfo` for more. + /// - completionHandler: Called when the image retrieved and set finished. + /// - Returns: A task represents the image downloading. + /// + /// - Note: + /// This is the easiest way to use Kingfisher to boost the image setting process from a source. Since all parameters + /// have a default value except the `source`, you can set an image from a certain URL to an image view like this: + /// + /// ``` + /// // Set image from a network source. + /// let url = URL(string: "https://example.com/image.png")! + /// imageView.kf.setImage(with: .network(url)) + /// + /// // Or set image from a data provider. + /// let provider = LocalFileImageDataProvider(fileURL: fileURL) + /// imageView.kf.setImage(with: .provider(provider)) + /// ``` + /// + /// For both `.network` and `.provider` source, there are corresponding view extension methods. So the code + /// above is equivalent to: + /// + /// ``` + /// imageView.kf.setImage(with: url) + /// imageView.kf.setImage(with: provider) + /// ``` + /// + /// Internally, this method will use `KingfisherManager` to get the source. + /// Since this method will perform UI changes, you must call it from the main thread. + /// The `completionHandler` will be also executed in the main thread. + /// + @discardableResult + public func setImage( + with source: Source?, + placeholder: Placeholder? = nil, + options: KingfisherOptionsInfo? = nil, + completionHandler: ((Result) -> Void)? = nil) -> DownloadTask? + { + return setImage( + with: source, + placeholder: placeholder, + options: options, + progressBlock: nil, + completionHandler: completionHandler + ) + } + + /// Sets an image to the image view with a requested resource. + /// + /// - Parameters: + /// - resource: The `Resource` object contains information about the resource. + /// - placeholder: A placeholder to show while retrieving the image from the given `resource`. + /// - options: An options set to define image setting behaviors. See `KingfisherOptionsInfo` for more. + /// - progressBlock: Called when the image downloading progress gets updated. If the response does not contain an + /// `expectedContentLength`, this block will not be called. + /// - completionHandler: Called when the image retrieved and set finished. + /// - Returns: A task represents the image downloading. + /// + /// - Note: + /// This is the easiest way to use Kingfisher to boost the image setting process from network. Since all parameters + /// have a default value except the `resource`, you can set an image from a certain URL to an image view like this: + /// + /// ``` + /// let url = URL(string: "https://example.com/image.png")! + /// imageView.kf.setImage(with: url) + /// ``` + /// + /// Internally, this method will use `KingfisherManager` to get the requested resource, from either cache + /// or network. Since this method will perform UI changes, you must call it from the main thread. + /// Both `progressBlock` and `completionHandler` will be also executed in the main thread. + /// + @discardableResult + public func setImage( + with resource: Resource?, + placeholder: Placeholder? = nil, + options: KingfisherOptionsInfo? = nil, + progressBlock: DownloadProgressBlock? = nil, + completionHandler: ((Result) -> Void)? = nil) -> DownloadTask? + { + return setImage( + with: resource?.convertToSource(), + placeholder: placeholder, + options: options, + progressBlock: progressBlock, + completionHandler: completionHandler) + } + + /// Sets an image to the image view with a requested resource. + /// + /// - Parameters: + /// - resource: The `Resource` object contains information about the resource. + /// - placeholder: A placeholder to show while retrieving the image from the given `resource`. + /// - options: An options set to define image setting behaviors. See `KingfisherOptionsInfo` for more. + /// - completionHandler: Called when the image retrieved and set finished. + /// - Returns: A task represents the image downloading. + /// + /// - Note: + /// This is the easiest way to use Kingfisher to boost the image setting process from network. Since all parameters + /// have a default value except the `resource`, you can set an image from a certain URL to an image view like this: + /// + /// ``` + /// let url = URL(string: "https://example.com/image.png")! + /// imageView.kf.setImage(with: url) + /// ``` + /// + /// Internally, this method will use `KingfisherManager` to get the requested resource, from either cache + /// or network. Since this method will perform UI changes, you must call it from the main thread. + /// The `completionHandler` will be also executed in the main thread. + /// + @discardableResult + public func setImage( + with resource: Resource?, + placeholder: Placeholder? = nil, + options: KingfisherOptionsInfo? = nil, + completionHandler: ((Result) -> Void)? = nil) -> DownloadTask? + { + return setImage( + with: resource, + placeholder: placeholder, + options: options, + progressBlock: nil, + completionHandler: completionHandler + ) + } + + /// Sets an image to the image view with a data provider. + /// + /// - Parameters: + /// - provider: The `ImageDataProvider` object contains information about the data. + /// - placeholder: A placeholder to show while retrieving the image from the given `resource`. + /// - options: An options set to define image setting behaviors. See `KingfisherOptionsInfo` for more. + /// - progressBlock: Called when the image downloading progress gets updated. If the response does not contain an + /// `expectedContentLength`, this block will not be called. + /// - completionHandler: Called when the image retrieved and set finished. + /// - Returns: A task represents the image downloading. + /// + /// Internally, this method will use `KingfisherManager` to get the image data, from either cache + /// or the data provider. Since this method will perform UI changes, you must call it from the main thread. + /// Both `progressBlock` and `completionHandler` will be also executed in the main thread. + /// + @discardableResult + public func setImage( + with provider: ImageDataProvider?, + placeholder: Placeholder? = nil, + options: KingfisherOptionsInfo? = nil, + progressBlock: DownloadProgressBlock? = nil, + completionHandler: ((Result) -> Void)? = nil) -> DownloadTask? + { + return setImage( + with: provider.map { .provider($0) }, + placeholder: placeholder, + options: options, + progressBlock: progressBlock, + completionHandler: completionHandler) + } + + /// Sets an image to the image view with a data provider. + /// + /// - Parameters: + /// - provider: The `ImageDataProvider` object contains information about the data. + /// - placeholder: A placeholder to show while retrieving the image from the given `resource`. + /// - options: An options set to define image setting behaviors. See `KingfisherOptionsInfo` for more. + /// - completionHandler: Called when the image retrieved and set finished. + /// - Returns: A task represents the image downloading. + /// + /// Internally, this method will use `KingfisherManager` to get the image data, from either cache + /// or the data provider. Since this method will perform UI changes, you must call it from the main thread. + /// The `completionHandler` will be also executed in the main thread. + /// + @discardableResult + public func setImage( + with provider: ImageDataProvider?, + placeholder: Placeholder? = nil, + options: KingfisherOptionsInfo? = nil, + completionHandler: ((Result) -> Void)? = nil) -> DownloadTask? + { + return setImage( + with: provider, + placeholder: placeholder, + options: options, + progressBlock: nil, + completionHandler: completionHandler + ) + } + + + func setImage( + with source: Source?, + placeholder: Placeholder? = nil, + parsedOptions: KingfisherParsedOptionsInfo, + progressBlock: DownloadProgressBlock? = nil, + completionHandler: ((Result) -> Void)? = nil) -> DownloadTask? + { + var mutatingSelf = self + guard let source = source else { + mutatingSelf.placeholder = placeholder + mutatingSelf.taskIdentifier = nil + completionHandler?(.failure(KingfisherError.imageSettingError(reason: .emptySource))) + return nil + } + + var options = parsedOptions + + let isEmptyImage = base.image == nil && self.placeholder == nil + if !options.keepCurrentImageWhileLoading || isEmptyImage { + // Always set placeholder while there is no image/placeholder yet. + mutatingSelf.placeholder = placeholder + } + + let maybeIndicator = indicator + maybeIndicator?.startAnimatingView() + + let issuedIdentifier = Source.Identifier.next() + mutatingSelf.taskIdentifier = issuedIdentifier + + if base.shouldPreloadAllAnimation() { + options.preloadAllAnimationData = true + } + + if let block = progressBlock { + options.onDataReceived = (options.onDataReceived ?? []) + [ImageLoadingProgressSideEffect(block)] + } + + let task = KingfisherManager.shared.retrieveImage( + with: source, + options: options, + downloadTaskUpdated: { mutatingSelf.imageTask = $0 }, + progressiveImageSetter: { self.base.image = $0 }, + referenceTaskIdentifierChecker: { issuedIdentifier == self.taskIdentifier }, + completionHandler: { result in + CallbackQueue.mainCurrentOrAsync.execute { + maybeIndicator?.stopAnimatingView() + guard issuedIdentifier == self.taskIdentifier else { + let reason: KingfisherError.ImageSettingErrorReason + do { + let value = try result.get() + reason = .notCurrentSourceTask(result: value, error: nil, source: source) + } catch { + reason = .notCurrentSourceTask(result: nil, error: error, source: source) + } + let error = KingfisherError.imageSettingError(reason: reason) + completionHandler?(.failure(error)) + return + } + + mutatingSelf.imageTask = nil + mutatingSelf.taskIdentifier = nil + + switch result { + case .success(let value): + guard self.needsTransition(options: options, cacheType: value.cacheType) else { + mutatingSelf.placeholder = nil + self.base.image = value.image + completionHandler?(result) + return + } + + self.makeTransition(image: value.image, transition: options.transition) { + completionHandler?(result) + } + + case .failure: + if let image = options.onFailureImage { + mutatingSelf.placeholder = nil + self.base.image = image + } + completionHandler?(result) + } + } + } + ) + mutatingSelf.imageTask = task + return task + } + + // MARK: Cancelling Downloading Task + + /// Cancels the image download task of the image view if it is running. + /// Nothing will happen if the downloading has already finished. + public func cancelDownloadTask() { + imageTask?.cancel() + } + + private func needsTransition(options: KingfisherParsedOptionsInfo, cacheType: CacheType) -> Bool { + switch options.transition { + case .none: + return false + #if os(macOS) + case .fade: // Fade is only a placeholder for SwiftUI on macOS. + return false + #else + default: + if options.forceTransition { return true } + if cacheType == .none { return true } + return false + #endif + } + } + + private func makeTransition(image: KFCrossPlatformImage, transition: ImageTransition, done: @escaping () -> Void) { + #if !os(macOS) + // Force hiding the indicator without transition first. + UIView.transition( + with: self.base, + duration: 0.0, + options: [], + animations: { self.indicator?.stopAnimatingView() }, + completion: { _ in + var mutatingSelf = self + mutatingSelf.placeholder = nil + UIView.transition( + with: self.base, + duration: transition.duration, + options: [transition.animationOptions, .allowUserInteraction], + animations: { transition.animations?(self.base, image) }, + completion: { finished in + transition.completion?(finished) + done() + } + ) + } + ) + #else + done() + #endif + } +} + +// MARK: - Associated Object +private var taskIdentifierKey: Void? +private var indicatorKey: Void? +private var indicatorTypeKey: Void? +private var placeholderKey: Void? +private var imageTaskKey: Void? + +extension KingfisherWrapper where Base: KFCrossPlatformImageView { + + // MARK: Properties + public private(set) var taskIdentifier: Source.Identifier.Value? { + get { + let box: Box? = getAssociatedObject(base, &taskIdentifierKey) + return box?.value + } + set { + let box = newValue.map { Box($0) } + setRetainedAssociatedObject(base, &taskIdentifierKey, box) + } + } + + /// Holds which indicator type is going to be used. + /// Default is `.none`, means no indicator will be shown while downloading. + public var indicatorType: IndicatorType { + get { + return getAssociatedObject(base, &indicatorTypeKey) ?? .none + } + + set { + switch newValue { + case .none: indicator = nil + case .activity: indicator = ActivityIndicator() + case .image(let data): indicator = ImageIndicator(imageData: data) + case .custom(let anIndicator): indicator = anIndicator + } + + setRetainedAssociatedObject(base, &indicatorTypeKey, newValue) + } + } + + /// Holds any type that conforms to the protocol `Indicator`. + /// The protocol `Indicator` has a `view` property that will be shown when loading an image. + /// It will be `nil` if `indicatorType` is `.none`. + public private(set) var indicator: Indicator? { + get { + let box: Box? = getAssociatedObject(base, &indicatorKey) + return box?.value + } + + set { + // Remove previous + if let previousIndicator = indicator { + previousIndicator.view.removeFromSuperview() + } + + // Add new + if let newIndicator = newValue { + // Set default indicator layout + let view = newIndicator.view + + base.addSubview(view) + view.translatesAutoresizingMaskIntoConstraints = false + view.centerXAnchor.constraint( + equalTo: base.centerXAnchor, constant: newIndicator.centerOffset.x).isActive = true + view.centerYAnchor.constraint( + equalTo: base.centerYAnchor, constant: newIndicator.centerOffset.y).isActive = true + + switch newIndicator.sizeStrategy(in: base) { + case .intrinsicSize: + break + case .full: + view.heightAnchor.constraint(equalTo: base.heightAnchor, constant: 0).isActive = true + view.widthAnchor.constraint(equalTo: base.widthAnchor, constant: 0).isActive = true + case .size(let size): + view.heightAnchor.constraint(equalToConstant: size.height).isActive = true + view.widthAnchor.constraint(equalToConstant: size.width).isActive = true + } + + newIndicator.view.isHidden = true + } + + // Save in associated object + // Wrap newValue with Box to workaround an issue that Swift does not recognize + // and casting protocol for associate object correctly. https://github.com/onevcat/Kingfisher/issues/872 + setRetainedAssociatedObject(base, &indicatorKey, newValue.map(Box.init)) + } + } + + private var imageTask: DownloadTask? { + get { return getAssociatedObject(base, &imageTaskKey) } + set { setRetainedAssociatedObject(base, &imageTaskKey, newValue)} + } + + /// Represents the `Placeholder` used for this image view. A `Placeholder` will be shown in the view while + /// it is downloading an image. + public private(set) var placeholder: Placeholder? { + get { return getAssociatedObject(base, &placeholderKey) } + set { + if let previousPlaceholder = placeholder { + previousPlaceholder.remove(from: base) + } + + if let newPlaceholder = newValue { + newPlaceholder.add(to: base) + } else { + base.image = nil + } + setRetainedAssociatedObject(base, &placeholderKey, newValue) + } + } +} + + +extension KFCrossPlatformImageView { + @objc func shouldPreloadAllAnimation() -> Bool { return true } +} + +#endif diff --git a/Pods/Kingfisher/Sources/Extensions/NSButton+Kingfisher.swift b/Pods/Kingfisher/Sources/Extensions/NSButton+Kingfisher.swift new file mode 100644 index 0000000..d33d557 --- /dev/null +++ b/Pods/Kingfisher/Sources/Extensions/NSButton+Kingfisher.swift @@ -0,0 +1,362 @@ +// +// NSButton+Kingfisher.swift +// Kingfisher +// +// Created by Jie Zhang on 14/04/2016. +// +// Copyright (c) 2019 Wei Wang +// +// Permission is hereby granted, free of charge, to any person obtaining a copy +// of this software and associated documentation files (the "Software"), to deal +// in the Software without restriction, including without limitation the rights +// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +// copies of the Software, and to permit persons to whom the Software is +// furnished to do so, subject to the following conditions: +// +// The above copyright notice and this permission notice shall be included in +// all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN +// THE SOFTWARE. + +#if canImport(AppKit) && !targetEnvironment(macCatalyst) + +import AppKit + +extension KingfisherWrapper where Base: NSButton { + + // MARK: Setting Image + + /// Sets an image to the button with a source. + /// + /// - Parameters: + /// - source: The `Source` object contains information about how to get the image. + /// - placeholder: A placeholder to show while retrieving the image from the given `resource`. + /// - options: An options set to define image setting behaviors. See `KingfisherOptionsInfo` for more. + /// - progressBlock: Called when the image downloading progress gets updated. If the response does not contain an + /// `expectedContentLength`, this block will not be called. + /// - completionHandler: Called when the image retrieved and set finished. + /// - Returns: A task represents the image downloading. + /// + /// - Note: + /// Internally, this method will use `KingfisherManager` to get the requested source. + /// Since this method will perform UI changes, you must call it from the main thread. + /// Both `progressBlock` and `completionHandler` will be also executed in the main thread. + /// + @discardableResult + public func setImage( + with source: Source?, + placeholder: KFCrossPlatformImage? = nil, + options: KingfisherOptionsInfo? = nil, + progressBlock: DownloadProgressBlock? = nil, + completionHandler: ((Result) -> Void)? = nil) -> DownloadTask? + { + let options = KingfisherParsedOptionsInfo(KingfisherManager.shared.defaultOptions + (options ?? .empty)) + return setImage( + with: source, + placeholder: placeholder, + parsedOptions: options, + progressBlock: progressBlock, + completionHandler: completionHandler + ) + } + + /// Sets an image to the button with a requested resource. + /// + /// - Parameters: + /// - resource: The `Resource` object contains information about the resource. + /// - placeholder: A placeholder to show while retrieving the image from the given `resource`. + /// - options: An options set to define image setting behaviors. See `KingfisherOptionsInfo` for more. + /// - progressBlock: Called when the image downloading progress gets updated. If the response does not contain an + /// `expectedContentLength`, this block will not be called. + /// - completionHandler: Called when the image retrieved and set finished. + /// - Returns: A task represents the image downloading. + /// + /// - Note: + /// Internally, this method will use `KingfisherManager` to get the requested resource, from either cache + /// or network. Since this method will perform UI changes, you must call it from the main thread. + /// Both `progressBlock` and `completionHandler` will be also executed in the main thread. + /// + @discardableResult + public func setImage( + with resource: Resource?, + placeholder: KFCrossPlatformImage? = nil, + options: KingfisherOptionsInfo? = nil, + progressBlock: DownloadProgressBlock? = nil, + completionHandler: ((Result) -> Void)? = nil) -> DownloadTask? + { + return setImage( + with: resource?.convertToSource(), + placeholder: placeholder, + options: options, + progressBlock: progressBlock, + completionHandler: completionHandler) + } + + func setImage( + with source: Source?, + placeholder: KFCrossPlatformImage? = nil, + parsedOptions: KingfisherParsedOptionsInfo, + progressBlock: DownloadProgressBlock? = nil, + completionHandler: ((Result) -> Void)? = nil) -> DownloadTask? + { + var mutatingSelf = self + guard let source = source else { + base.image = placeholder + mutatingSelf.taskIdentifier = nil + completionHandler?(.failure(KingfisherError.imageSettingError(reason: .emptySource))) + return nil + } + + var options = parsedOptions + if !options.keepCurrentImageWhileLoading { + base.image = placeholder + } + + let issuedIdentifier = Source.Identifier.next() + mutatingSelf.taskIdentifier = issuedIdentifier + + if let block = progressBlock { + options.onDataReceived = (options.onDataReceived ?? []) + [ImageLoadingProgressSideEffect(block)] + } + + let task = KingfisherManager.shared.retrieveImage( + with: source, + options: options, + downloadTaskUpdated: { mutatingSelf.imageTask = $0 }, + progressiveImageSetter: { self.base.image = $0 }, + referenceTaskIdentifierChecker: { issuedIdentifier == self.taskIdentifier }, + completionHandler: { result in + CallbackQueue.mainCurrentOrAsync.execute { + guard issuedIdentifier == self.taskIdentifier else { + let reason: KingfisherError.ImageSettingErrorReason + do { + let value = try result.get() + reason = .notCurrentSourceTask(result: value, error: nil, source: source) + } catch { + reason = .notCurrentSourceTask(result: nil, error: error, source: source) + } + let error = KingfisherError.imageSettingError(reason: reason) + completionHandler?(.failure(error)) + return + } + + mutatingSelf.imageTask = nil + mutatingSelf.taskIdentifier = nil + + switch result { + case .success(let value): + self.base.image = value.image + completionHandler?(result) + + case .failure: + if let image = options.onFailureImage { + self.base.image = image + } + completionHandler?(result) + } + } + } + ) + + mutatingSelf.imageTask = task + return task + } + + // MARK: Cancelling Downloading Task + + /// Cancels the image download task of the button if it is running. + /// Nothing will happen if the downloading has already finished. + public func cancelImageDownloadTask() { + imageTask?.cancel() + } + + // MARK: Setting Alternate Image + + @discardableResult + public func setAlternateImage( + with source: Source?, + placeholder: KFCrossPlatformImage? = nil, + options: KingfisherOptionsInfo? = nil, + progressBlock: DownloadProgressBlock? = nil, + completionHandler: ((Result) -> Void)? = nil) -> DownloadTask? + { + let options = KingfisherParsedOptionsInfo(KingfisherManager.shared.defaultOptions + (options ?? .empty)) + return setAlternateImage( + with: source, + placeholder: placeholder, + parsedOptions: options, + progressBlock: progressBlock, + completionHandler: completionHandler + ) + } + + /// Sets an alternate image to the button with a requested resource. + /// + /// - Parameters: + /// - resource: The `Resource` object contains information about the resource. + /// - placeholder: A placeholder to show while retrieving the image from the given `resource`. + /// - options: An options set to define image setting behaviors. See `KingfisherOptionsInfo` for more. + /// - progressBlock: Called when the image downloading progress gets updated. If the response does not contain an + /// `expectedContentLength`, this block will not be called. + /// - completionHandler: Called when the image retrieved and set finished. + /// - Returns: A task represents the image downloading. + /// + /// - Note: + /// Internally, this method will use `KingfisherManager` to get the requested resource, from either cache + /// or network. Since this method will perform UI changes, you must call it from the main thread. + /// Both `progressBlock` and `completionHandler` will be also executed in the main thread. + /// + @discardableResult + public func setAlternateImage( + with resource: Resource?, + placeholder: KFCrossPlatformImage? = nil, + options: KingfisherOptionsInfo? = nil, + progressBlock: DownloadProgressBlock? = nil, + completionHandler: ((Result) -> Void)? = nil) -> DownloadTask? + { + return setAlternateImage( + with: resource?.convertToSource(), + placeholder: placeholder, + options: options, + progressBlock: progressBlock, + completionHandler: completionHandler) + } + + func setAlternateImage( + with source: Source?, + placeholder: KFCrossPlatformImage? = nil, + parsedOptions: KingfisherParsedOptionsInfo, + progressBlock: DownloadProgressBlock? = nil, + completionHandler: ((Result) -> Void)? = nil) -> DownloadTask? + { + var mutatingSelf = self + guard let source = source else { + base.alternateImage = placeholder + mutatingSelf.alternateTaskIdentifier = nil + completionHandler?(.failure(KingfisherError.imageSettingError(reason: .emptySource))) + return nil + } + + var options = parsedOptions + if !options.keepCurrentImageWhileLoading { + base.alternateImage = placeholder + } + + let issuedIdentifier = Source.Identifier.next() + mutatingSelf.alternateTaskIdentifier = issuedIdentifier + + if let block = progressBlock { + options.onDataReceived = (options.onDataReceived ?? []) + [ImageLoadingProgressSideEffect(block)] + } + + if let provider = ImageProgressiveProvider(options, refresh: { image in + self.base.alternateImage = image + }) { + options.onDataReceived = (options.onDataReceived ?? []) + [provider] + } + + options.onDataReceived?.forEach { + $0.onShouldApply = { issuedIdentifier == self.alternateTaskIdentifier } + } + + let task = KingfisherManager.shared.retrieveImage( + with: source, + options: options, + downloadTaskUpdated: { mutatingSelf.alternateImageTask = $0 }, + completionHandler: { result in + CallbackQueue.mainCurrentOrAsync.execute { + guard issuedIdentifier == self.alternateTaskIdentifier else { + let reason: KingfisherError.ImageSettingErrorReason + do { + let value = try result.get() + reason = .notCurrentSourceTask(result: value, error: nil, source: source) + } catch { + reason = .notCurrentSourceTask(result: nil, error: error, source: source) + } + let error = KingfisherError.imageSettingError(reason: reason) + completionHandler?(.failure(error)) + return + } + + mutatingSelf.alternateImageTask = nil + mutatingSelf.alternateTaskIdentifier = nil + + switch result { + case .success(let value): + self.base.alternateImage = value.image + completionHandler?(result) + + case .failure: + if let image = options.onFailureImage { + self.base.alternateImage = image + } + completionHandler?(result) + } + } + } + ) + + mutatingSelf.alternateImageTask = task + return task + } + + // MARK: Cancelling Alternate Image Downloading Task + + /// Cancels the alternate image download task of the button if it is running. + /// Nothing will happen if the downloading has already finished. + public func cancelAlternateImageDownloadTask() { + alternateImageTask?.cancel() + } +} + + +// MARK: - Associated Object +private var taskIdentifierKey: Void? +private var imageTaskKey: Void? + +private var alternateTaskIdentifierKey: Void? +private var alternateImageTaskKey: Void? + +extension KingfisherWrapper where Base: NSButton { + + // MARK: Properties + + public private(set) var taskIdentifier: Source.Identifier.Value? { + get { + let box: Box? = getAssociatedObject(base, &taskIdentifierKey) + return box?.value + } + set { + let box = newValue.map { Box($0) } + setRetainedAssociatedObject(base, &taskIdentifierKey, box) + } + } + + private var imageTask: DownloadTask? { + get { return getAssociatedObject(base, &imageTaskKey) } + set { setRetainedAssociatedObject(base, &imageTaskKey, newValue)} + } + + public private(set) var alternateTaskIdentifier: Source.Identifier.Value? { + get { + let box: Box? = getAssociatedObject(base, &alternateTaskIdentifierKey) + return box?.value + } + set { + let box = newValue.map { Box($0) } + setRetainedAssociatedObject(base, &alternateTaskIdentifierKey, box) + } + } + + private var alternateImageTask: DownloadTask? { + get { return getAssociatedObject(base, &alternateImageTaskKey) } + set { setRetainedAssociatedObject(base, &alternateImageTaskKey, newValue)} + } +} +#endif diff --git a/Pods/Kingfisher/Sources/Extensions/NSTextAttachment+Kingfisher.swift b/Pods/Kingfisher/Sources/Extensions/NSTextAttachment+Kingfisher.swift new file mode 100644 index 0000000..23f627e --- /dev/null +++ b/Pods/Kingfisher/Sources/Extensions/NSTextAttachment+Kingfisher.swift @@ -0,0 +1,271 @@ +// +// NSTextAttachment+Kingfisher.swift +// Kingfisher +// +// Created by Benjamin Briggs on 22/07/2019. +// +// Copyright (c) 2019 Wei Wang +// +// Permission is hereby granted, free of charge, to any person obtaining a copy +// of this software and associated documentation files (the "Software"), to deal +// in the Software without restriction, including without limitation the rights +// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +// copies of the Software, and to permit persons to whom the Software is +// furnished to do so, subject to the following conditions: +// +// The above copyright notice and this permission notice shall be included in +// all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN +// THE SOFTWARE. + +#if !os(watchOS) + +#if os(macOS) +import AppKit +#else +import UIKit +#endif + +extension KingfisherWrapper where Base: NSTextAttachment { + + // MARK: Setting Image + + /// Sets an image to the text attachment with a source. + /// + /// - Parameters: + /// - source: The `Source` object defines data information from network or a data provider. + /// - attributedView: The owner of the attributed string which this `NSTextAttachment` is added. + /// - placeholder: A placeholder to show while retrieving the image from the given `resource`. + /// - options: An options set to define image setting behaviors. See `KingfisherOptionsInfo` for more. + /// - progressBlock: Called when the image downloading progress gets updated. If the response does not contain an + /// `expectedContentLength`, this block will not be called. + /// - completionHandler: Called when the image retrieved and set finished. + /// - Returns: A task represents the image downloading. + /// + /// - Note: + /// + /// Internally, this method will use `KingfisherManager` to get the requested source + /// Since this method will perform UI changes, you must call it from the main thread. + /// + /// The retrieved image will be set to `NSTextAttachment.image` property. Because it is not an image view based + /// rendering, options related to view, such as `.transition`, are not supported. + /// + /// Kingfisher will call `setNeedsDisplay` on the `attributedView` when the image task done. It gives the view a + /// chance to render the attributed string again for displaying the downloaded image. For example, if you set an + /// attributed with this `NSTextAttachment` to a `UILabel` object, pass it as the `attributedView` parameter. + /// + /// Here is a typical use case: + /// + /// ```swift + /// let attributedText = NSMutableAttributedString(string: "Hello World") + /// let textAttachment = NSTextAttachment() + /// + /// textAttachment.kf.setImage( + /// with: URL(string: "https://onevcat.com/assets/images/avatar.jpg")!, + /// attributedView: label, + /// options: [ + /// .processor( + /// ResizingImageProcessor(referenceSize: .init(width: 30, height: 30)) + /// |> RoundCornerImageProcessor(cornerRadius: 15)) + /// ] + /// ) + /// attributedText.replaceCharacters(in: NSRange(), with: NSAttributedString(attachment: textAttachment)) + /// label.attributedText = attributedText + /// ``` + /// + @discardableResult + public func setImage( + with source: Source?, + attributedView: @autoclosure @escaping () -> KFCrossPlatformView, + placeholder: KFCrossPlatformImage? = nil, + options: KingfisherOptionsInfo? = nil, + progressBlock: DownloadProgressBlock? = nil, + completionHandler: ((Result) -> Void)? = nil) -> DownloadTask? + { + let options = KingfisherParsedOptionsInfo(KingfisherManager.shared.defaultOptions + (options ?? .empty)) + return setImage( + with: source, + attributedView: attributedView, + placeholder: placeholder, + parsedOptions: options, + progressBlock: progressBlock, + completionHandler: completionHandler + ) + } + + /// Sets an image to the text attachment with a source. + /// + /// - Parameters: + /// - resource: The `Resource` object contains information about the resource. + /// - attributedView: The owner of the attributed string which this `NSTextAttachment` is added. + /// - placeholder: A placeholder to show while retrieving the image from the given `resource`. + /// - options: An options set to define image setting behaviors. See `KingfisherOptionsInfo` for more. + /// - progressBlock: Called when the image downloading progress gets updated. If the response does not contain an + /// `expectedContentLength`, this block will not be called. + /// - completionHandler: Called when the image retrieved and set finished. + /// - Returns: A task represents the image downloading. + /// + /// - Note: + /// + /// Internally, this method will use `KingfisherManager` to get the requested source + /// Since this method will perform UI changes, you must call it from the main thread. + /// + /// The retrieved image will be set to `NSTextAttachment.image` property. Because it is not an image view based + /// rendering, options related to view, such as `.transition`, are not supported. + /// + /// Kingfisher will call `setNeedsDisplay` on the `attributedView` when the image task done. It gives the view a + /// chance to render the attributed string again for displaying the downloaded image. For example, if you set an + /// attributed with this `NSTextAttachment` to a `UILabel` object, pass it as the `attributedView` parameter. + /// + /// Here is a typical use case: + /// + /// ```swift + /// let attributedText = NSMutableAttributedString(string: "Hello World") + /// let textAttachment = NSTextAttachment() + /// + /// textAttachment.kf.setImage( + /// with: URL(string: "https://onevcat.com/assets/images/avatar.jpg")!, + /// attributedView: label, + /// options: [ + /// .processor( + /// ResizingImageProcessor(referenceSize: .init(width: 30, height: 30)) + /// |> RoundCornerImageProcessor(cornerRadius: 15)) + /// ] + /// ) + /// attributedText.replaceCharacters(in: NSRange(), with: NSAttributedString(attachment: textAttachment)) + /// label.attributedText = attributedText + /// ``` + /// + @discardableResult + public func setImage( + with resource: Resource?, + attributedView: @autoclosure @escaping () -> KFCrossPlatformView, + placeholder: KFCrossPlatformImage? = nil, + options: KingfisherOptionsInfo? = nil, + progressBlock: DownloadProgressBlock? = nil, + completionHandler: ((Result) -> Void)? = nil) -> DownloadTask? + { + let options = KingfisherParsedOptionsInfo(KingfisherManager.shared.defaultOptions + (options ?? .empty)) + return setImage( + with: resource.map { .network($0) }, + attributedView: attributedView, + placeholder: placeholder, + parsedOptions: options, + progressBlock: progressBlock, + completionHandler: completionHandler + ) + } + + func setImage( + with source: Source?, + attributedView: @escaping () -> KFCrossPlatformView, + placeholder: KFCrossPlatformImage? = nil, + parsedOptions: KingfisherParsedOptionsInfo, + progressBlock: DownloadProgressBlock? = nil, + completionHandler: ((Result) -> Void)? = nil) -> DownloadTask? + { + var mutatingSelf = self + guard let source = source else { + base.image = placeholder + mutatingSelf.taskIdentifier = nil + completionHandler?(.failure(KingfisherError.imageSettingError(reason: .emptySource))) + return nil + } + + var options = parsedOptions + if !options.keepCurrentImageWhileLoading { + base.image = placeholder + } + + let issuedIdentifier = Source.Identifier.next() + mutatingSelf.taskIdentifier = issuedIdentifier + + if let block = progressBlock { + options.onDataReceived = (options.onDataReceived ?? []) + [ImageLoadingProgressSideEffect(block)] + } + + let task = KingfisherManager.shared.retrieveImage( + with: source, + options: options, + progressiveImageSetter: { self.base.image = $0 }, + referenceTaskIdentifierChecker: { issuedIdentifier == self.taskIdentifier }, + completionHandler: { result in + CallbackQueue.mainCurrentOrAsync.execute { + guard issuedIdentifier == self.taskIdentifier else { + let reason: KingfisherError.ImageSettingErrorReason + do { + let value = try result.get() + reason = .notCurrentSourceTask(result: value, error: nil, source: source) + } catch { + reason = .notCurrentSourceTask(result: nil, error: error, source: source) + } + let error = KingfisherError.imageSettingError(reason: reason) + completionHandler?(.failure(error)) + return + } + + mutatingSelf.imageTask = nil + mutatingSelf.taskIdentifier = nil + + switch result { + case .success(let value): + self.base.image = value.image + let view = attributedView() + #if canImport(UIKit) + view.setNeedsDisplay() + #else + view.setNeedsDisplay(view.bounds) + #endif + case .failure: + if let image = options.onFailureImage { + self.base.image = image + } + } + completionHandler?(result) + } + } + ) + + mutatingSelf.imageTask = task + return task + } + + // MARK: Cancelling Image + + /// Cancel the image download task bounded to the text attachment if it is running. + /// Nothing will happen if the downloading has already finished. + public func cancelDownloadTask() { + imageTask?.cancel() + } +} + +private var taskIdentifierKey: Void? +private var imageTaskKey: Void? + +// MARK: Properties +extension KingfisherWrapper where Base: NSTextAttachment { + + public private(set) var taskIdentifier: Source.Identifier.Value? { + get { + let box: Box? = getAssociatedObject(base, &taskIdentifierKey) + return box?.value + } + set { + let box = newValue.map { Box($0) } + setRetainedAssociatedObject(base, &taskIdentifierKey, box) + } + } + + private var imageTask: DownloadTask? { + get { return getAssociatedObject(base, &imageTaskKey) } + set { setRetainedAssociatedObject(base, &imageTaskKey, newValue)} + } +} + +#endif diff --git a/Pods/Kingfisher/Sources/Extensions/TVMonogramView+Kingfisher.swift b/Pods/Kingfisher/Sources/Extensions/TVMonogramView+Kingfisher.swift new file mode 100644 index 0000000..c0993cd --- /dev/null +++ b/Pods/Kingfisher/Sources/Extensions/TVMonogramView+Kingfisher.swift @@ -0,0 +1,209 @@ +// +// TVMonogramView+Kingfisher.swift +// Kingfisher +// +// Created by Marvin Nazari on 2020-12-07. +// +// Copyright (c) 2020 Wei Wang +// +// Permission is hereby granted, free of charge, to any person obtaining a copy +// of this software and associated documentation files (the "Software"), to deal +// in the Software without restriction, including without limitation the rights +// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +// copies of the Software, and to permit persons to whom the Software is +// furnished to do so, subject to the following conditions: +// +// The above copyright notice and this permission notice shall be included in +// all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN +// THE SOFTWARE. + +import Foundation + +#if canImport(TVUIKit) + +import TVUIKit + +@available(tvOS 12.0, *) +extension KingfisherWrapper where Base: TVMonogramView { + + // MARK: Setting Image + + /// Sets an image to the image view with a source. + /// + /// - Parameters: + /// - source: The `Source` object contains information about the image. + /// - placeholder: A placeholder to show while retrieving the image from the given `resource`. + /// - options: An options set to define image setting behaviors. See `KingfisherOptionsInfo` for more. + /// - progressBlock: Called when the image downloading progress gets updated. If the response does not contain an + /// `expectedContentLength`, this block will not be called. + /// - completionHandler: Called when the image retrieved and set finished. + /// - Returns: A task represents the image downloading. + /// + /// - Note: + /// + /// Internally, this method will use `KingfisherManager` to get the requested source + /// Since this method will perform UI changes, you must call it from the main thread. + /// Both `progressBlock` and `completionHandler` will be also executed in the main thread. + /// + @discardableResult + public func setImage( + with source: Source?, + placeholder: KFCrossPlatformImage? = nil, + options: KingfisherOptionsInfo? = nil, + progressBlock: DownloadProgressBlock? = nil, + completionHandler: ((Result) -> Void)? = nil) -> DownloadTask? + { + let options = KingfisherParsedOptionsInfo(KingfisherManager.shared.defaultOptions + (options ?? .empty)) + return setImage( + with: source, + placeholder: placeholder, + parsedOptions: options, + progressBlock: progressBlock, + completionHandler: completionHandler + ) + } + + func setImage( + with source: Source?, + placeholder: KFCrossPlatformImage? = nil, + parsedOptions: KingfisherParsedOptionsInfo, + progressBlock: DownloadProgressBlock? = nil, + completionHandler: ((Result) -> Void)? = nil) -> DownloadTask? + { + var mutatingSelf = self + guard let source = source else { + base.image = placeholder + mutatingSelf.taskIdentifier = nil + completionHandler?(.failure(KingfisherError.imageSettingError(reason: .emptySource))) + return nil + } + + var options = parsedOptions + if !options.keepCurrentImageWhileLoading { + base.image = placeholder + } + + let issuedIdentifier = Source.Identifier.next() + mutatingSelf.taskIdentifier = issuedIdentifier + + if let block = progressBlock { + options.onDataReceived = (options.onDataReceived ?? []) + [ImageLoadingProgressSideEffect(block)] + } + + let task = KingfisherManager.shared.retrieveImage( + with: source, + options: options, + downloadTaskUpdated: { mutatingSelf.imageTask = $0 }, + progressiveImageSetter: { self.base.image = $0 }, + referenceTaskIdentifierChecker: { issuedIdentifier == self.taskIdentifier }, + completionHandler: { result in + CallbackQueue.mainCurrentOrAsync.execute { + guard issuedIdentifier == self.taskIdentifier else { + let reason: KingfisherError.ImageSettingErrorReason + do { + let value = try result.get() + reason = .notCurrentSourceTask(result: value, error: nil, source: source) + } catch { + reason = .notCurrentSourceTask(result: nil, error: error, source: source) + } + let error = KingfisherError.imageSettingError(reason: reason) + completionHandler?(.failure(error)) + return + } + + mutatingSelf.imageTask = nil + mutatingSelf.taskIdentifier = nil + + switch result { + case .success(let value): + self.base.image = value.image + completionHandler?(result) + + case .failure: + if let image = options.onFailureImage { + self.base.image = image + } + completionHandler?(result) + } + } + } + ) + + mutatingSelf.imageTask = task + return task + } + + /// Sets an image to the image view with a requested resource. + /// + /// - Parameters: + /// - resource: The `Resource` object contains information about the image. + /// - placeholder: A placeholder to show while retrieving the image from the given `resource`. + /// - options: An options set to define image setting behaviors. See `KingfisherOptionsInfo` for more. + /// - progressBlock: Called when the image downloading progress gets updated. If the response does not contain an + /// `expectedContentLength`, this block will not be called. + /// - completionHandler: Called when the image retrieved and set finished. + /// - Returns: A task represents the image downloading. + /// + /// - Note: + /// + /// Internally, this method will use `KingfisherManager` to get the requested resource, from either cache + /// or network. Since this method will perform UI changes, you must call it from the main thread. + /// Both `progressBlock` and `completionHandler` will be also executed in the main thread. + /// + @discardableResult + public func setImage( + with resource: Resource?, + placeholder: KFCrossPlatformImage? = nil, + options: KingfisherOptionsInfo? = nil, + progressBlock: DownloadProgressBlock? = nil, + completionHandler: ((Result) -> Void)? = nil) -> DownloadTask? + { + return setImage( + with: resource?.convertToSource(), + placeholder: placeholder, + options: options, + progressBlock: progressBlock, + completionHandler: completionHandler) + } + + // MARK: Cancelling Image + + /// Cancel the image download task bounded to the image view if it is running. + /// Nothing will happen if the downloading has already finished. + public func cancelDownloadTask() { + imageTask?.cancel() + } +} + +private var taskIdentifierKey: Void? +private var imageTaskKey: Void? + +// MARK: Properties +@available(tvOS 12.0, *) +extension KingfisherWrapper where Base: TVMonogramView { + + public private(set) var taskIdentifier: Source.Identifier.Value? { + get { + let box: Box? = getAssociatedObject(base, &taskIdentifierKey) + return box?.value + } + set { + let box = newValue.map { Box($0) } + setRetainedAssociatedObject(base, &taskIdentifierKey, box) + } + } + + private var imageTask: DownloadTask? { + get { return getAssociatedObject(base, &imageTaskKey) } + set { setRetainedAssociatedObject(base, &imageTaskKey, newValue)} + } +} + +#endif diff --git a/Pods/Kingfisher/Sources/Extensions/UIButton+Kingfisher.swift b/Pods/Kingfisher/Sources/Extensions/UIButton+Kingfisher.swift new file mode 100644 index 0000000..d1e2dcb --- /dev/null +++ b/Pods/Kingfisher/Sources/Extensions/UIButton+Kingfisher.swift @@ -0,0 +1,400 @@ +// +// UIButton+Kingfisher.swift +// Kingfisher +// +// Created by Wei Wang on 15/4/13. +// +// Copyright (c) 2019 Wei Wang +// +// Permission is hereby granted, free of charge, to any person obtaining a copy +// of this software and associated documentation files (the "Software"), to deal +// in the Software without restriction, including without limitation the rights +// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +// copies of the Software, and to permit persons to whom the Software is +// furnished to do so, subject to the following conditions: +// +// The above copyright notice and this permission notice shall be included in +// all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN +// THE SOFTWARE. + +#if !os(watchOS) + +#if canImport(UIKit) +import UIKit + +extension KingfisherWrapper where Base: UIButton { + + // MARK: Setting Image + /// Sets an image to the button for a specified state with a source. + /// + /// - Parameters: + /// - source: The `Source` object contains information about the image. + /// - state: The button state to which the image should be set. + /// - placeholder: A placeholder to show while retrieving the image from the given `resource`. + /// - options: An options set to define image setting behaviors. See `KingfisherOptionsInfo` for more. + /// - progressBlock: Called when the image downloading progress gets updated. If the response does not contain an + /// `expectedContentLength`, this block will not be called. + /// - completionHandler: Called when the image retrieved and set finished. + /// - Returns: A task represents the image downloading. + /// + /// - Note: + /// Internally, this method will use `KingfisherManager` to get the requested source, from either cache + /// or network. Since this method will perform UI changes, you must call it from the main thread. + /// Both `progressBlock` and `completionHandler` will be also executed in the main thread. + /// + @discardableResult + public func setImage( + with source: Source?, + for state: UIControl.State, + placeholder: UIImage? = nil, + options: KingfisherOptionsInfo? = nil, + progressBlock: DownloadProgressBlock? = nil, + completionHandler: ((Result) -> Void)? = nil) -> DownloadTask? + { + let options = KingfisherParsedOptionsInfo(KingfisherManager.shared.defaultOptions + (options ?? .empty)) + return setImage( + with: source, + for: state, + placeholder: placeholder, + parsedOptions: options, + progressBlock: progressBlock, + completionHandler: completionHandler + ) + } + + /// Sets an image to the button for a specified state with a requested resource. + /// + /// - Parameters: + /// - resource: The `Resource` object contains information about the resource. + /// - state: The button state to which the image should be set. + /// - placeholder: A placeholder to show while retrieving the image from the given `resource`. + /// - options: An options set to define image setting behaviors. See `KingfisherOptionsInfo` for more. + /// - progressBlock: Called when the image downloading progress gets updated. If the response does not contain an + /// `expectedContentLength`, this block will not be called. + /// - completionHandler: Called when the image retrieved and set finished. + /// - Returns: A task represents the image downloading. + /// + /// - Note: + /// Internally, this method will use `KingfisherManager` to get the requested resource, from either cache + /// or network. Since this method will perform UI changes, you must call it from the main thread. + /// Both `progressBlock` and `completionHandler` will be also executed in the main thread. + /// + @discardableResult + public func setImage( + with resource: Resource?, + for state: UIControl.State, + placeholder: UIImage? = nil, + options: KingfisherOptionsInfo? = nil, + progressBlock: DownloadProgressBlock? = nil, + completionHandler: ((Result) -> Void)? = nil) -> DownloadTask? + { + return setImage( + with: resource?.convertToSource(), + for: state, + placeholder: placeholder, + options: options, + progressBlock: progressBlock, + completionHandler: completionHandler) + } + + @discardableResult + public func setImage( + with source: Source?, + for state: UIControl.State, + placeholder: UIImage? = nil, + parsedOptions: KingfisherParsedOptionsInfo, + progressBlock: DownloadProgressBlock? = nil, + completionHandler: ((Result) -> Void)? = nil) -> DownloadTask? + { + guard let source = source else { + base.setImage(placeholder, for: state) + setTaskIdentifier(nil, for: state) + completionHandler?(.failure(KingfisherError.imageSettingError(reason: .emptySource))) + return nil + } + + var options = parsedOptions + if !options.keepCurrentImageWhileLoading { + base.setImage(placeholder, for: state) + } + + var mutatingSelf = self + let issuedIdentifier = Source.Identifier.next() + setTaskIdentifier(issuedIdentifier, for: state) + + if let block = progressBlock { + options.onDataReceived = (options.onDataReceived ?? []) + [ImageLoadingProgressSideEffect(block)] + } + + let task = KingfisherManager.shared.retrieveImage( + with: source, + options: options, + downloadTaskUpdated: { mutatingSelf.imageTask = $0 }, + progressiveImageSetter: { self.base.setImage($0, for: state) }, + referenceTaskIdentifierChecker: { issuedIdentifier == self.taskIdentifier(for: state) }, + completionHandler: { result in + CallbackQueue.mainCurrentOrAsync.execute { + guard issuedIdentifier == self.taskIdentifier(for: state) else { + let reason: KingfisherError.ImageSettingErrorReason + do { + let value = try result.get() + reason = .notCurrentSourceTask(result: value, error: nil, source: source) + } catch { + reason = .notCurrentSourceTask(result: nil, error: error, source: source) + } + let error = KingfisherError.imageSettingError(reason: reason) + completionHandler?(.failure(error)) + return + } + + mutatingSelf.imageTask = nil + mutatingSelf.setTaskIdentifier(nil, for: state) + + switch result { + case .success(let value): + self.base.setImage(value.image, for: state) + completionHandler?(result) + + case .failure: + if let image = options.onFailureImage { + self.base.setImage(image, for: state) + } + completionHandler?(result) + } + } + } + ) + + mutatingSelf.imageTask = task + return task + } + + // MARK: Cancelling Downloading Task + + /// Cancels the image download task of the button if it is running. + /// Nothing will happen if the downloading has already finished. + public func cancelImageDownloadTask() { + imageTask?.cancel() + } + + // MARK: Setting Background Image + + /// Sets a background image to the button for a specified state with a source. + /// + /// - Parameters: + /// - source: The `Source` object contains information about the image. + /// - state: The button state to which the image should be set. + /// - placeholder: A placeholder to show while retrieving the image from the given `resource`. + /// - options: An options set to define image setting behaviors. See `KingfisherOptionsInfo` for more. + /// - progressBlock: Called when the image downloading progress gets updated. If the response does not contain an + /// `expectedContentLength`, this block will not be called. + /// - completionHandler: Called when the image retrieved and set finished. + /// - Returns: A task represents the image downloading. + /// + /// - Note: + /// Internally, this method will use `KingfisherManager` to get the requested source + /// Since this method will perform UI changes, you must call it from the main thread. + /// Both `progressBlock` and `completionHandler` will be also executed in the main thread. + /// + @discardableResult + public func setBackgroundImage( + with source: Source?, + for state: UIControl.State, + placeholder: UIImage? = nil, + options: KingfisherOptionsInfo? = nil, + progressBlock: DownloadProgressBlock? = nil, + completionHandler: ((Result) -> Void)? = nil) -> DownloadTask? + { + let options = KingfisherParsedOptionsInfo(KingfisherManager.shared.defaultOptions + (options ?? .empty)) + return setBackgroundImage( + with: source, + for: state, + placeholder: placeholder, + parsedOptions: options, + progressBlock: progressBlock, + completionHandler: completionHandler + ) + } + + /// Sets a background image to the button for a specified state with a requested resource. + /// + /// - Parameters: + /// - resource: The `Resource` object contains information about the resource. + /// - state: The button state to which the image should be set. + /// - placeholder: A placeholder to show while retrieving the image from the given `resource`. + /// - options: An options set to define image setting behaviors. See `KingfisherOptionsInfo` for more. + /// - progressBlock: Called when the image downloading progress gets updated. If the response does not contain an + /// `expectedContentLength`, this block will not be called. + /// - completionHandler: Called when the image retrieved and set finished. + /// - Returns: A task represents the image downloading. + /// + /// - Note: + /// Internally, this method will use `KingfisherManager` to get the requested resource, from either cache + /// or network. Since this method will perform UI changes, you must call it from the main thread. + /// Both `progressBlock` and `completionHandler` will be also executed in the main thread. + /// + @discardableResult + public func setBackgroundImage( + with resource: Resource?, + for state: UIControl.State, + placeholder: UIImage? = nil, + options: KingfisherOptionsInfo? = nil, + progressBlock: DownloadProgressBlock? = nil, + completionHandler: ((Result) -> Void)? = nil) -> DownloadTask? + { + return setBackgroundImage( + with: resource?.convertToSource(), + for: state, + placeholder: placeholder, + options: options, + progressBlock: progressBlock, + completionHandler: completionHandler) + } + + func setBackgroundImage( + with source: Source?, + for state: UIControl.State, + placeholder: UIImage? = nil, + parsedOptions: KingfisherParsedOptionsInfo, + progressBlock: DownloadProgressBlock? = nil, + completionHandler: ((Result) -> Void)? = nil) -> DownloadTask? + { + guard let source = source else { + base.setBackgroundImage(placeholder, for: state) + setBackgroundTaskIdentifier(nil, for: state) + completionHandler?(.failure(KingfisherError.imageSettingError(reason: .emptySource))) + return nil + } + + var options = parsedOptions + if !options.keepCurrentImageWhileLoading { + base.setBackgroundImage(placeholder, for: state) + } + + var mutatingSelf = self + let issuedIdentifier = Source.Identifier.next() + setBackgroundTaskIdentifier(issuedIdentifier, for: state) + + if let block = progressBlock { + options.onDataReceived = (options.onDataReceived ?? []) + [ImageLoadingProgressSideEffect(block)] + } + + let task = KingfisherManager.shared.retrieveImage( + with: source, + options: options, + downloadTaskUpdated: { mutatingSelf.backgroundImageTask = $0 }, + progressiveImageSetter: { self.base.setBackgroundImage($0, for: state) }, + referenceTaskIdentifierChecker: { issuedIdentifier == self.backgroundTaskIdentifier(for: state) }, + completionHandler: { result in + CallbackQueue.mainCurrentOrAsync.execute { + guard issuedIdentifier == self.backgroundTaskIdentifier(for: state) else { + let reason: KingfisherError.ImageSettingErrorReason + do { + let value = try result.get() + reason = .notCurrentSourceTask(result: value, error: nil, source: source) + } catch { + reason = .notCurrentSourceTask(result: nil, error: error, source: source) + } + let error = KingfisherError.imageSettingError(reason: reason) + completionHandler?(.failure(error)) + return + } + + mutatingSelf.backgroundImageTask = nil + mutatingSelf.setBackgroundTaskIdentifier(nil, for: state) + + switch result { + case .success(let value): + self.base.setBackgroundImage(value.image, for: state) + completionHandler?(result) + + case .failure: + if let image = options.onFailureImage { + self.base.setBackgroundImage(image, for: state) + } + completionHandler?(result) + } + } + } + ) + + mutatingSelf.backgroundImageTask = task + return task + } + + // MARK: Cancelling Background Downloading Task + + /// Cancels the background image download task of the button if it is running. + /// Nothing will happen if the downloading has already finished. + public func cancelBackgroundImageDownloadTask() { + backgroundImageTask?.cancel() + } +} + +// MARK: - Associated Object +private var taskIdentifierKey: Void? +private var imageTaskKey: Void? + +// MARK: Properties +extension KingfisherWrapper where Base: UIButton { + + private typealias TaskIdentifier = Box<[UInt: Source.Identifier.Value]> + + public func taskIdentifier(for state: UIControl.State) -> Source.Identifier.Value? { + return taskIdentifierInfo.value[state.rawValue] + } + + private func setTaskIdentifier(_ identifier: Source.Identifier.Value?, for state: UIControl.State) { + taskIdentifierInfo.value[state.rawValue] = identifier + } + + private var taskIdentifierInfo: TaskIdentifier { + return getAssociatedObject(base, &taskIdentifierKey) ?? { + setRetainedAssociatedObject(base, &taskIdentifierKey, $0) + return $0 + } (TaskIdentifier([:])) + } + + private var imageTask: DownloadTask? { + get { return getAssociatedObject(base, &imageTaskKey) } + set { setRetainedAssociatedObject(base, &imageTaskKey, newValue)} + } +} + + +private var backgroundTaskIdentifierKey: Void? +private var backgroundImageTaskKey: Void? + +// MARK: Background Properties +extension KingfisherWrapper where Base: UIButton { + + public func backgroundTaskIdentifier(for state: UIControl.State) -> Source.Identifier.Value? { + return backgroundTaskIdentifierInfo.value[state.rawValue] + } + + private func setBackgroundTaskIdentifier(_ identifier: Source.Identifier.Value?, for state: UIControl.State) { + backgroundTaskIdentifierInfo.value[state.rawValue] = identifier + } + + private var backgroundTaskIdentifierInfo: TaskIdentifier { + return getAssociatedObject(base, &backgroundTaskIdentifierKey) ?? { + setRetainedAssociatedObject(base, &backgroundTaskIdentifierKey, $0) + return $0 + } (TaskIdentifier([:])) + } + + private var backgroundImageTask: DownloadTask? { + get { return getAssociatedObject(base, &backgroundImageTaskKey) } + mutating set { setRetainedAssociatedObject(base, &backgroundImageTaskKey, newValue) } + } +} +#endif + +#endif diff --git a/Pods/Kingfisher/Sources/Extensions/WKInterfaceImage+Kingfisher.swift b/Pods/Kingfisher/Sources/Extensions/WKInterfaceImage+Kingfisher.swift new file mode 100644 index 0000000..a24feeb --- /dev/null +++ b/Pods/Kingfisher/Sources/Extensions/WKInterfaceImage+Kingfisher.swift @@ -0,0 +1,204 @@ +// +// WKInterfaceImage+Kingfisher.swift +// Kingfisher +// +// Created by Rodrigo Borges Soares on 04/05/18. +// +// Copyright (c) 2019 Wei Wang +// +// Permission is hereby granted, free of charge, to any person obtaining a copy +// of this software and associated documentation files (the "Software"), to deal +// in the Software without restriction, including without limitation the rights +// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +// copies of the Software, and to permit persons to whom the Software is +// furnished to do so, subject to the following conditions: +// +// The above copyright notice and this permission notice shall be included in +// all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN +// THE SOFTWARE. + +#if canImport(WatchKit) + +import WatchKit + +extension KingfisherWrapper where Base: WKInterfaceImage { + + // MARK: Setting Image + + /// Sets an image to the image view with a source. + /// + /// - Parameters: + /// - source: The `Source` object contains information about the image. + /// - placeholder: A placeholder to show while retrieving the image from the given `resource`. + /// - options: An options set to define image setting behaviors. See `KingfisherOptionsInfo` for more. + /// - progressBlock: Called when the image downloading progress gets updated. If the response does not contain an + /// `expectedContentLength`, this block will not be called. + /// - completionHandler: Called when the image retrieved and set finished. + /// - Returns: A task represents the image downloading. + /// + /// - Note: + /// + /// Internally, this method will use `KingfisherManager` to get the requested source + /// Since this method will perform UI changes, you must call it from the main thread. + /// Both `progressBlock` and `completionHandler` will be also executed in the main thread. + /// + @discardableResult + public func setImage( + with source: Source?, + placeholder: KFCrossPlatformImage? = nil, + options: KingfisherOptionsInfo? = nil, + progressBlock: DownloadProgressBlock? = nil, + completionHandler: ((Result) -> Void)? = nil) -> DownloadTask? + { + let options = KingfisherParsedOptionsInfo(KingfisherManager.shared.defaultOptions + (options ?? .empty)) + return setImage( + with: source, + placeholder: placeholder, + parsedOptions: options, + progressBlock: progressBlock, + completionHandler: completionHandler + ) + } + + /// Sets an image to the image view with a requested resource. + /// + /// - Parameters: + /// - resource: The `Resource` object contains information about the image. + /// - placeholder: A placeholder to show while retrieving the image from the given `resource`. + /// - options: An options set to define image setting behaviors. See `KingfisherOptionsInfo` for more. + /// - progressBlock: Called when the image downloading progress gets updated. If the response does not contain an + /// `expectedContentLength`, this block will not be called. + /// - completionHandler: Called when the image retrieved and set finished. + /// - Returns: A task represents the image downloading. + /// + /// - Note: + /// + /// Internally, this method will use `KingfisherManager` to get the requested resource, from either cache + /// or network. Since this method will perform UI changes, you must call it from the main thread. + /// Both `progressBlock` and `completionHandler` will be also executed in the main thread. + /// + @discardableResult + public func setImage( + with resource: Resource?, + placeholder: KFCrossPlatformImage? = nil, + options: KingfisherOptionsInfo? = nil, + progressBlock: DownloadProgressBlock? = nil, + completionHandler: ((Result) -> Void)? = nil) -> DownloadTask? + { + return setImage( + with: resource?.convertToSource(), + placeholder: placeholder, + options: options, + progressBlock: progressBlock, + completionHandler: completionHandler) + } + + func setImage( + with source: Source?, + placeholder: KFCrossPlatformImage? = nil, + parsedOptions: KingfisherParsedOptionsInfo, + progressBlock: DownloadProgressBlock? = nil, + completionHandler: ((Result) -> Void)? = nil) -> DownloadTask? + { + var mutatingSelf = self + guard let source = source else { + base.setImage(placeholder) + mutatingSelf.taskIdentifier = nil + completionHandler?(.failure(KingfisherError.imageSettingError(reason: .emptySource))) + return nil + } + + var options = parsedOptions + if !options.keepCurrentImageWhileLoading { + base.setImage(placeholder) + } + + let issuedIdentifier = Source.Identifier.next() + mutatingSelf.taskIdentifier = issuedIdentifier + + if let block = progressBlock { + options.onDataReceived = (options.onDataReceived ?? []) + [ImageLoadingProgressSideEffect(block)] + } + + let task = KingfisherManager.shared.retrieveImage( + with: source, + options: options, + downloadTaskUpdated: { mutatingSelf.imageTask = $0 }, + progressiveImageSetter: { self.base.setImage($0) }, + referenceTaskIdentifierChecker: { issuedIdentifier == self.taskIdentifier }, + completionHandler: { result in + CallbackQueue.mainCurrentOrAsync.execute { + guard issuedIdentifier == self.taskIdentifier else { + let reason: KingfisherError.ImageSettingErrorReason + do { + let value = try result.get() + reason = .notCurrentSourceTask(result: value, error: nil, source: source) + } catch { + reason = .notCurrentSourceTask(result: nil, error: error, source: source) + } + let error = KingfisherError.imageSettingError(reason: reason) + completionHandler?(.failure(error)) + return + } + + mutatingSelf.imageTask = nil + mutatingSelf.taskIdentifier = nil + + switch result { + case .success(let value): + self.base.setImage(value.image) + completionHandler?(result) + + case .failure: + if let image = options.onFailureImage { + self.base.setImage(image) + } + completionHandler?(result) + } + } + } + ) + + mutatingSelf.imageTask = task + return task + } + + // MARK: Cancelling Image + + /// Cancel the image download task bounded to the image view if it is running. + /// Nothing will happen if the downloading has already finished. + public func cancelDownloadTask() { + imageTask?.cancel() + } +} + +private var taskIdentifierKey: Void? +private var imageTaskKey: Void? + +// MARK: Properties +extension KingfisherWrapper where Base: WKInterfaceImage { + + public private(set) var taskIdentifier: Source.Identifier.Value? { + get { + let box: Box? = getAssociatedObject(base, &taskIdentifierKey) + return box?.value + } + set { + let box = newValue.map { Box($0) } + setRetainedAssociatedObject(base, &taskIdentifierKey, box) + } + } + + private var imageTask: DownloadTask? { + get { return getAssociatedObject(base, &imageTaskKey) } + set { setRetainedAssociatedObject(base, &imageTaskKey, newValue)} + } +} +#endif diff --git a/Pods/Kingfisher/Sources/General/ImageSource/AVAssetImageDataProvider.swift b/Pods/Kingfisher/Sources/General/ImageSource/AVAssetImageDataProvider.swift new file mode 100644 index 0000000..7dc35ff --- /dev/null +++ b/Pods/Kingfisher/Sources/General/ImageSource/AVAssetImageDataProvider.swift @@ -0,0 +1,151 @@ +// +// AVAssetImageDataProvider.swift +// Kingfisher +// +// Created by onevcat on 2020/08/09. +// +// Copyright (c) 2020 Wei Wang +// +// Permission is hereby granted, free of charge, to any person obtaining a copy +// of this software and associated documentation files (the "Software"), to deal +// in the Software without restriction, including without limitation the rights +// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +// copies of the Software, and to permit persons to whom the Software is +// furnished to do so, subject to the following conditions: +// +// The above copyright notice and this permission notice shall be included in +// all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN +// THE SOFTWARE. + +#if !os(watchOS) + +import Foundation +import AVKit + +#if canImport(MobileCoreServices) +import MobileCoreServices +#else +import CoreServices +#endif + +/// A data provider to provide thumbnail data from a given AVKit asset. +public struct AVAssetImageDataProvider: ImageDataProvider { + + /// The possible error might be caused by the `AVAssetImageDataProvider`. + /// - userCancelled: The data provider process is cancelled. + /// - invalidImage: The retrieved image is invalid. + public enum AVAssetImageDataProviderError: Error { + case userCancelled + case invalidImage(_ image: CGImage?) + } + + /// The asset image generator bound to `self`. + public let assetImageGenerator: AVAssetImageGenerator + + /// The time at which the image should be generate in the asset. + public let time: CMTime + + private var internalKey: String { + guard let url = (assetImageGenerator.asset as? AVURLAsset)?.url else { + return UUID().uuidString + } + return url.cacheKey + } + + /// The cache key used by `self`. + public var cacheKey: String { + return "\(internalKey)_\(time.seconds)" + } + + /// Creates an asset image data provider. + /// - Parameters: + /// - assetImageGenerator: The asset image generator controls data providing behaviors. + /// - time: At which time in the asset the image should be generated. + public init(assetImageGenerator: AVAssetImageGenerator, time: CMTime) { + self.assetImageGenerator = assetImageGenerator + self.time = time + } + + /// Creates an asset image data provider. + /// - Parameters: + /// - assetURL: The URL of asset for providing image data. + /// - time: At which time in the asset the image should be generated. + /// + /// This method uses `assetURL` to create an `AVAssetImageGenerator` object and calls + /// the `init(assetImageGenerator:time:)` initializer. + /// + public init(assetURL: URL, time: CMTime) { + let asset = AVAsset(url: assetURL) + let generator = AVAssetImageGenerator(asset: asset) + generator.appliesPreferredTrackTransform = true + self.init(assetImageGenerator: generator, time: time) + } + + /// Creates an asset image data provider. + /// + /// - Parameters: + /// - assetURL: The URL of asset for providing image data. + /// - seconds: At which time in seconds in the asset the image should be generated. + /// + /// This method uses `assetURL` to create an `AVAssetImageGenerator` object, uses `seconds` to create a `CMTime`, + /// and calls the `init(assetImageGenerator:time:)` initializer. + /// + public init(assetURL: URL, seconds: TimeInterval) { + let time = CMTime(seconds: seconds, preferredTimescale: 600) + self.init(assetURL: assetURL, time: time) + } + + public func data(handler: @escaping (Result) -> Void) { + assetImageGenerator.generateCGImagesAsynchronously(forTimes: [NSValue(time: time)]) { + (requestedTime, image, imageTime, result, error) in + if let error = error { + handler(.failure(error)) + return + } + + if result == .cancelled { + handler(.failure(AVAssetImageDataProviderError.userCancelled)) + return + } + + guard let cgImage = image, let data = cgImage.jpegData else { + handler(.failure(AVAssetImageDataProviderError.invalidImage(image))) + return + } + + handler(.success(data)) + } + } +} + +extension CGImage { + var jpegData: Data? { + guard let mutableData = CFDataCreateMutable(nil, 0) else { + return nil + } +#if os(visionOS) + guard let destination = CGImageDestinationCreateWithData( + mutableData, UTType.jpeg.identifier as CFString , 1, nil + ) else { + return nil + } +#else + guard let destination = CGImageDestinationCreateWithData(mutableData, kUTTypeJPEG, 1, nil) else { + return nil + } +#endif + + CGImageDestinationAddImage(destination, self, nil) + guard CGImageDestinationFinalize(destination) else { return nil } + return mutableData as Data + } +} + +#endif diff --git a/Pods/Kingfisher/Sources/General/ImageSource/ImageDataProvider.swift b/Pods/Kingfisher/Sources/General/ImageSource/ImageDataProvider.swift new file mode 100644 index 0000000..dd34150 --- /dev/null +++ b/Pods/Kingfisher/Sources/General/ImageSource/ImageDataProvider.swift @@ -0,0 +1,190 @@ +// +// ImageDataProvider.swift +// Kingfisher +// +// Created by onevcat on 2018/11/13. +// +// Copyright (c) 2019 Wei Wang +// +// Permission is hereby granted, free of charge, to any person obtaining a copy +// of this software and associated documentation files (the "Software"), to deal +// in the Software without restriction, including without limitation the rights +// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +// copies of the Software, and to permit persons to whom the Software is +// furnished to do so, subject to the following conditions: +// +// The above copyright notice and this permission notice shall be included in +// all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN +// THE SOFTWARE. + +import Foundation + +/// Represents a data provider to provide image data to Kingfisher when setting with +/// `Source.provider` source. Compared to `Source.network` member, it gives a chance +/// to load some image data in your own way, as long as you can provide the data +/// representation for the image. +public protocol ImageDataProvider { + + /// The key used in cache. + var cacheKey: String { get } + + /// Provides the data which represents image. Kingfisher uses the data you pass in the + /// handler to process images and caches it for later use. + /// + /// - Parameter handler: The handler you should call when you prepared your data. + /// If the data is loaded successfully, call the handler with + /// a `.success` with the data associated. Otherwise, call it + /// with a `.failure` and pass the error. + /// + /// - Note: + /// If the `handler` is called with a `.failure` with error, a `dataProviderError` of + /// `ImageSettingErrorReason` will be finally thrown out to you as the `KingfisherError` + /// from the framework. + func data(handler: @escaping (Result) -> Void) + + /// The content URL represents this provider, if exists. + var contentURL: URL? { get } +} + +public extension ImageDataProvider { + var contentURL: URL? { return nil } + func convertToSource() -> Source { + .provider(self) + } +} + +/// Represents an image data provider for loading from a local file URL on disk. +/// Uses this type for adding a disk image to Kingfisher. Compared to loading it +/// directly, you can get benefit of using Kingfisher's extension methods, as well +/// as applying `ImageProcessor`s and storing the image to `ImageCache` of Kingfisher. +public struct LocalFileImageDataProvider: ImageDataProvider { + + // MARK: Public Properties + + /// The file URL from which the image be loaded. + public let fileURL: URL + private let loadingQueue: ExecutionQueue + + // MARK: Initializers + + /// Creates an image data provider by supplying the target local file URL. + /// + /// - Parameters: + /// - fileURL: The file URL from which the image be loaded. + /// - cacheKey: The key is used for caching the image data. By default, + /// the `absoluteString` of `fileURL` is used. + /// - loadingQueue: The queue where the file loading should happen. By default, the dispatch queue of + /// `.global(qos: .userInitiated)` will be used. + public init( + fileURL: URL, + cacheKey: String? = nil, + loadingQueue: ExecutionQueue = .dispatch(DispatchQueue.global(qos: .userInitiated)) + ) { + self.fileURL = fileURL + self.cacheKey = cacheKey ?? fileURL.localFileCacheKey + self.loadingQueue = loadingQueue + } + + // MARK: Protocol Conforming + + /// The key used in cache. + public var cacheKey: String + + public func data(handler:@escaping (Result) -> Void) { + loadingQueue.execute { + handler(Result(catching: { try Data(contentsOf: fileURL) })) + } + } + + #if swift(>=5.5) + #if canImport(_Concurrency) + @available(iOS 13.0, macOS 10.15, tvOS 13.0, watchOS 6.0, *) + public var data: Data { + get async throws { + try await withCheckedThrowingContinuation { continuation in + loadingQueue.execute { + do { + let data = try Data(contentsOf: fileURL) + continuation.resume(returning: data) + } catch { + continuation.resume(throwing: error) + } + } + } + } + } + #endif + #endif + + /// The URL of the local file on the disk. + public var contentURL: URL? { + return fileURL + } +} + +/// Represents an image data provider for loading image from a given Base64 encoded string. +public struct Base64ImageDataProvider: ImageDataProvider { + + // MARK: Public Properties + /// The encoded Base64 string for the image. + public let base64String: String + + // MARK: Initializers + + /// Creates an image data provider by supplying the Base64 encoded string. + /// + /// - Parameters: + /// - base64String: The Base64 encoded string for an image. + /// - cacheKey: The key is used for caching the image data. You need a different key for any different image. + public init(base64String: String, cacheKey: String) { + self.base64String = base64String + self.cacheKey = cacheKey + } + + // MARK: Protocol Conforming + + /// The key used in cache. + public var cacheKey: String + + public func data(handler: (Result) -> Void) { + let data = Data(base64Encoded: base64String)! + handler(.success(data)) + } +} + +/// Represents an image data provider for a raw data object. +public struct RawImageDataProvider: ImageDataProvider { + + // MARK: Public Properties + + /// The raw data object to provide to Kingfisher image loader. + public let data: Data + + // MARK: Initializers + + /// Creates an image data provider by the given raw `data` value and a `cacheKey` be used in Kingfisher cache. + /// + /// - Parameters: + /// - data: The raw data reprensents an image. + /// - cacheKey: The key is used for caching the image data. You need a different key for any different image. + public init(data: Data, cacheKey: String) { + self.data = data + self.cacheKey = cacheKey + } + + // MARK: Protocol Conforming + + /// The key used in cache. + public var cacheKey: String + + public func data(handler: @escaping (Result) -> Void) { + handler(.success(data)) + } +} diff --git a/Pods/Kingfisher/Sources/General/ImageSource/Resource.swift b/Pods/Kingfisher/Sources/General/ImageSource/Resource.swift new file mode 100644 index 0000000..f6c1a57 --- /dev/null +++ b/Pods/Kingfisher/Sources/General/ImageSource/Resource.swift @@ -0,0 +1,121 @@ +// +// Resource.swift +// Kingfisher +// +// Created by Wei Wang on 15/4/6. +// +// Copyright (c) 2019 Wei Wang +// +// Permission is hereby granted, free of charge, to any person obtaining a copy +// of this software and associated documentation files (the "Software"), to deal +// in the Software without restriction, including without limitation the rights +// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +// copies of the Software, and to permit persons to whom the Software is +// furnished to do so, subject to the following conditions: +// +// The above copyright notice and this permission notice shall be included in +// all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN +// THE SOFTWARE. + +import Foundation + +/// Represents an image resource at a certain url and a given cache key. +/// Kingfisher will use a `Resource` to download a resource from network and cache it with the cache key when +/// using `Source.network` as its image setting source. +public protocol Resource { + + /// The key used in cache. + var cacheKey: String { get } + + /// The target image URL. + var downloadURL: URL { get } +} + +extension Resource { + + /// Converts `self` to a valid `Source` based on its `downloadURL` scheme. A `.provider` with + /// `LocalFileImageDataProvider` associated will be returned if the URL points to a local file. Otherwise, + /// `.network` is returned. + public func convertToSource(overrideCacheKey: String? = nil) -> Source { + let key = overrideCacheKey ?? cacheKey + return downloadURL.isFileURL ? + .provider(LocalFileImageDataProvider(fileURL: downloadURL, cacheKey: key)) : + .network(KF.ImageResource(downloadURL: downloadURL, cacheKey: key)) + } +} + +@available(*, deprecated, message: "This type conflicts with `GeneratedAssetSymbols.ImageResource` in Swift 5.9. Renamed to avoid issues in the future.", renamed: "KF.ImageResource") +public typealias ImageResource = KF.ImageResource + + +extension KF { + /// ImageResource is a simple combination of `downloadURL` and `cacheKey`. + /// When passed to image view set methods, Kingfisher will try to download the target + /// image from the `downloadURL`, and then store it with the `cacheKey` as the key in cache. + public struct ImageResource: Resource { + + // MARK: - Initializers + + /// Creates an image resource. + /// + /// - Parameters: + /// - downloadURL: The target image URL from where the image can be downloaded. + /// - cacheKey: The cache key. If `nil`, Kingfisher will use the `absoluteString` of `downloadURL` as the key. + /// Default is `nil`. + public init(downloadURL: URL, cacheKey: String? = nil) { + self.downloadURL = downloadURL + self.cacheKey = cacheKey ?? downloadURL.cacheKey + } + + // MARK: Protocol Conforming + + /// The key used in cache. + public let cacheKey: String + + /// The target image URL. + public let downloadURL: URL + } +} + +/// URL conforms to `Resource` in Kingfisher. +/// The `absoluteString` of this URL is used as `cacheKey`. And the URL itself will be used as `downloadURL`. +/// If you need customize the url and/or cache key, use `ImageResource` instead. +extension URL: Resource { + public var cacheKey: String { return isFileURL ? localFileCacheKey : absoluteString } + public var downloadURL: URL { return self } +} + +extension URL { + static let localFileCacheKeyPrefix = "kingfisher.local.cacheKey" + + // The special version of cache key for a local file on disk. Every time the app is reinstalled on the disk, + // the system assigns a new container folder to hold the .app (and the extensions, .appex) folder. So the URL for + // the same image in bundle might be different. + // + // This getter only uses the fixed part in the URL (until the bundle name folder) to provide a stable cache key + // for the image under the same path inside the bundle. + // + // See #1825 (https://github.com/onevcat/Kingfisher/issues/1825) + var localFileCacheKey: String { + var validComponents: [String] = [] + for part in pathComponents.reversed() { + validComponents.append(part) + if part.hasSuffix(".app") || part.hasSuffix(".appex") { + break + } + } + let fixedPath = "\(Self.localFileCacheKeyPrefix)/\(validComponents.reversed().joined(separator: "/"))" + if let q = query { + return "\(fixedPath)?\(q)" + } else { + return fixedPath + } + } +} diff --git a/Pods/Kingfisher/Sources/General/ImageSource/Source.swift b/Pods/Kingfisher/Sources/General/ImageSource/Source.swift new file mode 100644 index 0000000..e0684fb --- /dev/null +++ b/Pods/Kingfisher/Sources/General/ImageSource/Source.swift @@ -0,0 +1,116 @@ +// +// Source.swift +// Kingfisher +// +// Created by onevcat on 2018/11/17. +// +// Copyright (c) 2019 Wei Wang +// +// Permission is hereby granted, free of charge, to any person obtaining a copy +// of this software and associated documentation files (the "Software"), to deal +// in the Software without restriction, including without limitation the rights +// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +// copies of the Software, and to permit persons to whom the Software is +// furnished to do so, subject to the following conditions: +// +// The above copyright notice and this permission notice shall be included in +// all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN +// THE SOFTWARE. + +import Foundation + +/// Represents an image setting source for Kingfisher methods. +/// +/// A `Source` value indicates the way how the target image can be retrieved and cached. +/// +/// - network: The target image should be got from network remotely. The associated `Resource` +/// value defines detail information like image URL and cache key. +/// - provider: The target image should be provided in a data format. Normally, it can be an image +/// from local storage or in any other encoding format (like Base64). +public enum Source { + + /// Represents the source task identifier when setting an image to a view with extension methods. + public enum Identifier { + + /// The underlying value type of source identifier. + public typealias Value = UInt + static private(set) var current: Value = 0 + static func next() -> Value { + current += 1 + return current + } + } + + // MARK: Member Cases + + /// The target image should be got from network remotely. The associated `Resource` + /// value defines detail information like image URL and cache key. + case network(Resource) + + /// The target image should be provided in a data format. Normally, it can be an image + /// from local storage or in any other encoding format (like Base64). + case provider(ImageDataProvider) + + // MARK: Getting Properties + + /// The cache key defined for this source value. + public var cacheKey: String { + switch self { + case .network(let resource): return resource.cacheKey + case .provider(let provider): return provider.cacheKey + } + } + + /// The URL defined for this source value. + /// + /// For a `.network` source, it is the `downloadURL` of associated `Resource` instance. + /// For a `.provider` value, it is always `nil`. + public var url: URL? { + switch self { + case .network(let resource): return resource.downloadURL + case .provider(let provider): return provider.contentURL + } + } +} + +extension Source: Hashable { + public static func == (lhs: Source, rhs: Source) -> Bool { + switch (lhs, rhs) { + case (.network(let r1), .network(let r2)): + return r1.cacheKey == r2.cacheKey && r1.downloadURL == r2.downloadURL + case (.provider(let p1), .provider(let p2)): + return p1.cacheKey == p2.cacheKey && p1.contentURL == p2.contentURL + case (.provider(_), .network(_)): + return false + case (.network(_), .provider(_)): + return false + } + } + + public func hash(into hasher: inout Hasher) { + switch self { + case .network(let r): + hasher.combine(r.cacheKey) + hasher.combine(r.downloadURL) + case .provider(let p): + hasher.combine(p.cacheKey) + hasher.combine(p.contentURL) + } + } +} + +extension Source { + var asResource: Resource? { + guard case .network(let resource) = self else { + return nil + } + return resource + } +} diff --git a/Pods/Kingfisher/Sources/General/KF.swift b/Pods/Kingfisher/Sources/General/KF.swift new file mode 100644 index 0000000..0e6a970 --- /dev/null +++ b/Pods/Kingfisher/Sources/General/KF.swift @@ -0,0 +1,442 @@ +// +// KF.swift +// Kingfisher +// +// Created by onevcat on 2020/09/21. +// +// Copyright (c) 2020 Wei Wang +// +// Permission is hereby granted, free of charge, to any person obtaining a copy +// of this software and associated documentation files (the "Software"), to deal +// in the Software without restriction, including without limitation the rights +// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +// copies of the Software, and to permit persons to whom the Software is +// furnished to do so, subject to the following conditions: +// +// The above copyright notice and this permission notice shall be included in +// all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN +// THE SOFTWARE. + +#if canImport(UIKit) +import UIKit +#endif + +#if canImport(CarPlay) && !targetEnvironment(macCatalyst) +import CarPlay +#endif + +#if canImport(AppKit) && !targetEnvironment(macCatalyst) +import AppKit +#endif + +#if canImport(WatchKit) +import WatchKit +#endif + +#if canImport(TVUIKit) +import TVUIKit +#endif + +/// A helper type to create image setting tasks in a builder pattern. +/// Use methods in this type to create a `KF.Builder` instance and configure image tasks there. +public enum KF { + + /// Creates a builder for a given `Source`. + /// - Parameter source: The `Source` object defines data information from network or a data provider. + /// - Returns: A `KF.Builder` for future configuration. After configuring the builder, call `set(to:)` + /// to start the image loading. + public static func source(_ source: Source?) -> KF.Builder { + Builder(source: source) + } + + /// Creates a builder for a given `Resource`. + /// - Parameter resource: The `Resource` object defines data information like key or URL. + /// - Returns: A `KF.Builder` for future configuration. After configuring the builder, call `set(to:)` + /// to start the image loading. + public static func resource(_ resource: Resource?) -> KF.Builder { + source(resource?.convertToSource()) + } + + /// Creates a builder for a given `URL` and an optional cache key. + /// - Parameters: + /// - url: The URL where the image should be downloaded. + /// - cacheKey: The key used to store the downloaded image in cache. + /// If `nil`, the `absoluteString` of `url` is used as the cache key. + /// - Returns: A `KF.Builder` for future configuration. After configuring the builder, call `set(to:)` + /// to start the image loading. + public static func url(_ url: URL?, cacheKey: String? = nil) -> KF.Builder { + source(url?.convertToSource(overrideCacheKey: cacheKey)) + } + + /// Creates a builder for a given `ImageDataProvider`. + /// - Parameter provider: The `ImageDataProvider` object contains information about the data. + /// - Returns: A `KF.Builder` for future configuration. After configuring the builder, call `set(to:)` + /// to start the image loading. + public static func dataProvider(_ provider: ImageDataProvider?) -> KF.Builder { + source(provider?.convertToSource()) + } + + /// Creates a builder for some given raw data and a cache key. + /// - Parameters: + /// - data: The data object from which the image should be created. + /// - cacheKey: The key used to store the downloaded image in cache. + /// - Returns: A `KF.Builder` for future configuration. After configuring the builder, call `set(to:)` + /// to start the image loading. + public static func data(_ data: Data?, cacheKey: String) -> KF.Builder { + if let data = data { + return dataProvider(RawImageDataProvider(data: data, cacheKey: cacheKey)) + } else { + return dataProvider(nil) + } + } +} + + +extension KF { + + /// A builder class to configure an image retrieving task and set it to a holder view or component. + public class Builder { + private let source: Source? + + #if os(watchOS) + private var placeholder: KFCrossPlatformImage? + #else + private var placeholder: Placeholder? + #endif + + public var options = KingfisherParsedOptionsInfo(KingfisherManager.shared.defaultOptions) + + public let onFailureDelegate = Delegate() + public let onSuccessDelegate = Delegate() + public let onProgressDelegate = Delegate<(Int64, Int64), Void>() + + init(source: Source?) { + self.source = source + } + + private var resultHandler: ((Result) -> Void)? { + { + switch $0 { + case .success(let result): + self.onSuccessDelegate(result) + case .failure(let error): + self.onFailureDelegate(error) + } + } + } + + private var progressBlock: DownloadProgressBlock { + { self.onProgressDelegate(($0, $1)) } + } + } +} + +extension KF.Builder { + #if !os(watchOS) + + /// Builds the image task request and sets it to an image view. + /// - Parameter imageView: The image view which loads the task and should be set with the image. + /// - Returns: A task represents the image downloading, if initialized. + /// This value is `nil` if the image is being loaded from cache. + @discardableResult + public func set(to imageView: KFCrossPlatformImageView) -> DownloadTask? { + imageView.kf.setImage( + with: source, + placeholder: placeholder, + parsedOptions: options, + progressBlock: progressBlock, + completionHandler: resultHandler + ) + } + + /// Builds the image task request and sets it to an `NSTextAttachment` object. + /// - Parameters: + /// - attachment: The text attachment object which loads the task and should be set with the image. + /// - attributedView: The owner of the attributed string which this `NSTextAttachment` is added. + /// - Returns: A task represents the image downloading, if initialized. + /// This value is `nil` if the image is being loaded from cache. + @discardableResult + public func set(to attachment: NSTextAttachment, attributedView: @autoclosure @escaping () -> KFCrossPlatformView) -> DownloadTask? { + let placeholderImage = placeholder as? KFCrossPlatformImage ?? nil + return attachment.kf.setImage( + with: source, + attributedView: attributedView, + placeholder: placeholderImage, + parsedOptions: options, + progressBlock: progressBlock, + completionHandler: resultHandler + ) + } + + #if canImport(UIKit) + + /// Builds the image task request and sets it to a button. + /// - Parameters: + /// - button: The button which loads the task and should be set with the image. + /// - state: The button state to which the image should be set. + /// - Returns: A task represents the image downloading, if initialized. + /// This value is `nil` if the image is being loaded from cache. + @discardableResult + public func set(to button: UIButton, for state: UIControl.State) -> DownloadTask? { + let placeholderImage = placeholder as? KFCrossPlatformImage ?? nil + return button.kf.setImage( + with: source, + for: state, + placeholder: placeholderImage, + parsedOptions: options, + progressBlock: progressBlock, + completionHandler: resultHandler + ) + } + + /// Builds the image task request and sets it to the background image for a button. + /// - Parameters: + /// - button: The button which loads the task and should be set with the image. + /// - state: The button state to which the image should be set. + /// - Returns: A task represents the image downloading, if initialized. + /// This value is `nil` if the image is being loaded from cache. + @discardableResult + public func setBackground(to button: UIButton, for state: UIControl.State) -> DownloadTask? { + let placeholderImage = placeholder as? KFCrossPlatformImage ?? nil + return button.kf.setBackgroundImage( + with: source, + for: state, + placeholder: placeholderImage, + parsedOptions: options, + progressBlock: progressBlock, + completionHandler: resultHandler + ) + } + #endif // end of canImport(UIKit) + + #if canImport(CarPlay) && !targetEnvironment(macCatalyst) + + /// Builds the image task request and sets it to the image for a list item. + /// - Parameters: + /// - listItem: The list item which loads the task and should be set with the image. + /// - Returns: A task represents the image downloading, if initialized. + /// This value is `nil` if the image is being loaded from cache. + @available(iOS 14.0, *) + @discardableResult + public func set(to listItem: CPListItem) -> DownloadTask? { + let placeholderImage = placeholder as? KFCrossPlatformImage ?? nil + return listItem.kf.setImage( + with: source, + placeholder: placeholderImage, + parsedOptions: options, + progressBlock: progressBlock, + completionHandler: resultHandler + ) + + } + + #endif + + #if canImport(AppKit) && !targetEnvironment(macCatalyst) + /// Builds the image task request and sets it to a button. + /// - Parameter button: The button which loads the task and should be set with the image. + /// - Returns: A task represents the image downloading, if initialized. + /// This value is `nil` if the image is being loaded from cache. + @discardableResult + public func set(to button: NSButton) -> DownloadTask? { + let placeholderImage = placeholder as? KFCrossPlatformImage ?? nil + return button.kf.setImage( + with: source, + placeholder: placeholderImage, + parsedOptions: options, + progressBlock: progressBlock, + completionHandler: resultHandler + ) + } + + /// Builds the image task request and sets it to the alternative image for a button. + /// - Parameter button: The button which loads the task and should be set with the image. + /// - Returns: A task represents the image downloading, if initialized. + /// This value is `nil` if the image is being loaded from cache. + @discardableResult + public func setAlternative(to button: NSButton) -> DownloadTask? { + let placeholderImage = placeholder as? KFCrossPlatformImage ?? nil + return button.kf.setAlternateImage( + with: source, + placeholder: placeholderImage, + parsedOptions: options, + progressBlock: progressBlock, + completionHandler: resultHandler + ) + } + #endif // end of canImport(AppKit) + #endif // end of !os(watchOS) + + #if canImport(WatchKit) + /// Builds the image task request and sets it to a `WKInterfaceImage` object. + /// - Parameter interfaceImage: The watch interface image which loads the task and should be set with the image. + /// - Returns: A task represents the image downloading, if initialized. + /// This value is `nil` if the image is being loaded from cache. + @discardableResult + public func set(to interfaceImage: WKInterfaceImage) -> DownloadTask? { + return interfaceImage.kf.setImage( + with: source, + placeholder: placeholder, + parsedOptions: options, + progressBlock: progressBlock, + completionHandler: resultHandler + ) + } + #endif // end of canImport(WatchKit) + + #if canImport(TVUIKit) + /// Builds the image task request and sets it to a TV monogram view. + /// - Parameter monogramView: The monogram view which loads the task and should be set with the image. + /// - Returns: A task represents the image downloading, if initialized. + /// This value is `nil` if the image is being loaded from cache. + @available(tvOS 12.0, *) + @discardableResult + public func set(to monogramView: TVMonogramView) -> DownloadTask? { + let placeholderImage = placeholder as? KFCrossPlatformImage ?? nil + return monogramView.kf.setImage( + with: source, + placeholder: placeholderImage, + parsedOptions: options, + progressBlock: progressBlock, + completionHandler: resultHandler + ) + } + #endif // end of canImport(TVUIKit) +} + +#if !os(watchOS) +extension KF.Builder { + #if os(iOS) || os(tvOS) || os(visionOS) + + /// Sets a placeholder which is used while retrieving the image. + /// - Parameter placeholder: A placeholder to show while retrieving the image from its source. + /// - Returns: A `KF.Builder` with changes applied. + public func placeholder(_ placeholder: Placeholder?) -> Self { + self.placeholder = placeholder + return self + } + #endif + + /// Sets a placeholder image which is used while retrieving the image. + /// - Parameter placeholder: An image to show while retrieving the image from its source. + /// - Returns: A `KF.Builder` with changes applied. + public func placeholder(_ image: KFCrossPlatformImage?) -> Self { + self.placeholder = image + return self + } +} +#endif + +extension KF.Builder { + + #if os(iOS) || os(tvOS) || os(visionOS) + /// Sets the transition for the image task. + /// - Parameter transition: The desired transition effect when setting the image to image view. + /// - Returns: A `KF.Builder` with changes applied. + /// + /// Kingfisher will use the `transition` to animate the image in if it is downloaded from web. + /// The transition will not happen when the + /// image is retrieved from either memory or disk cache by default. If you need to do the transition even when + /// the image being retrieved from cache, also call `forceRefresh()` on the returned `KF.Builder`. + public func transition(_ transition: ImageTransition) -> Self { + options.transition = transition + return self + } + + /// Sets a fade transition for the image task. + /// - Parameter duration: The duration of the fade transition. + /// - Returns: A `KF.Builder` with changes applied. + /// + /// Kingfisher will use the fade transition to animate the image in if it is downloaded from web. + /// The transition will not happen when the + /// image is retrieved from either memory or disk cache by default. If you need to do the transition even when + /// the image being retrieved from cache, also call `forceRefresh()` on the returned `KF.Builder`. + public func fade(duration: TimeInterval) -> Self { + options.transition = .fade(duration) + return self + } + #endif + + /// Sets whether keeping the existing image of image view while setting another image to it. + /// - Parameter enabled: Whether the existing image should be kept. + /// - Returns: A `KF.Builder` with changes applied. + /// + /// By setting this option, the placeholder image parameter of image view extension method + /// will be ignored and the current image will be kept while loading or downloading the new image. + /// + public func keepCurrentImageWhileLoading(_ enabled: Bool = true) -> Self { + options.keepCurrentImageWhileLoading = enabled + return self + } + + /// Sets whether only the first frame from an animated image file should be loaded as a single image. + /// - Parameter enabled: Whether the only the first frame should be loaded. + /// - Returns: A `KF.Builder` with changes applied. + /// + /// Loading an animated images may take too much memory. It will be useful when you want to display a + /// static preview of the first frame from an animated image. + /// + /// This option will be ignored if the target image is not animated image data. + /// + public func onlyLoadFirstFrame(_ enabled: Bool = true) -> Self { + options.onlyLoadFirstFrame = enabled + return self + } + + /// Enables progressive image loading with a specified `ImageProgressive` setting to process the + /// progressive JPEG data and display it in a progressive way. + /// - Parameter progressive: The progressive settings which is used while loading. + /// - Returns: A `KF.Builder` with changes applied. + public func progressiveJPEG(_ progressive: ImageProgressive? = .init()) -> Self { + options.progressiveJPEG = progressive + return self + } +} + +// MARK: - Deprecated +extension KF.Builder { + /// Starts the loading process of `self` immediately. + /// + /// By default, a `KFImage` will not load its source until the `onAppear` is called. This is a lazily loading + /// behavior and provides better performance. However, when you refresh the view, the lazy loading also causes a + /// flickering since the loading does not happen immediately. Call this method if you want to start the load at once + /// could help avoiding the flickering, with some performance trade-off. + /// + /// - Deprecated: This is not necessary anymore since `@StateObject` is used for holding the image data. + /// It does nothing now and please just remove it. + /// + /// - Returns: The `Self` value with changes applied. + @available(*, deprecated, message: "This is not necessary anymore since `@StateObject` is used. It does nothing now and please just remove it.") + public func loadImmediately(_ start: Bool = true) -> Self { + return self + } +} + +// MARK: - Redirect Handler +extension KF { + + /// Represents the detail information when a task redirect happens. It is wrapping necessary information for a + /// `ImageDownloadRedirectHandler`. See that protocol for more information. + public struct RedirectPayload { + + /// The related session data task when the redirect happens. It is + /// the current `SessionDataTask` which triggers this redirect. + public let task: SessionDataTask + + /// The response received during redirection. + public let response: HTTPURLResponse + + /// The request for redirection which can be modified. + public let newRequest: URLRequest + + /// A closure for being called with modified request. + public let completionHandler: (URLRequest?) -> Void + } +} diff --git a/Pods/Kingfisher/Sources/General/KFOptionsSetter.swift b/Pods/Kingfisher/Sources/General/KFOptionsSetter.swift new file mode 100644 index 0000000..979ed27 --- /dev/null +++ b/Pods/Kingfisher/Sources/General/KFOptionsSetter.swift @@ -0,0 +1,711 @@ +// +// KFOptionsSetter.swift +// Kingfisher +// +// Created by onevcat on 2020/12/22. +// +// Copyright (c) 2020 Wei Wang +// +// Permission is hereby granted, free of charge, to any person obtaining a copy +// of this software and associated documentation files (the "Software"), to deal +// in the Software without restriction, including without limitation the rights +// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +// copies of the Software, and to permit persons to whom the Software is +// furnished to do so, subject to the following conditions: +// +// The above copyright notice and this permission notice shall be included in +// all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN +// THE SOFTWARE. + +import Foundation +import CoreGraphics +#if os(macOS) +import AppKit +#else +import UIKit +#endif + +public protocol KFOptionSetter { + var options: KingfisherParsedOptionsInfo { get nonmutating set } + + var onFailureDelegate: Delegate { get } + var onSuccessDelegate: Delegate { get } + var onProgressDelegate: Delegate<(Int64, Int64), Void> { get } + + var delegateObserver: AnyObject { get } +} + +extension KF.Builder: KFOptionSetter { + public var delegateObserver: AnyObject { self } +} + +// MARK: - Life cycles +extension KFOptionSetter { + /// Sets the progress block to current builder. + /// - Parameter block: Called when the image downloading progress gets updated. If the response does not contain an + /// `expectedContentLength`, this block will not be called. If `block` is `nil`, the callback + /// will be reset. + /// - Returns: A `Self` value with changes applied. + public func onProgress(_ block: DownloadProgressBlock?) -> Self { + onProgressDelegate.delegate(on: delegateObserver) { (observer, result) in + block?(result.0, result.1) + } + return self + } + + /// Sets the the done block to current builder. + /// - Parameter block: Called when the image task successfully completes and the the image set is done. If `block` + /// is `nil`, the callback will be reset. + /// - Returns: A `KF.Builder` with changes applied. + public func onSuccess(_ block: ((RetrieveImageResult) -> Void)?) -> Self { + onSuccessDelegate.delegate(on: delegateObserver) { (observer, result) in + block?(result) + } + return self + } + + /// Sets the catch block to current builder. + /// - Parameter block: Called when an error happens during the image task. If `block` + /// is `nil`, the callback will be reset. + /// - Returns: A `KF.Builder` with changes applied. + public func onFailure(_ block: ((KingfisherError) -> Void)?) -> Self { + onFailureDelegate.delegate(on: delegateObserver) { (observer, error) in + block?(error) + } + return self + } +} + +// MARK: - Basic options settings. +extension KFOptionSetter { + /// Sets the target image cache for this task. + /// - Parameter cache: The target cache is about to be used for the task. + /// - Returns: A `Self` value with changes applied. + /// + /// Kingfisher will use the associated `ImageCache` object when handling related operations, + /// including trying to retrieve the cached images and store the downloaded image to it. + /// + public func targetCache(_ cache: ImageCache) -> Self { + options.targetCache = cache + return self + } + + /// Sets the target image cache to store the original downloaded image for this task. + /// - Parameter cache: The target cache is about to be used for storing the original downloaded image from the task. + /// - Returns: A `Self` value with changes applied. + /// + /// The `ImageCache` for storing and retrieving original images. If `originalCache` is + /// contained in the options, it will be preferred for storing and retrieving original images. + /// If there is no `.originalCache` in the options, `.targetCache` will be used to store original images. + /// + /// When using KingfisherManager to download and store an image, if `cacheOriginalImage` is + /// applied in the option, the original image will be stored to this `originalCache`. At the + /// same time, if a requested final image (with processor applied) cannot be found in `targetCache`, + /// Kingfisher will try to search the original image to check whether it is already there. If found, + /// it will be used and applied with the given processor. It is an optimization for not downloading + /// the same image for multiple times. + /// + public func originalCache(_ cache: ImageCache) -> Self { + options.originalCache = cache + return self + } + + /// Sets the downloader used to perform the image download task. + /// - Parameter downloader: The downloader which is about to be used for downloading. + /// - Returns: A `Self` value with changes applied. + /// + /// Kingfisher will use the set `ImageDownloader` object to download the requested images. + public func downloader(_ downloader: ImageDownloader) -> Self { + options.downloader = downloader + return self + } + + /// Sets the download priority for the image task. + /// - Parameter priority: The download priority of image download task. + /// - Returns: A `Self` value with changes applied. + /// + /// The `priority` value will be set as the priority of the image download task. The value for it should be + /// between 0.0~1.0. You can choose a value between `URLSessionTask.defaultPriority`, `URLSessionTask.lowPriority` + /// or `URLSessionTask.highPriority`. If this option not set, the default value (`URLSessionTask.defaultPriority`) + /// will be used. + public func downloadPriority(_ priority: Float) -> Self { + options.downloadPriority = priority + return self + } + + /// Sets whether Kingfisher should ignore the cache and try to start a download task for the image source. + /// - Parameter enabled: Enable the force refresh or not. + /// - Returns: A `Self` value with changes applied. + public func forceRefresh(_ enabled: Bool = true) -> Self { + options.forceRefresh = enabled + return self + } + + /// Sets whether Kingfisher should try to retrieve the image from memory cache first. If not found, it ignores the + /// disk cache and starts a download task for the image source. + /// - Parameter enabled: Enable the memory-only cache searching or not. + /// - Returns: A `Self` value with changes applied. + /// + /// This is useful when you want to display a changeable image behind the same url at the same app session, while + /// avoiding download it for multiple times. + public func fromMemoryCacheOrRefresh(_ enabled: Bool = true) -> Self { + options.fromMemoryCacheOrRefresh = enabled + return self + } + + /// Sets whether the image should only be cached in memory but not in disk. + /// - Parameter enabled: Whether the image should be only cache in memory or not. + /// - Returns: A `Self` value with changes applied. + public func cacheMemoryOnly(_ enabled: Bool = true) -> Self { + options.cacheMemoryOnly = enabled + return self + } + + /// Sets whether Kingfisher should wait for caching operation to be completed before calling the + /// `onSuccess` or `onFailure` block. + /// - Parameter enabled: Whether Kingfisher should wait for caching operation. + /// - Returns: A `Self` value with changes applied. + public func waitForCache(_ enabled: Bool = true) -> Self { + options.waitForCache = enabled + return self + } + + /// Sets whether Kingfisher should only try to retrieve the image from cache, but not from network. + /// - Parameter enabled: Whether Kingfisher should only try to retrieve the image from cache. + /// - Returns: A `Self` value with changes applied. + /// + /// If the image is not in cache, the image retrieving will fail with the + /// `KingfisherError.cacheError` with `.imageNotExisting` as its reason. + public func onlyFromCache(_ enabled: Bool = true) -> Self { + options.onlyFromCache = enabled + return self + } + + /// Sets whether the image should be decoded in a background thread before using. + /// - Parameter enabled: Whether the image should be decoded in a background thread before using. + /// - Returns: A `Self` value with changes applied. + /// + /// Setting to `true` will decode the downloaded image data and do a off-screen rendering to extract pixel + /// information in background. This can speed up display, but will cost more time and memory to prepare the image + /// for using. + public func backgroundDecode(_ enabled: Bool = true) -> Self { + options.backgroundDecode = enabled + return self + } + + /// Sets the callback queue which is used as the target queue of dispatch callbacks when retrieving images from + /// cache. If not set, Kingfisher will use main queue for callbacks. + /// - Parameter queue: The target queue which the cache retrieving callback will be invoked on. + /// - Returns: A `Self` value with changes applied. + /// + /// - Note: + /// This option does not affect the callbacks for UI related extension methods or `KFImage` result handlers. + /// You will always get the callbacks called from main queue. + public func callbackQueue(_ queue: CallbackQueue) -> Self { + options.callbackQueue = queue + return self + } + + /// Sets the scale factor value when converting retrieved data to an image. + /// - Parameter factor: The scale factor value. + /// - Returns: A `Self` value with changes applied. + /// + /// Specify the image scale, instead of your screen scale. You may need to set the correct scale when you dealing + /// with 2x or 3x retina images. Otherwise, Kingfisher will convert the data to image object at `scale` 1.0. + /// + public func scaleFactor(_ factor: CGFloat) -> Self { + options.scaleFactor = factor + return self + } + + /// Sets whether the original image should be cached even when the original image has been processed by any other + /// `ImageProcessor`s. + /// - Parameter enabled: Whether the original image should be cached. + /// - Returns: A `Self` value with changes applied. + /// + /// If set and an `ImageProcessor` is used, Kingfisher will try to cache both the final result and original + /// image. Kingfisher will have a chance to use the original image when another processor is applied to the same + /// resource, instead of downloading it again. You can use `.originalCache` to specify a cache or the original + /// images if necessary. + /// + /// The original image will be only cached to disk storage. + /// + public func cacheOriginalImage(_ enabled: Bool = true) -> Self { + options.cacheOriginalImage = enabled + return self + } + + /// Sets writing options for an original image on a first write + /// - Parameter writingOptions: Options to control the writing of data to a disk storage. + /// - Returns: A `Self` value with changes applied. + /// If set, options will be passed the store operation for a new files. + /// + /// This is useful if you want to implement file enctyption on first write - eg [.completeFileProtection] + /// + public func diskStoreWriteOptions(_ writingOptions: Data.WritingOptions) -> Self { + options.diskStoreWriteOptions = writingOptions + return self + } + + /// Sets whether the disk storage loading should happen in the same calling queue. + /// - Parameter enabled: Whether the disk storage loading should happen in the same calling queue. + /// - Returns: A `Self` value with changes applied. + /// + /// By default, disk storage file loading + /// happens in its own queue with an asynchronous dispatch behavior. Although it provides better non-blocking disk + /// loading performance, it also causes a flickering when you reload an image from disk, if the image view already + /// has an image set. + /// + /// Set this options will stop that flickering by keeping all loading in the same queue (typically the UI queue + /// if you are using Kingfisher's extension methods to set an image), with a tradeoff of loading performance. + /// + public func loadDiskFileSynchronously(_ enabled: Bool = true) -> Self { + options.loadDiskFileSynchronously = enabled + return self + } + + /// Sets a queue on which the image processing should happen. + /// - Parameter queue: The queue on which the image processing should happen. + /// - Returns: A `Self` value with changes applied. + /// + /// By default, Kingfisher uses a pre-defined serial + /// queue to process images. Use this option to change this behavior. For example, specify a `.mainCurrentOrAsync` + /// to let the image be processed in main queue to prevent a possible flickering (but with a possibility of + /// blocking the UI, especially if the processor needs a lot of time to run). + public func processingQueue(_ queue: CallbackQueue?) -> Self { + options.processingQueue = queue + return self + } + + /// Sets the alternative sources that will be used when loading of the original input `Source` fails. + /// - Parameter sources: The alternative sources will be used. + /// - Returns: A `Self` value with changes applied. + /// + /// Values of the `sources` array will be used to start a new image loading task if the previous task + /// fails due to an error. The image source loading process will stop as soon as a source is loaded successfully. + /// If all `sources` are used but the loading is still failing, an `imageSettingError` with + /// `alternativeSourcesExhausted` as its reason will be given out in the `catch` block. + /// + /// This is useful if you want to implement a fallback solution for setting image. + /// + /// User cancellation will not trigger the alternative source loading. + public func alternativeSources(_ sources: [Source]?) -> Self { + options.alternativeSources = sources + return self + } + + /// Sets a retry strategy that will be used when something gets wrong during the image retrieving. + /// - Parameter strategy: The provided strategy to define how the retrying should happen. + /// - Returns: A `Self` value with changes applied. + public func retry(_ strategy: RetryStrategy?) -> Self { + options.retryStrategy = strategy + return self + } + + /// Sets a retry strategy with a max retry count and retrying interval. + /// - Parameters: + /// - maxCount: The maximum count before the retry stops. + /// - interval: The time interval between each retry attempt. + /// - Returns: A `Self` value with changes applied. + /// + /// This defines the simplest retry strategy, which retry a failing request for several times, with some certain + /// interval between each time. For example, `.retry(maxCount: 3, interval: .second(3))` means attempt for at most + /// three times, and wait for 3 seconds if a previous retry attempt fails, then start a new attempt. + public func retry(maxCount: Int, interval: DelayRetryStrategy.Interval = .seconds(3)) -> Self { + let strategy = DelayRetryStrategy(maxRetryCount: maxCount, retryInterval: interval) + options.retryStrategy = strategy + return self + } + + /// Sets the `Source` should be loaded when user enables Low Data Mode and the original source fails with an + /// `NSURLErrorNetworkUnavailableReason.constrained` error. + /// - Parameter source: The `Source` will be loaded under low data mode. + /// - Returns: A `Self` value with changes applied. + /// + /// When this option is set, the + /// `allowsConstrainedNetworkAccess` property of the request for the original source will be set to `false` and the + /// `Source` in associated value will be used to retrieve the image for low data mode. Usually, you can provide a + /// low-resolution version of your image or a local image provider to display a placeholder. + /// + /// If not set or the `source` is `nil`, the device Low Data Mode will be ignored and the original source will + /// be loaded following the system default behavior, in a normal way. + public func lowDataModeSource(_ source: Source?) -> Self { + options.lowDataModeSource = source + return self + } + + /// Sets whether the image setting for an image view should happen with transition even when retrieved from cache. + /// - Parameter enabled: Enable the force transition or not. + /// - Returns: A `Self` with changes applied. + public func forceTransition(_ enabled: Bool = true) -> Self { + options.forceTransition = enabled + return self + } + + /// Sets the image that will be used if an image retrieving task fails. + /// - Parameter image: The image that will be used when something goes wrong. + /// - Returns: A `Self` with changes applied. + /// + /// If set and an image retrieving error occurred Kingfisher will set provided image (or empty) + /// in place of requested one. It's useful when you don't want to show placeholder + /// during loading time but wants to use some default image when requests will be failed. + /// + public func onFailureImage(_ image: KFCrossPlatformImage?) -> Self { + options.onFailureImage = .some(image) + return self + } +} + +// MARK: - Request Modifier +extension KFOptionSetter { + /// Sets an `ImageDownloadRequestModifier` to change the image download request before it being sent. + /// - Parameter modifier: The modifier will be used to change the request before it being sent. + /// - Returns: A `Self` value with changes applied. + /// + /// This is the last chance you can modify the image download request. You can modify the request for some + /// customizing purpose, such as adding auth token to the header, do basic HTTP auth or something like url mapping. + /// + public func requestModifier(_ modifier: AsyncImageDownloadRequestModifier) -> Self { + options.requestModifier = modifier + return self + } + + /// Sets a block to change the image download request before it being sent. + /// - Parameter modifyBlock: The modifying block will be called to change the request before it being sent. + /// - Returns: A `Self` value with changes applied. + /// + /// This is the last chance you can modify the image download request. You can modify the request for some + /// customizing purpose, such as adding auth token to the header, do basic HTTP auth or something like url mapping. + /// + public func requestModifier(_ modifyBlock: @escaping (inout URLRequest) -> Void) -> Self { + options.requestModifier = AnyModifier { r -> URLRequest? in + var request = r + modifyBlock(&request) + return request + } + return self + } +} + +// MARK: - Redirect Handler +extension KFOptionSetter { + /// The `ImageDownloadRedirectHandler` argument will be used to change the request before redirection. + /// This is the possibility you can modify the image download request during redirect. You can modify the request for + /// some customizing purpose, such as adding auth token to the header, do basic HTTP auth or something like url + /// mapping. + /// The original redirection request will be sent without any modification by default. + /// - Parameter handler: The handler will be used for redirection. + /// - Returns: A `Self` value with changes applied. + public func redirectHandler(_ handler: ImageDownloadRedirectHandler) -> Self { + options.redirectHandler = handler + return self + } + + /// The `block` will be used to change the request before redirection. + /// This is the possibility you can modify the image download request during redirect. You can modify the request for + /// some customizing purpose, such as adding auth token to the header, do basic HTTP auth or something like url + /// mapping. + /// The original redirection request will be sent without any modification by default. + /// - Parameter block: The block will be used for redirection. + /// - Returns: A `Self` value with changes applied. + public func redirectHandler(_ block: @escaping (KF.RedirectPayload) -> Void) -> Self { + let redirectHandler = AnyRedirectHandler { (task, response, request, handler) in + let payload = KF.RedirectPayload( + task: task, response: response, newRequest: request, completionHandler: handler + ) + block(payload) + } + options.redirectHandler = redirectHandler + return self + } +} + +// MARK: - Processor +extension KFOptionSetter { + + /// Sets an image processor for the image task. It replaces the current image processor settings. + /// + /// - Parameter processor: The processor you want to use to process the image after it is downloaded. + /// - Returns: A `Self` value with changes applied. + /// + /// - Note: + /// To append a processor to current ones instead of replacing them all, use `appendProcessor(_:)`. + public func setProcessor(_ processor: ImageProcessor) -> Self { + options.processor = processor + return self + } + + /// Sets an array of image processors for the image task. It replaces the current image processor settings. + /// - Parameter processors: An array of processors. The processors inside this array will be concatenated one by one + /// to form a processor pipeline. + /// - Returns: A `Self` value with changes applied. + /// + /// - Note: To append processors to current ones instead of replacing them all, concatenate them by `|>`, then use + /// `appendProcessor(_:)`. + public func setProcessors(_ processors: [ImageProcessor]) -> Self { + switch processors.count { + case 0: + options.processor = DefaultImageProcessor.default + case 1...: + options.processor = processors.dropFirst().reduce(processors[0]) { $0 |> $1 } + default: + assertionFailure("Never happen") + } + return self + } + + /// Appends a processor to the current set processors. + /// - Parameter processor: The processor which will be appended to current processor settings. + /// - Returns: A `Self` value with changes applied. + public func appendProcessor(_ processor: ImageProcessor) -> Self { + options.processor = options.processor |> processor + return self + } + + /// Appends a `RoundCornerImageProcessor` to current processors. + /// - Parameters: + /// - radius: The radius will be applied in processing. Specify a certain point value with `.point`, or a fraction + /// of the target image with `.widthFraction`. or `.heightFraction`. For example, given a square image + /// with width and height equals, `.widthFraction(0.5)` means use half of the length of size and makes + /// the final image a round one. + /// - targetSize: Target size of output image should be. If `nil`, the image will keep its original size after processing. + /// - corners: The target corners which will be applied rounding. + /// - backgroundColor: Background color of the output image. If `nil`, it will use a transparent background. + /// - Returns: A `Self` value with changes applied. + public func roundCorner( + radius: Radius, + targetSize: CGSize? = nil, + roundingCorners corners: RectCorner = .all, + backgroundColor: KFCrossPlatformColor? = nil + ) -> Self + { + let processor = RoundCornerImageProcessor( + radius: radius, + targetSize: targetSize, + roundingCorners: corners, + backgroundColor: backgroundColor + ) + return appendProcessor(processor) + } + + /// Appends a `BlurImageProcessor` to current processors. + /// - Parameter radius: Blur radius for the simulated Gaussian blur. + /// - Returns: A `Self` value with changes applied. + public func blur(radius: CGFloat) -> Self { + appendProcessor( + BlurImageProcessor(blurRadius: radius) + ) + } + + /// Appends a `OverlayImageProcessor` to current processors. + /// - Parameters: + /// - color: Overlay color will be used to overlay the input image. + /// - fraction: Fraction will be used when overlay the color to image. + /// - Returns: A `Self` value with changes applied. + public func overlay(color: KFCrossPlatformColor, fraction: CGFloat = 0.5) -> Self { + appendProcessor( + OverlayImageProcessor(overlay: color, fraction: fraction) + ) + } + + /// Appends a `TintImageProcessor` to current processors. + /// - Parameter color: Tint color will be used to tint the input image. + /// - Returns: A `Self` value with changes applied. + public func tint(color: KFCrossPlatformColor) -> Self { + appendProcessor( + TintImageProcessor(tint: color) + ) + } + + /// Appends a `BlackWhiteProcessor` to current processors. + /// - Returns: A `Self` value with changes applied. + public func blackWhite() -> Self { + appendProcessor( + BlackWhiteProcessor() + ) + } + + /// Appends a `CroppingImageProcessor` to current processors. + /// - Parameters: + /// - size: Target size of output image should be. + /// - anchor: Anchor point from which the output size should be calculate. The anchor point is consisted by two + /// values between 0.0 and 1.0. It indicates a related point in current image. + /// See `CroppingImageProcessor.init(size:anchor:)` for more. + /// - Returns: A `Self` value with changes applied. + public func cropping(size: CGSize, anchor: CGPoint = .init(x: 0.5, y: 0.5)) -> Self { + appendProcessor( + CroppingImageProcessor(size: size, anchor: anchor) + ) + } + + /// Appends a `DownsamplingImageProcessor` to current processors. + /// + /// Compared to `ResizingImageProcessor`, the `DownsamplingImageProcessor` does not render the original images and + /// then resize it. Instead, it downsamples the input data directly to a thumbnail image. So it is a more efficient + /// than `ResizingImageProcessor`. Prefer to use `DownsamplingImageProcessor` as possible + /// as you can than the `ResizingImageProcessor`. + /// + /// Only CG-based images are supported. Animated images (like GIF) is not supported. + /// + /// - Parameter size: Target size of output image should be. It should be smaller than the size of input image. + /// If it is larger, the result image will be the same size of input data without downsampling. + /// - Returns: A `Self` value with changes applied. + public func downsampling(size: CGSize) -> Self { + let processor = DownsamplingImageProcessor(size: size) + if options.processor == DefaultImageProcessor.default { + return setProcessor(processor) + } else { + return appendProcessor(processor) + } + } + + + /// Appends a `ResizingImageProcessor` to current processors. + /// + /// If you need to resize a data represented image to a smaller size, use `DownsamplingImageProcessor` + /// instead, which is more efficient and uses less memory. + /// + /// - Parameters: + /// - referenceSize: The reference size for resizing operation in point. + /// - mode: Target content mode of output image should be. Default is `.none`. + /// - Returns: A `Self` value with changes applied. + public func resizing(referenceSize: CGSize, mode: ContentMode = .none) -> Self { + appendProcessor( + ResizingImageProcessor(referenceSize: referenceSize, mode: mode) + ) + } +} + +// MARK: - Cache Serializer +extension KFOptionSetter { + + /// Uses a given `CacheSerializer` to convert some data to an image object for retrieving from disk cache or vice + /// versa for storing to disk cache. + /// - Parameter cacheSerializer: The `CacheSerializer` which will be used. + /// - Returns: A `Self` value with changes applied. + public func serialize(by cacheSerializer: CacheSerializer) -> Self { + options.cacheSerializer = cacheSerializer + return self + } + + /// Uses a given format to serializer the image data to disk. It converts the image object to the give data format. + /// - Parameters: + /// - format: The desired data encoding format when store the image on disk. + /// - jpegCompressionQuality: If the format is `.JPEG`, it specify the compression quality when converting the + /// image to a JPEG data. Otherwise, it is ignored. + /// - Returns: A `Self` value with changes applied. + public func serialize(as format: ImageFormat, jpegCompressionQuality: CGFloat? = nil) -> Self { + let cacheSerializer: FormatIndicatedCacheSerializer + switch format { + case .JPEG: + cacheSerializer = .jpeg(compressionQuality: jpegCompressionQuality ?? 1.0) + case .PNG: + cacheSerializer = .png + case .GIF: + cacheSerializer = .gif + case .unknown: + cacheSerializer = .png + } + options.cacheSerializer = cacheSerializer + return self + } +} + +// MARK: - Image Modifier +extension KFOptionSetter { + + /// Sets an `ImageModifier` to the image task. Use this to modify the fetched image object properties if needed. + /// + /// If the image was fetched directly from the downloader, the modifier will run directly after the + /// `ImageProcessor`. If the image is being fetched from a cache, the modifier will run after the `CacheSerializer`. + /// - Parameter modifier: The `ImageModifier` which will be used to modify the image object. + /// - Returns: A `Self` value with changes applied. + public func imageModifier(_ modifier: ImageModifier?) -> Self { + options.imageModifier = modifier + return self + } + + /// Sets a block to modify the image object. Use this to modify the fetched image object properties if needed. + /// + /// If the image was fetched directly from the downloader, the modifier block will run directly after the + /// `ImageProcessor`. If the image is being fetched from a cache, the modifier will run after the `CacheSerializer`. + /// + /// - Parameter block: The block which is used to modify the image object. + /// - Returns: A `Self` value with changes applied. + public func imageModifier(_ block: @escaping (inout KFCrossPlatformImage) throws -> Void) -> Self { + let modifier = AnyImageModifier { image -> KFCrossPlatformImage in + var image = image + try block(&image) + return image + } + options.imageModifier = modifier + return self + } +} + + +// MARK: - Cache Expiration +extension KFOptionSetter { + + /// Sets the expiration setting for memory cache of this image task. + /// + /// By default, the underlying `MemoryStorage.Backend` uses the + /// expiration in its config for all items. If set, the `MemoryStorage.Backend` will use this value to overwrite + /// the config setting for this caching item. + /// + /// - Parameter expiration: The expiration setting used in cache storage. + /// - Returns: A `Self` value with changes applied. + public func memoryCacheExpiration(_ expiration: StorageExpiration?) -> Self { + options.memoryCacheExpiration = expiration + return self + } + + /// Sets the expiration extending setting for memory cache. The item expiration time will be incremented by this + /// value after access. + /// + /// By default, the underlying `MemoryStorage.Backend` uses the initial cache expiration as extending + /// value: .cacheTime. + /// + /// To disable extending option at all, sets `.none` to it. + /// + /// - Parameter extending: The expiration extending setting used in cache storage. + /// - Returns: A `Self` value with changes applied. + public func memoryCacheAccessExtending(_ extending: ExpirationExtending) -> Self { + options.memoryCacheAccessExtendingExpiration = extending + return self + } + + /// Sets the expiration setting for disk cache of this image task. + /// + /// By default, the underlying `DiskStorage.Backend` uses the expiration in its config for all items. If set, + /// the `DiskStorage.Backend` will use this value to overwrite the config setting for this caching item. + /// + /// - Parameter expiration: The expiration setting used in cache storage. + /// - Returns: A `Self` value with changes applied. + public func diskCacheExpiration(_ expiration: StorageExpiration?) -> Self { + options.diskCacheExpiration = expiration + return self + } + + /// Sets the expiration extending setting for disk cache. The item expiration time will be incremented by this + /// value after access. + /// + /// By default, the underlying `DiskStorage.Backend` uses the initial cache expiration as extending + /// value: .cacheTime. + /// + /// To disable extending option at all, sets `.none` to it. + /// + /// - Parameter extending: The expiration extending setting used in cache storage. + /// - Returns: A `Self` value with changes applied. + public func diskCacheAccessExtending(_ extending: ExpirationExtending) -> Self { + options.diskCacheAccessExtendingExpiration = extending + return self + } +} diff --git a/Pods/Kingfisher/Sources/General/Kingfisher.swift b/Pods/Kingfisher/Sources/General/Kingfisher.swift new file mode 100644 index 0000000..f875e2a --- /dev/null +++ b/Pods/Kingfisher/Sources/General/Kingfisher.swift @@ -0,0 +1,106 @@ +// +// Kingfisher.swift +// Kingfisher +// +// Created by Wei Wang on 16/9/14. +// +// Copyright (c) 2019 Wei Wang +// +// Permission is hereby granted, free of charge, to any person obtaining a copy +// of this software and associated documentation files (the "Software"), to deal +// in the Software without restriction, including without limitation the rights +// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +// copies of the Software, and to permit persons to whom the Software is +// furnished to do so, subject to the following conditions: +// +// The above copyright notice and this permission notice shall be included in +// all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN +// THE SOFTWARE. + +import Foundation +import ImageIO + +#if os(macOS) +import AppKit +public typealias KFCrossPlatformImage = NSImage +public typealias KFCrossPlatformView = NSView +public typealias KFCrossPlatformColor = NSColor +public typealias KFCrossPlatformImageView = NSImageView +public typealias KFCrossPlatformButton = NSButton +#else +import UIKit +public typealias KFCrossPlatformImage = UIImage +public typealias KFCrossPlatformColor = UIColor +#if !os(watchOS) +public typealias KFCrossPlatformImageView = UIImageView +public typealias KFCrossPlatformView = UIView +public typealias KFCrossPlatformButton = UIButton +#if canImport(TVUIKit) +import TVUIKit +#endif +#if canImport(CarPlay) && !targetEnvironment(macCatalyst) +import CarPlay +#endif +#else +import WatchKit +#endif +#endif + +/// Wrapper for Kingfisher compatible types. This type provides an extension point for +/// convenience methods in Kingfisher. +public struct KingfisherWrapper { + public let base: Base + public init(_ base: Base) { + self.base = base + } +} + +/// Represents an object type that is compatible with Kingfisher. You can use `kf` property to get a +/// value in the namespace of Kingfisher. +public protocol KingfisherCompatible: AnyObject { } + +/// Represents a value type that is compatible with Kingfisher. You can use `kf` property to get a +/// value in the namespace of Kingfisher. +public protocol KingfisherCompatibleValue {} + +extension KingfisherCompatible { + /// Gets a namespace holder for Kingfisher compatible types. + public var kf: KingfisherWrapper { + get { return KingfisherWrapper(self) } + set { } + } +} + +extension KingfisherCompatibleValue { + /// Gets a namespace holder for Kingfisher compatible types. + public var kf: KingfisherWrapper { + get { return KingfisherWrapper(self) } + set { } + } +} + +extension KFCrossPlatformImage: KingfisherCompatible { } +#if !os(watchOS) +extension KFCrossPlatformImageView: KingfisherCompatible { } +extension KFCrossPlatformButton: KingfisherCompatible { } +extension NSTextAttachment: KingfisherCompatible { } +#else +extension WKInterfaceImage: KingfisherCompatible { } +#endif + +#if os(tvOS) && canImport(TVUIKit) +@available(tvOS 12.0, *) +extension TVMonogramView: KingfisherCompatible { } +#endif + +#if canImport(CarPlay) && !targetEnvironment(macCatalyst) +@available(iOS 14.0, *) +extension CPListItem: KingfisherCompatible { } +#endif diff --git a/Pods/Kingfisher/Sources/General/KingfisherError.swift b/Pods/Kingfisher/Sources/General/KingfisherError.swift new file mode 100644 index 0000000..c6e7914 --- /dev/null +++ b/Pods/Kingfisher/Sources/General/KingfisherError.swift @@ -0,0 +1,474 @@ +// +// KingfisherError.swift +// Kingfisher +// +// Created by onevcat on 2018/09/26. +// +// Copyright (c) 2019 Wei Wang +// +// Permission is hereby granted, free of charge, to any person obtaining a copy +// of this software and associated documentation files (the "Software"), to deal +// in the Software without restriction, including without limitation the rights +// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +// copies of the Software, and to permit persons to whom the Software is +// furnished to do so, subject to the following conditions: +// +// The above copyright notice and this permission notice shall be included in +// all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN +// THE SOFTWARE. + +import Foundation +#if os(macOS) +import AppKit +#else +import UIKit +#endif + +extension Never {} + +/// Represents all the errors which can happen in Kingfisher framework. +/// Kingfisher related methods always throw a `KingfisherError` or invoke the callback with `KingfisherError` +/// as its error type. To handle errors from Kingfisher, you switch over the error to get a reason catalog, +/// then switch over the reason to know error detail. +public enum KingfisherError: Error { + + // MARK: Error Reason Types + + /// Represents the error reason during networking request phase. + /// + /// - emptyRequest: The request is empty. Code 1001. + /// - invalidURL: The URL of request is invalid. Code 1002. + /// - taskCancelled: The downloading task is cancelled by user. Code 1003. + public enum RequestErrorReason { + + /// The request is empty. Code 1001. + case emptyRequest + + /// The URL of request is invalid. Code 1002. + /// - request: The request is tend to be sent but its URL is invalid. + case invalidURL(request: URLRequest) + + /// The downloading task is cancelled by user. Code 1003. + /// - task: The session data task which is cancelled. + /// - token: The cancel token which is used for cancelling the task. + case taskCancelled(task: SessionDataTask, token: SessionDataTask.CancelToken) + } + + /// Represents the error reason during networking response phase. + /// + /// - invalidURLResponse: The response is not a valid URL response. Code 2001. + /// - invalidHTTPStatusCode: The response contains an invalid HTTP status code. Code 2002. + /// - URLSessionError: An error happens in the system URL session. Code 2003. + /// - dataModifyingFailed: Data modifying fails on returning a valid data. Code 2004. + /// - noURLResponse: The task is done but no URL response found. Code 2005. + public enum ResponseErrorReason { + + /// The response is not a valid URL response. Code 2001. + /// - response: The received invalid URL response. + /// The response is expected to be an HTTP response, but it is not. + case invalidURLResponse(response: URLResponse) + + /// The response contains an invalid HTTP status code. Code 2002. + /// - Note: + /// By default, status code 200..<400 is recognized as valid. You can override + /// this behavior by conforming to the `ImageDownloaderDelegate`. + /// - response: The received response. + case invalidHTTPStatusCode(response: HTTPURLResponse) + + /// An error happens in the system URL session. Code 2003. + /// - error: The underlying URLSession error object. + case URLSessionError(error: Error) + + /// Data modifying fails on returning a valid data. Code 2004. + /// - task: The failed task. + case dataModifyingFailed(task: SessionDataTask) + + /// The task is done but no URL response found. Code 2005. + /// - task: The failed task. + case noURLResponse(task: SessionDataTask) + + /// The task is cancelled by `ImageDownloaderDelegate` due to the `.cancel` response disposition is + /// specified by the delegate method. Code 2006. + case cancelledByDelegate(response: URLResponse) + } + + /// Represents the error reason during Kingfisher caching system. + /// + /// - fileEnumeratorCreationFailed: Cannot create a file enumerator for a certain disk URL. Code 3001. + /// - invalidFileEnumeratorContent: Cannot get correct file contents from a file enumerator. Code 3002. + /// - invalidURLResource: The file at target URL exists, but its URL resource is unavailable. Code 3003. + /// - cannotLoadDataFromDisk: The file at target URL exists, but the data cannot be loaded from it. Code 3004. + /// - cannotCreateDirectory: Cannot create a folder at a given path. Code 3005. + /// - imageNotExisting: The requested image does not exist in cache. Code 3006. + /// - cannotConvertToData: Cannot convert an object to data for storing. Code 3007. + /// - cannotSerializeImage: Cannot serialize an image to data for storing. Code 3008. + /// - cannotCreateCacheFile: Cannot create the cache file at a certain fileURL under a key. Code 3009. + /// - cannotSetCacheFileAttribute: Cannot set file attributes to a cached file. Code 3010. + public enum CacheErrorReason { + + /// Cannot create a file enumerator for a certain disk URL. Code 3001. + /// - url: The target disk URL from which the file enumerator should be created. + case fileEnumeratorCreationFailed(url: URL) + + /// Cannot get correct file contents from a file enumerator. Code 3002. + /// - url: The target disk URL from which the content of a file enumerator should be got. + case invalidFileEnumeratorContent(url: URL) + + /// The file at target URL exists, but its URL resource is unavailable. Code 3003. + /// - error: The underlying error thrown by file manager. + /// - key: The key used to getting the resource from cache. + /// - url: The disk URL where the target cached file exists. + case invalidURLResource(error: Error, key: String, url: URL) + + /// The file at target URL exists, but the data cannot be loaded from it. Code 3004. + /// - url: The disk URL where the target cached file exists. + /// - error: The underlying error which describes why this error happens. + case cannotLoadDataFromDisk(url: URL, error: Error) + + /// Cannot create a folder at a given path. Code 3005. + /// - path: The disk path where the directory creating operation fails. + /// - error: The underlying error which describes why this error happens. + case cannotCreateDirectory(path: String, error: Error) + + /// The requested image does not exist in cache. Code 3006. + /// - key: Key of the requested image in cache. + case imageNotExisting(key: String) + + /// Cannot convert an object to data for storing. Code 3007. + /// - object: The object which needs be convert to data. + case cannotConvertToData(object: Any, error: Error) + + /// Cannot serialize an image to data for storing. Code 3008. + /// - image: The input image needs to be serialized to cache. + /// - original: The original image data, if exists. + /// - serializer: The `CacheSerializer` used for the image serializing. + case cannotSerializeImage(image: KFCrossPlatformImage?, original: Data?, serializer: CacheSerializer) + + /// Cannot create the cache file at a certain fileURL under a key. Code 3009. + /// - fileURL: The url where the cache file should be created. + /// - key: The cache key used for the cache. When caching a file through `KingfisherManager` and Kingfisher's + /// extension method, it is the resolved cache key based on your input `Source` and the image processors. + /// - data: The data to be cached. + /// - error: The underlying error originally thrown by Foundation when writing the `data` to the disk file at + /// `fileURL`. + case cannotCreateCacheFile(fileURL: URL, key: String, data: Data, error: Error) + + /// Cannot set file attributes to a cached file. Code 3010. + /// - filePath: The path of target cache file. + /// - attributes: The file attribute to be set to the target file. + /// - error: The underlying error originally thrown by Foundation when setting the `attributes` to the disk + /// file at `filePath`. + case cannotSetCacheFileAttribute(filePath: String, attributes: [FileAttributeKey : Any], error: Error) + + /// The disk storage of cache is not ready. Code 3011. + /// + /// This is usually due to extremely lack of space on disk storage, and + /// Kingfisher failed even when creating the cache folder. The disk storage will be in unusable state. Normally, + /// ask user to free some spaces and restart the app to make the disk storage work again. + /// - cacheURL: The intended URL which should be the storage folder. + case diskStorageIsNotReady(cacheURL: URL) + } + + + /// Represents the error reason during image processing phase. + /// + /// - processingFailed: Image processing fails. There is no valid output image from the processor. Code 4001. + public enum ProcessorErrorReason { + /// Image processing fails. There is no valid output image from the processor. Code 4001. + /// - processor: The `ImageProcessor` used to process the image or its data in `item`. + /// - item: The image or its data content. + case processingFailed(processor: ImageProcessor, item: ImageProcessItem) + } + + /// Represents the error reason during image setting in a view related class. + /// + /// - emptySource: The input resource is empty or `nil`. Code 5001. + /// - notCurrentSourceTask: The source task is finished, but it is not the one expected now. Code 5002. + /// - dataProviderError: An error happens during getting data from an `ImageDataProvider`. Code 5003. + public enum ImageSettingErrorReason { + + /// The input resource is empty or `nil`. Code 5001. + case emptySource + + /// The resource task is finished, but it is not the one expected now. This usually happens when you set another + /// resource on the view without cancelling the current on-going one. The previous setting task will fail with + /// this `.notCurrentSourceTask` error when a result got, regardless of it being successful or not for that task. + /// The result of this original task is contained in the associated value. + /// Code 5002. + /// - result: The `RetrieveImageResult` if the source task is finished without problem. `nil` if an error + /// happens. + /// - error: The `Error` if an issue happens during image setting task. `nil` if the task finishes without + /// problem. + /// - source: The original source value of the task. + case notCurrentSourceTask(result: RetrieveImageResult?, error: Error?, source: Source) + + /// An error happens during getting data from an `ImageDataProvider`. Code 5003. + case dataProviderError(provider: ImageDataProvider, error: Error) + + /// No more alternative `Source` can be used in current loading process. It means that the + /// `.alternativeSources` are used and Kingfisher tried to recovery from the original error, but still + /// fails for all the given alternative sources. The associated value holds all the errors encountered during + /// the load process, including the original source loading error and all the alternative sources errors. + /// Code 5004. + case alternativeSourcesExhausted([PropagationError]) + } + + // MARK: Member Cases + + /// Represents the error reason during networking request phase. + case requestError(reason: RequestErrorReason) + /// Represents the error reason during networking response phase. + case responseError(reason: ResponseErrorReason) + /// Represents the error reason during Kingfisher caching system. + case cacheError(reason: CacheErrorReason) + /// Represents the error reason during image processing phase. + case processorError(reason: ProcessorErrorReason) + /// Represents the error reason during image setting in a view related class. + case imageSettingError(reason: ImageSettingErrorReason) + + // MARK: Helper Properties & Methods + + /// Helper property to check whether this error is a `RequestErrorReason.taskCancelled` or not. + public var isTaskCancelled: Bool { + if case .requestError(reason: .taskCancelled) = self { + return true + } + return false + } + + /// Helper method to check whether this error is a `ResponseErrorReason.invalidHTTPStatusCode` and the + /// associated value is a given status code. + /// + /// - Parameter code: The given status code. + /// - Returns: If `self` is a `ResponseErrorReason.invalidHTTPStatusCode` error + /// and its status code equals to `code`, `true` is returned. Otherwise, `false`. + public func isInvalidResponseStatusCode(_ code: Int) -> Bool { + if case .responseError(reason: .invalidHTTPStatusCode(let response)) = self { + return response.statusCode == code + } + return false + } + + public var isInvalidResponseStatusCode: Bool { + if case .responseError(reason: .invalidHTTPStatusCode) = self { + return true + } + return false + } + + /// Helper property to check whether this error is a `ImageSettingErrorReason.notCurrentSourceTask` or not. + /// When a new image setting task starts while the old one is still running, the new task identifier will be + /// set and the old one is overwritten. A `.notCurrentSourceTask` error will be raised when the old task finishes + /// to let you know the setting process finishes with a certain result, but the image view or button is not set. + public var isNotCurrentTask: Bool { + if case .imageSettingError(reason: .notCurrentSourceTask(_, _, _)) = self { + return true + } + return false + } + + var isLowDataModeConstrained: Bool { + if #available(macOS 10.15, iOS 13.0, watchOS 6.0, tvOS 13.0, *), + case .responseError(reason: .URLSessionError(let sessionError)) = self, + let urlError = sessionError as? URLError, + urlError.networkUnavailableReason == .constrained + { + return true + } + return false + } + +} + +// MARK: - LocalizedError Conforming +extension KingfisherError: LocalizedError { + + /// A localized message describing what error occurred. + public var errorDescription: String? { + switch self { + case .requestError(let reason): return reason.errorDescription + case .responseError(let reason): return reason.errorDescription + case .cacheError(let reason): return reason.errorDescription + case .processorError(let reason): return reason.errorDescription + case .imageSettingError(let reason): return reason.errorDescription + } + } +} + + +// MARK: - CustomNSError Conforming +extension KingfisherError: CustomNSError { + + /// The error domain of `KingfisherError`. All errors from Kingfisher is under this domain. + public static let domain = "com.onevcat.Kingfisher.Error" + + /// The error code within the given domain. + public var errorCode: Int { + switch self { + case .requestError(let reason): return reason.errorCode + case .responseError(let reason): return reason.errorCode + case .cacheError(let reason): return reason.errorCode + case .processorError(let reason): return reason.errorCode + case .imageSettingError(let reason): return reason.errorCode + } + } +} + +extension KingfisherError.RequestErrorReason { + var errorDescription: String? { + switch self { + case .emptyRequest: + return "The request is empty or `nil`." + case .invalidURL(let request): + return "The request contains an invalid or empty URL. Request: \(request)." + case .taskCancelled(let task, let token): + return "The session task was cancelled. Task: \(task), cancel token: \(token)." + } + } + + var errorCode: Int { + switch self { + case .emptyRequest: return 1001 + case .invalidURL: return 1002 + case .taskCancelled: return 1003 + } + } +} + +extension KingfisherError.ResponseErrorReason { + var errorDescription: String? { + switch self { + case .invalidURLResponse(let response): + return "The URL response is invalid: \(response)" + case .invalidHTTPStatusCode(let response): + return "The HTTP status code in response is invalid. Code: \(response.statusCode), response: \(response)." + case .URLSessionError(let error): + return "A URL session error happened. The underlying error: \(error)" + case .dataModifyingFailed(let task): + return "The data modifying delegate returned `nil` for the downloaded data. Task: \(task)." + case .noURLResponse(let task): + return "No URL response received. Task: \(task)." + case .cancelledByDelegate(let response): + return "The downloading task is cancelled by the downloader delegate. Response: \(response)." + + } + } + + var errorCode: Int { + switch self { + case .invalidURLResponse: return 2001 + case .invalidHTTPStatusCode: return 2002 + case .URLSessionError: return 2003 + case .dataModifyingFailed: return 2004 + case .noURLResponse: return 2005 + case .cancelledByDelegate: return 2006 + } + } +} + +extension KingfisherError.CacheErrorReason { + var errorDescription: String? { + switch self { + case .fileEnumeratorCreationFailed(let url): + return "Cannot create file enumerator for URL: \(url)." + case .invalidFileEnumeratorContent(let url): + return "Cannot get contents from the file enumerator at URL: \(url)." + case .invalidURLResource(let error, let key, let url): + return "Cannot get URL resource values or data for the given URL: \(url). " + + "Cache key: \(key). Underlying error: \(error)" + case .cannotLoadDataFromDisk(let url, let error): + return "Cannot load data from disk at URL: \(url). Underlying error: \(error)" + case .cannotCreateDirectory(let path, let error): + return "Cannot create directory at given path: Path: \(path). Underlying error: \(error)" + case .imageNotExisting(let key): + return "The image is not in cache, but you requires it should only be " + + "from cache by enabling the `.onlyFromCache` option. Key: \(key)." + case .cannotConvertToData(let object, let error): + return "Cannot convert the input object to a `Data` object when storing it to disk cache. " + + "Object: \(object). Underlying error: \(error)" + case .cannotSerializeImage(let image, let originalData, let serializer): + return "Cannot serialize an image due to the cache serializer returning `nil`. " + + "Image: \(String(describing:image)), original data: \(String(describing: originalData)), " + + "serializer: \(serializer)." + case .cannotCreateCacheFile(let fileURL, let key, let data, let error): + return "Cannot create cache file at url: \(fileURL), key: \(key), data length: \(data.count). " + + "Underlying foundation error: \(error)." + case .cannotSetCacheFileAttribute(let filePath, let attributes, let error): + return "Cannot set file attribute for the cache file at path: \(filePath), attributes: \(attributes)." + + "Underlying foundation error: \(error)." + case .diskStorageIsNotReady(let cacheURL): + return "The disk storage is not ready to use yet at URL: '\(cacheURL)'. " + + "This is usually caused by extremely lack of disk space. Ask users to free up some space and restart the app." + } + } + + var errorCode: Int { + switch self { + case .fileEnumeratorCreationFailed: return 3001 + case .invalidFileEnumeratorContent: return 3002 + case .invalidURLResource: return 3003 + case .cannotLoadDataFromDisk: return 3004 + case .cannotCreateDirectory: return 3005 + case .imageNotExisting: return 3006 + case .cannotConvertToData: return 3007 + case .cannotSerializeImage: return 3008 + case .cannotCreateCacheFile: return 3009 + case .cannotSetCacheFileAttribute: return 3010 + case .diskStorageIsNotReady: return 3011 + } + } +} + +extension KingfisherError.ProcessorErrorReason { + var errorDescription: String? { + switch self { + case .processingFailed(let processor, let item): + return "Processing image failed. Processor: \(processor). Processing item: \(item)." + } + } + + var errorCode: Int { + switch self { + case .processingFailed: return 4001 + } + } +} + +extension KingfisherError.ImageSettingErrorReason { + var errorDescription: String? { + switch self { + case .emptySource: + return "The input resource is empty." + case .notCurrentSourceTask(let result, let error, let resource): + if let result = result { + return "Retrieving resource succeeded, but this source is " + + "not the one currently expected. Result: \(result). Resource: \(resource)." + } else if let error = error { + return "Retrieving resource failed, and this resource is " + + "not the one currently expected. Error: \(error). Resource: \(resource)." + } else { + return nil + } + case .dataProviderError(let provider, let error): + return "Image data provider fails to provide data. Provider: \(provider), error: \(error)" + case .alternativeSourcesExhausted(let errors): + return "Image setting from alternaive sources failed: \(errors)" + } + } + + var errorCode: Int { + switch self { + case .emptySource: return 5001 + case .notCurrentSourceTask: return 5002 + case .dataProviderError: return 5003 + case .alternativeSourcesExhausted: return 5004 + } + } +} diff --git a/Pods/Kingfisher/Sources/General/KingfisherManager.swift b/Pods/Kingfisher/Sources/General/KingfisherManager.swift new file mode 100644 index 0000000..1979a8f --- /dev/null +++ b/Pods/Kingfisher/Sources/General/KingfisherManager.swift @@ -0,0 +1,807 @@ +// +// KingfisherManager.swift +// Kingfisher +// +// Created by Wei Wang on 15/4/6. +// +// Copyright (c) 2019 Wei Wang +// +// Permission is hereby granted, free of charge, to any person obtaining a copy +// of this software and associated documentation files (the "Software"), to deal +// in the Software without restriction, including without limitation the rights +// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +// copies of the Software, and to permit persons to whom the Software is +// furnished to do so, subject to the following conditions: +// +// The above copyright notice and this permission notice shall be included in +// all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN +// THE SOFTWARE. + + +import Foundation +#if os(macOS) +import AppKit +#else +import UIKit +#endif + +/// The downloading progress block type. +/// The parameter value is the `receivedSize` of current response. +/// The second parameter is the total expected data length from response's "Content-Length" header. +/// If the expected length is not available, this block will not be called. +public typealias DownloadProgressBlock = ((_ receivedSize: Int64, _ totalSize: Int64) -> Void) + +/// Represents the result of a Kingfisher retrieving image task. +public struct RetrieveImageResult { + /// Gets the image object of this result. + public let image: KFCrossPlatformImage + + /// Gets the cache source of the image. It indicates from which layer of cache this image is retrieved. + /// If the image is just downloaded from network, `.none` will be returned. + public let cacheType: CacheType + + /// The `Source` which this result is related to. This indicated where the `image` of `self` is referring. + public let source: Source + + /// The original `Source` from which the retrieve task begins. It can be different from the `source` property. + /// When an alternative source loading happened, the `source` will be the replacing loading target, while the + /// `originalSource` will be kept as the initial `source` which issued the image loading process. + public let originalSource: Source + + /// Gets the data behind the result. + /// + /// If this result is from a network downloading (when `cacheType == .none`), calling this returns the downloaded + /// data. If the reuslt is from cache, it serializes the image with the given cache serializer in the loading option + /// and returns the result. + /// + /// - Note: + /// This can be a time-consuming action, so if you need to use the data for multiple times, it is suggested to hold + /// it and prevent keeping calling this too frequently. + public let data: () -> Data? +} + +/// A struct that stores some related information of an `KingfisherError`. It provides some context information for +/// a pure error so you can identify the error easier. +public struct PropagationError { + + /// The `Source` to which current `error` is bound. + public let source: Source + + /// The actual error happens in framework. + public let error: KingfisherError +} + + +/// The downloading task updated block type. The parameter `newTask` is the updated new task of image setting process. +/// It is a `nil` if the image loading does not require an image downloading process. If an image downloading is issued, +/// this value will contain the actual `DownloadTask` for you to keep and cancel it later if you need. +public typealias DownloadTaskUpdatedBlock = ((_ newTask: DownloadTask?) -> Void) + +/// Main manager class of Kingfisher. It connects Kingfisher downloader and cache, +/// to provide a set of convenience methods to use Kingfisher for tasks. +/// You can use this class to retrieve an image via a specified URL from web or cache. +public class KingfisherManager { + + /// Represents a shared manager used across Kingfisher. + /// Use this instance for getting or storing images with Kingfisher. + public static let shared = KingfisherManager() + + // Mark: Public Properties + /// The `ImageCache` used by this manager. It is `ImageCache.default` by default. + /// If a cache is specified in `KingfisherManager.defaultOptions`, the value in `defaultOptions` will be + /// used instead. + public var cache: ImageCache + + /// The `ImageDownloader` used by this manager. It is `ImageDownloader.default` by default. + /// If a downloader is specified in `KingfisherManager.defaultOptions`, the value in `defaultOptions` will be + /// used instead. + public var downloader: ImageDownloader + + /// Default options used by the manager. This option will be used in + /// Kingfisher manager related methods, as well as all view extension methods. + /// You can also passing other options for each image task by sending an `options` parameter + /// to Kingfisher's APIs. The per image options will overwrite the default ones, + /// if the option exists in both. + public var defaultOptions = KingfisherOptionsInfo.empty + + // Use `defaultOptions` to overwrite the `downloader` and `cache`. + private var currentDefaultOptions: KingfisherOptionsInfo { + return [.downloader(downloader), .targetCache(cache)] + defaultOptions + } + + private let processingQueue: CallbackQueue + + private convenience init() { + self.init(downloader: .default, cache: .default) + } + + /// Creates an image setting manager with specified downloader and cache. + /// + /// - Parameters: + /// - downloader: The image downloader used to download images. + /// - cache: The image cache which stores memory and disk images. + public init(downloader: ImageDownloader, cache: ImageCache) { + self.downloader = downloader + self.cache = cache + + let processQueueName = "com.onevcat.Kingfisher.KingfisherManager.processQueue.\(UUID().uuidString)" + processingQueue = .dispatch(DispatchQueue(label: processQueueName)) + } + + // MARK: - Getting Images + + /// Gets an image from a given resource. + /// - Parameters: + /// - resource: The `Resource` object defines data information like key or URL. + /// - options: Options to use when creating the image. + /// - progressBlock: Called when the image downloading progress gets updated. If the response does not contain an + /// `expectedContentLength`, this block will not be called. `progressBlock` is always called in + /// main queue. + /// - downloadTaskUpdated: Called when a new image downloading task is created for current image retrieving. This + /// usually happens when an alternative source is used to replace the original (failed) + /// task. You can update your reference of `DownloadTask` if you want to manually `cancel` + /// the new task. + /// - completionHandler: Called when the image retrieved and set finished. This completion handler will be invoked + /// from the `options.callbackQueue`. If not specified, the main queue will be used. + /// - Returns: A task represents the image downloading. If there is a download task starts for `.network` resource, + /// the started `DownloadTask` is returned. Otherwise, `nil` is returned. + /// + /// - Note: + /// This method will first check whether the requested `resource` is already in cache or not. If cached, + /// it returns `nil` and invoke the `completionHandler` after the cached image retrieved. Otherwise, it + /// will download the `resource`, store it in cache, then call `completionHandler`. + @discardableResult + public func retrieveImage( + with resource: Resource, + options: KingfisherOptionsInfo? = nil, + progressBlock: DownloadProgressBlock? = nil, + downloadTaskUpdated: DownloadTaskUpdatedBlock? = nil, + completionHandler: ((Result) -> Void)?) -> DownloadTask? + { + return retrieveImage( + with: resource.convertToSource(), + options: options, + progressBlock: progressBlock, + downloadTaskUpdated: downloadTaskUpdated, + completionHandler: completionHandler + ) + } + + /// Gets an image from a given resource. + /// + /// - Parameters: + /// - source: The `Source` object defines data information from network or a data provider. + /// - options: Options to use when creating the image. + /// - progressBlock: Called when the image downloading progress gets updated. If the response does not contain an + /// `expectedContentLength`, this block will not be called. `progressBlock` is always called in + /// main queue. + /// - downloadTaskUpdated: Called when a new image downloading task is created for current image retrieving. This + /// usually happens when an alternative source is used to replace the original (failed) + /// task. You can update your reference of `DownloadTask` if you want to manually `cancel` + /// the new task. + /// - completionHandler: Called when the image retrieved and set finished. This completion handler will be invoked + /// from the `options.callbackQueue`. If not specified, the main queue will be used. + /// - Returns: A task represents the image downloading. If there is a download task starts for `.network` resource, + /// the started `DownloadTask` is returned. Otherwise, `nil` is returned. + /// + /// - Note: + /// This method will first check whether the requested `source` is already in cache or not. If cached, + /// it returns `nil` and invoke the `completionHandler` after the cached image retrieved. Otherwise, it + /// will try to load the `source`, store it in cache, then call `completionHandler`. + /// + @discardableResult + public func retrieveImage( + with source: Source, + options: KingfisherOptionsInfo? = nil, + progressBlock: DownloadProgressBlock? = nil, + downloadTaskUpdated: DownloadTaskUpdatedBlock? = nil, + completionHandler: ((Result) -> Void)?) -> DownloadTask? + { + let options = currentDefaultOptions + (options ?? .empty) + let info = KingfisherParsedOptionsInfo(options) + return retrieveImage( + with: source, + options: info, + progressBlock: progressBlock, + downloadTaskUpdated: downloadTaskUpdated, + completionHandler: completionHandler) + } + + func retrieveImage( + with source: Source, + options: KingfisherParsedOptionsInfo, + progressBlock: DownloadProgressBlock? = nil, + downloadTaskUpdated: DownloadTaskUpdatedBlock? = nil, + completionHandler: ((Result) -> Void)?) -> DownloadTask? + { + var info = options + if let block = progressBlock { + info.onDataReceived = (info.onDataReceived ?? []) + [ImageLoadingProgressSideEffect(block)] + } + return retrieveImage( + with: source, + options: info, + downloadTaskUpdated: downloadTaskUpdated, + progressiveImageSetter: nil, + completionHandler: completionHandler) + } + + func retrieveImage( + with source: Source, + options: KingfisherParsedOptionsInfo, + downloadTaskUpdated: DownloadTaskUpdatedBlock? = nil, + progressiveImageSetter: ((KFCrossPlatformImage?) -> Void)? = nil, + referenceTaskIdentifierChecker: (() -> Bool)? = nil, + completionHandler: ((Result) -> Void)?) -> DownloadTask? + { + var options = options + if let provider = ImageProgressiveProvider(options, refresh: { image in + guard let setter = progressiveImageSetter else { + return + } + guard let strategy = options.progressiveJPEG?.onImageUpdated(image) else { + setter(image) + return + } + switch strategy { + case .default: setter(image) + case .keepCurrent: break + case .replace(let newImage): setter(newImage) + } + }) { + options.onDataReceived = (options.onDataReceived ?? []) + [provider] + } + if let checker = referenceTaskIdentifierChecker { + options.onDataReceived?.forEach { + $0.onShouldApply = checker + } + } + + let retrievingContext = RetrievingContext(options: options, originalSource: source) + var retryContext: RetryContext? + + func startNewRetrieveTask( + with source: Source, + downloadTaskUpdated: DownloadTaskUpdatedBlock? + ) { + let newTask = self.retrieveImage(with: source, context: retrievingContext) { result in + handler(currentSource: source, result: result) + } + downloadTaskUpdated?(newTask) + } + + func failCurrentSource(_ source: Source, with error: KingfisherError) { + // Skip alternative sources if the user cancelled it. + guard !error.isTaskCancelled else { + completionHandler?(.failure(error)) + return + } + // When low data mode constrained error, retry with the low data mode source instead of use alternative on fly. + guard !error.isLowDataModeConstrained else { + if let source = retrievingContext.options.lowDataModeSource { + retrievingContext.options.lowDataModeSource = nil + startNewRetrieveTask(with: source, downloadTaskUpdated: downloadTaskUpdated) + } else { + // This should not happen. + completionHandler?(.failure(error)) + } + return + } + if let nextSource = retrievingContext.popAlternativeSource() { + retrievingContext.appendError(error, to: source) + startNewRetrieveTask(with: nextSource, downloadTaskUpdated: downloadTaskUpdated) + } else { + // No other alternative source. Finish with error. + if retrievingContext.propagationErrors.isEmpty { + completionHandler?(.failure(error)) + } else { + retrievingContext.appendError(error, to: source) + let finalError = KingfisherError.imageSettingError( + reason: .alternativeSourcesExhausted(retrievingContext.propagationErrors) + ) + completionHandler?(.failure(finalError)) + } + } + } + + func handler(currentSource: Source, result: (Result)) -> Void { + switch result { + case .success: + completionHandler?(result) + case .failure(let error): + if let retryStrategy = options.retryStrategy { + let context = retryContext?.increaseRetryCount() ?? RetryContext(source: source, error: error) + retryContext = context + + retryStrategy.retry(context: context) { decision in + switch decision { + case .retry(let userInfo): + retryContext?.userInfo = userInfo + startNewRetrieveTask(with: source, downloadTaskUpdated: downloadTaskUpdated) + case .stop: + failCurrentSource(currentSource, with: error) + } + } + } else { + failCurrentSource(currentSource, with: error) + } + } + } + + return retrieveImage( + with: source, + context: retrievingContext) + { + result in + handler(currentSource: source, result: result) + } + + } + + private func retrieveImage( + with source: Source, + context: RetrievingContext, + completionHandler: ((Result) -> Void)?) -> DownloadTask? + { + let options = context.options + if options.forceRefresh { + return loadAndCacheImage( + source: source, + context: context, + completionHandler: completionHandler)?.value + + } else { + let loadedFromCache = retrieveImageFromCache( + source: source, + context: context, + completionHandler: completionHandler) + + if loadedFromCache { + return nil + } + + if options.onlyFromCache { + let error = KingfisherError.cacheError(reason: .imageNotExisting(key: source.cacheKey)) + completionHandler?(.failure(error)) + return nil + } + + return loadAndCacheImage( + source: source, + context: context, + completionHandler: completionHandler)?.value + } + } + + func provideImage( + provider: ImageDataProvider, + options: KingfisherParsedOptionsInfo, + completionHandler: ((Result) -> Void)?) + { + guard let completionHandler = completionHandler else { return } + provider.data { result in + switch result { + case .success(let data): + (options.processingQueue ?? self.processingQueue).execute { + let processor = options.processor + let processingItem = ImageProcessItem.data(data) + guard let image = processor.process(item: processingItem, options: options) else { + options.callbackQueue.execute { + let error = KingfisherError.processorError( + reason: .processingFailed(processor: processor, item: processingItem)) + completionHandler(.failure(error)) + } + return + } + + options.callbackQueue.execute { + let result = ImageLoadingResult(image: image, url: nil, originalData: data) + completionHandler(.success(result)) + } + } + case .failure(let error): + options.callbackQueue.execute { + let error = KingfisherError.imageSettingError( + reason: .dataProviderError(provider: provider, error: error)) + completionHandler(.failure(error)) + } + + } + } + } + + private func cacheImage( + source: Source, + options: KingfisherParsedOptionsInfo, + context: RetrievingContext, + result: Result, + completionHandler: ((Result) -> Void)? + ) + { + switch result { + case .success(let value): + let needToCacheOriginalImage = options.cacheOriginalImage && + options.processor != DefaultImageProcessor.default + let coordinator = CacheCallbackCoordinator( + shouldWaitForCache: options.waitForCache, shouldCacheOriginal: needToCacheOriginalImage) + let result = RetrieveImageResult( + image: options.imageModifier?.modify(value.image) ?? value.image, + cacheType: .none, + source: source, + originalSource: context.originalSource, + data: { value.originalData } + ) + // Add image to cache. + let targetCache = options.targetCache ?? self.cache + targetCache.store( + value.image, + original: value.originalData, + forKey: source.cacheKey, + options: options, + toDisk: !options.cacheMemoryOnly) + { + _ in + coordinator.apply(.cachingImage) { + completionHandler?(.success(result)) + } + } + + // Add original image to cache if necessary. + + if needToCacheOriginalImage { + let originalCache = options.originalCache ?? targetCache + originalCache.storeToDisk( + value.originalData, + forKey: source.cacheKey, + processorIdentifier: DefaultImageProcessor.default.identifier, + expiration: options.diskCacheExpiration) + { + _ in + coordinator.apply(.cachingOriginalImage) { + completionHandler?(.success(result)) + } + } + } + + coordinator.apply(.cacheInitiated) { + completionHandler?(.success(result)) + } + + case .failure(let error): + completionHandler?(.failure(error)) + } + } + + @discardableResult + func loadAndCacheImage( + source: Source, + context: RetrievingContext, + completionHandler: ((Result) -> Void)?) -> DownloadTask.WrappedTask? + { + let options = context.options + func _cacheImage(_ result: Result) { + cacheImage( + source: source, + options: options, + context: context, + result: result, + completionHandler: completionHandler + ) + } + + switch source { + case .network(let resource): + let downloader = options.downloader ?? self.downloader + let task = downloader.downloadImage( + with: resource.downloadURL, options: options, completionHandler: _cacheImage + ) + + + // The code below is neat, but it fails the Swift 5.2 compiler with a runtime crash when + // `BUILD_LIBRARY_FOR_DISTRIBUTION` is turned on. I believe it is a bug in the compiler. + // Let's fallback to a traditional style before it can be fixed in Swift. + // + // https://github.com/onevcat/Kingfisher/issues/1436 + // + // return task.map(DownloadTask.WrappedTask.download) + + if let task = task { + return .download(task) + } else { + return nil + } + + case .provider(let provider): + provideImage(provider: provider, options: options, completionHandler: _cacheImage) + return .dataProviding + } + } + + /// Retrieves image from memory or disk cache. + /// + /// - Parameters: + /// - source: The target source from which to get image. + /// - key: The key to use when caching the image. + /// - url: Image request URL. This is not used when retrieving image from cache. It is just used for + /// `RetrieveImageResult` callback compatibility. + /// - options: Options on how to get the image from image cache. + /// - completionHandler: Called when the image retrieving finishes, either with succeeded + /// `RetrieveImageResult` or an error. + /// - Returns: `true` if the requested image or the original image before being processed is existing in cache. + /// Otherwise, this method returns `false`. + /// + /// - Note: + /// The image retrieving could happen in either memory cache or disk cache. The `.processor` option in + /// `options` will be considered when searching in the cache. If no processed image is found, Kingfisher + /// will try to check whether an original version of that image is existing or not. If there is already an + /// original, Kingfisher retrieves it from cache and processes it. Then, the processed image will be store + /// back to cache for later use. + func retrieveImageFromCache( + source: Source, + context: RetrievingContext, + completionHandler: ((Result) -> Void)?) -> Bool + { + let options = context.options + // 1. Check whether the image was already in target cache. If so, just get it. + let targetCache = options.targetCache ?? cache + let key = source.cacheKey + let targetImageCached = targetCache.imageCachedType( + forKey: key, processorIdentifier: options.processor.identifier) + + let validCache = targetImageCached.cached && + (options.fromMemoryCacheOrRefresh == false || targetImageCached == .memory) + if validCache { + targetCache.retrieveImage(forKey: key, options: options) { result in + guard let completionHandler = completionHandler else { return } + + // TODO: Optimize it when we can use async across all the project. + func checkResultImageAndCallback(_ inputImage: KFCrossPlatformImage) { + var image = inputImage + if image.kf.imageFrameCount != nil && image.kf.imageFrameCount != 1, let data = image.kf.animatedImageData { + // Always recreate animated image representation since it is possible to be loaded in different options. + // https://github.com/onevcat/Kingfisher/issues/1923 + image = options.processor.process(item: .data(data), options: options) ?? .init() + } + if let modifier = options.imageModifier { + image = modifier.modify(image) + } + let value = result.map { + RetrieveImageResult( + image: image, + cacheType: $0.cacheType, + source: source, + originalSource: context.originalSource, + data: { options.cacheSerializer.data(with: image, original: nil) } + ) + } + completionHandler(value) + } + + result.match { cacheResult in + options.callbackQueue.execute { + guard let image = cacheResult.image else { + completionHandler(.failure(KingfisherError.cacheError(reason: .imageNotExisting(key: key)))) + return + } + + if options.cacheSerializer.originalDataUsed { + let processor = options.processor + (options.processingQueue ?? self.processingQueue).execute { + let item = ImageProcessItem.image(image) + guard let processedImage = processor.process(item: item, options: options) else { + let error = KingfisherError.processorError( + reason: .processingFailed(processor: processor, item: item)) + options.callbackQueue.execute { completionHandler(.failure(error)) } + return + } + options.callbackQueue.execute { + checkResultImageAndCallback(processedImage) + } + } + } else { + checkResultImageAndCallback(image) + } + } + } onFailure: { error in + options.callbackQueue.execute { + completionHandler(.failure(KingfisherError.cacheError(reason: .imageNotExisting(key: key)))) + } + } + } + return true + } + + // 2. Check whether the original image exists. If so, get it, process it, save to storage and return. + let originalCache = options.originalCache ?? targetCache + // No need to store the same file in the same cache again. + if originalCache === targetCache && options.processor == DefaultImageProcessor.default { + return false + } + + // Check whether the unprocessed image existing or not. + let originalImageCacheType = originalCache.imageCachedType( + forKey: key, processorIdentifier: DefaultImageProcessor.default.identifier) + let canAcceptDiskCache = !options.fromMemoryCacheOrRefresh + + let canUseOriginalImageCache = + (canAcceptDiskCache && originalImageCacheType.cached) || + (!canAcceptDiskCache && originalImageCacheType == .memory) + + if canUseOriginalImageCache { + // Now we are ready to get found the original image from cache. We need the unprocessed image, so remove + // any processor from options first. + var optionsWithoutProcessor = options + optionsWithoutProcessor.processor = DefaultImageProcessor.default + originalCache.retrieveImage(forKey: key, options: optionsWithoutProcessor) { result in + + result.match( + onSuccess: { cacheResult in + guard let image = cacheResult.image else { + assertionFailure("The image (under key: \(key) should be existing in the original cache.") + return + } + + let processor = options.processor + (options.processingQueue ?? self.processingQueue).execute { + let item = ImageProcessItem.image(image) + guard let processedImage = processor.process(item: item, options: options) else { + let error = KingfisherError.processorError( + reason: .processingFailed(processor: processor, item: item)) + options.callbackQueue.execute { completionHandler?(.failure(error)) } + return + } + + var cacheOptions = options + cacheOptions.callbackQueue = .untouch + + let coordinator = CacheCallbackCoordinator( + shouldWaitForCache: options.waitForCache, shouldCacheOriginal: false) + + let image = options.imageModifier?.modify(processedImage) ?? processedImage + let result = RetrieveImageResult( + image: image, + cacheType: .none, + source: source, + originalSource: context.originalSource, + data: { options.cacheSerializer.data(with: processedImage, original: nil) } + ) + + targetCache.store( + processedImage, + forKey: key, + options: cacheOptions, + toDisk: !options.cacheMemoryOnly) + { + _ in + coordinator.apply(.cachingImage) { + options.callbackQueue.execute { completionHandler?(.success(result)) } + } + } + + coordinator.apply(.cacheInitiated) { + options.callbackQueue.execute { completionHandler?(.success(result)) } + } + } + }, + onFailure: { _ in + // This should not happen actually, since we already confirmed `originalImageCached` is `true`. + // Just in case... + options.callbackQueue.execute { + completionHandler?( + .failure(KingfisherError.cacheError(reason: .imageNotExisting(key: key))) + ) + } + } + ) + } + return true + } + + return false + } +} + +class RetrievingContext { + + var options: KingfisherParsedOptionsInfo + + let originalSource: Source + var propagationErrors: [PropagationError] = [] + + init(options: KingfisherParsedOptionsInfo, originalSource: Source) { + self.originalSource = originalSource + self.options = options + } + + func popAlternativeSource() -> Source? { + guard var alternativeSources = options.alternativeSources, !alternativeSources.isEmpty else { + return nil + } + let nextSource = alternativeSources.removeFirst() + options.alternativeSources = alternativeSources + return nextSource + } + + @discardableResult + func appendError(_ error: KingfisherError, to source: Source) -> [PropagationError] { + let item = PropagationError(source: source, error: error) + propagationErrors.append(item) + return propagationErrors + } +} + +class CacheCallbackCoordinator { + + enum State { + case idle + case imageCached + case originalImageCached + case done + } + + enum Action { + case cacheInitiated + case cachingImage + case cachingOriginalImage + } + + private let shouldWaitForCache: Bool + private let shouldCacheOriginal: Bool + private let stateQueue: DispatchQueue + private var threadSafeState: State = .idle + + private (set) var state: State { + set { stateQueue.sync { threadSafeState = newValue } } + get { stateQueue.sync { threadSafeState } } + } + + init(shouldWaitForCache: Bool, shouldCacheOriginal: Bool) { + self.shouldWaitForCache = shouldWaitForCache + self.shouldCacheOriginal = shouldCacheOriginal + let stateQueueName = "com.onevcat.Kingfisher.CacheCallbackCoordinator.stateQueue.\(UUID().uuidString)" + self.stateQueue = DispatchQueue(label: stateQueueName) + } + + func apply(_ action: Action, trigger: () -> Void) { + switch (state, action) { + case (.done, _): + break + + // From .idle + case (.idle, .cacheInitiated): + if !shouldWaitForCache { + state = .done + trigger() + } + case (.idle, .cachingImage): + if shouldCacheOriginal { + state = .imageCached + } else { + state = .done + trigger() + } + case (.idle, .cachingOriginalImage): + state = .originalImageCached + + // From .imageCached + case (.imageCached, .cachingOriginalImage): + state = .done + trigger() + + // From .originalImageCached + case (.originalImageCached, .cachingImage): + state = .done + trigger() + + default: + assertionFailure("This case should not happen in CacheCallbackCoordinator: \(state) - \(action)") + } + } +} diff --git a/Pods/Kingfisher/Sources/General/KingfisherOptionsInfo.swift b/Pods/Kingfisher/Sources/General/KingfisherOptionsInfo.swift new file mode 100644 index 0000000..5f2aea6 --- /dev/null +++ b/Pods/Kingfisher/Sources/General/KingfisherOptionsInfo.swift @@ -0,0 +1,400 @@ +// +// KingfisherOptionsInfo.swift +// Kingfisher +// +// Created by Wei Wang on 15/4/23. +// +// Copyright (c) 2019 Wei Wang +// +// Permission is hereby granted, free of charge, to any person obtaining a copy +// of this software and associated documentation files (the "Software"), to deal +// in the Software without restriction, including without limitation the rights +// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +// copies of the Software, and to permit persons to whom the Software is +// furnished to do so, subject to the following conditions: +// +// The above copyright notice and this permission notice shall be included in +// all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN +// THE SOFTWARE. + +#if os(macOS) +import AppKit +#else +import UIKit +#endif + + +/// KingfisherOptionsInfo is a typealias for [KingfisherOptionsInfoItem]. +/// You can use the enum of option item with value to control some behaviors of Kingfisher. +public typealias KingfisherOptionsInfo = [KingfisherOptionsInfoItem] + +extension Array where Element == KingfisherOptionsInfoItem { + static let empty: KingfisherOptionsInfo = [] +} + +/// Represents the available option items could be used in `KingfisherOptionsInfo`. +public enum KingfisherOptionsInfoItem { + + /// Kingfisher will use the associated `ImageCache` object when handling related operations, + /// including trying to retrieve the cached images and store the downloaded image to it. + case targetCache(ImageCache) + + /// The `ImageCache` for storing and retrieving original images. If `originalCache` is + /// contained in the options, it will be preferred for storing and retrieving original images. + /// If there is no `.originalCache` in the options, `.targetCache` will be used to store original images. + /// + /// When using KingfisherManager to download and store an image, if `cacheOriginalImage` is + /// applied in the option, the original image will be stored to this `originalCache`. At the + /// same time, if a requested final image (with processor applied) cannot be found in `targetCache`, + /// Kingfisher will try to search the original image to check whether it is already there. If found, + /// it will be used and applied with the given processor. It is an optimization for not downloading + /// the same image for multiple times. + case originalCache(ImageCache) + + /// Kingfisher will use the associated `ImageDownloader` object to download the requested images. + case downloader(ImageDownloader) + + /// Member for animation transition when using `UIImageView`. Kingfisher will use the `ImageTransition` of + /// this enum to animate the image in if it is downloaded from web. The transition will not happen when the + /// image is retrieved from either memory or disk cache by default. If you need to do the transition even when + /// the image being retrieved from cache, set `.forceRefresh` as well. + case transition(ImageTransition) + + /// Associated `Float` value will be set as the priority of image download task. The value for it should be + /// between 0.0~1.0. If this option not set, the default value (`URLSessionTask.defaultPriority`) will be used. + case downloadPriority(Float) + + /// If set, Kingfisher will ignore the cache and try to start a download task for the image source. + case forceRefresh + + /// If set, Kingfisher will try to retrieve the image from memory cache first. If the image is not in memory + /// cache, then it will ignore the disk cache but download the image again from network. This is useful when + /// you want to display a changeable image behind the same url at the same app session, while avoiding download + /// it for multiple times. + case fromMemoryCacheOrRefresh + + /// If set, setting the image to an image view will happen with transition even when retrieved from cache. + /// See `.transition` option for more. + case forceTransition + + /// If set, Kingfisher will only cache the value in memory but not in disk. + case cacheMemoryOnly + + /// If set, Kingfisher will wait for caching operation to be completed before calling the completion block. + case waitForCache + + /// If set, Kingfisher will only try to retrieve the image from cache, but not from network. If the image is not in + /// cache, the image retrieving will fail with the `KingfisherError.cacheError` with `.imageNotExisting` as its + /// reason. + case onlyFromCache + + /// Decode the image in background thread before using. It will decode the downloaded image data and do a off-screen + /// rendering to extract pixel information in background. This can speed up display, but will cost more time to + /// prepare the image for using. + case backgroundDecode + + /// The associated value will be used as the target queue of dispatch callbacks when retrieving images from + /// cache. If not set, Kingfisher will use `.mainCurrentOrAsync` for callbacks. + /// + /// - Note: + /// This option does not affect the callbacks for UI related extension methods. You will always get the + /// callbacks called from main queue. + case callbackQueue(CallbackQueue) + + /// The associated value will be used as the scale factor when converting retrieved data to an image. + /// Specify the image scale, instead of your screen scale. You may need to set the correct scale when you dealing + /// with 2x or 3x retina images. Otherwise, Kingfisher will convert the data to image object at `scale` 1.0. + case scaleFactor(CGFloat) + + /// Whether all the animated image data should be preloaded. Default is `false`, which means only following frames + /// will be loaded on need. If `true`, all the animated image data will be loaded and decoded into memory. + /// + /// This option is mainly used for back compatibility internally. You should not set it directly. Instead, + /// you should choose the image view class to control the GIF data loading. There are two classes in Kingfisher + /// support to display a GIF image. `AnimatedImageView` does not preload all data, it takes much less memory, but + /// uses more CPU when display. While a normal image view (`UIImageView` or `NSImageView`) loads all data at once, + /// which uses more memory but only decode image frames once. + case preloadAllAnimationData + + /// The `ImageDownloadRequestModifier` contained will be used to change the request before it being sent. + /// This is the last chance you can modify the image download request. You can modify the request for some + /// customizing purpose, such as adding auth token to the header, do basic HTTP auth or something like url mapping. + /// The original request will be sent without any modification by default. + case requestModifier(AsyncImageDownloadRequestModifier) + + /// The `ImageDownloadRedirectHandler` contained will be used to change the request before redirection. + /// This is the possibility you can modify the image download request during redirect. You can modify the request for + /// some customizing purpose, such as adding auth token to the header, do basic HTTP auth or something like url + /// mapping. + /// The original redirection request will be sent without any modification by default. + case redirectHandler(ImageDownloadRedirectHandler) + + /// Processor for processing when the downloading finishes, a processor will convert the downloaded data to an image + /// and/or apply some filter on it. If a cache is connected to the downloader (it happens when you are using + /// KingfisherManager or any of the view extension methods), the converted image will also be sent to cache as well. + /// If not set, the `DefaultImageProcessor.default` will be used. + case processor(ImageProcessor) + + /// Provides a `CacheSerializer` to convert some data to an image object for + /// retrieving from disk cache or vice versa for storing to disk cache. + /// If not set, the `DefaultCacheSerializer.default` will be used. + case cacheSerializer(CacheSerializer) + + /// An `ImageModifier` is for modifying an image as needed right before it is used. If the image was fetched + /// directly from the downloader, the modifier will run directly after the `ImageProcessor`. If the image is being + /// fetched from a cache, the modifier will run after the `CacheSerializer`. + /// + /// Use `ImageModifier` when you need to set properties that do not persist when caching the image on a concrete + /// type of `Image`, such as the `renderingMode` or the `alignmentInsets` of `UIImage`. + case imageModifier(ImageModifier) + + /// Keep the existing image of image view while setting another image to it. + /// By setting this option, the placeholder image parameter of image view extension method + /// will be ignored and the current image will be kept while loading or downloading the new image. + case keepCurrentImageWhileLoading + + /// If set, Kingfisher will only load the first frame from an animated image file as a single image. + /// Loading an animated images may take too much memory. It will be useful when you want to display a + /// static preview of the first frame from an animated image. + /// + /// This option will be ignored if the target image is not animated image data. + case onlyLoadFirstFrame + + /// If set and an `ImageProcessor` is used, Kingfisher will try to cache both the final result and original + /// image. Kingfisher will have a chance to use the original image when another processor is applied to the same + /// resource, instead of downloading it again. You can use `.originalCache` to specify a cache or the original + /// images if necessary. + /// + /// The original image will be only cached to disk storage. + case cacheOriginalImage + + /// If set and an image retrieving error occurred Kingfisher will set provided image (or empty) + /// in place of requested one. It's useful when you don't want to show placeholder + /// during loading time but wants to use some default image when requests will be failed. + case onFailureImage(KFCrossPlatformImage?) + + /// If set and used in `ImagePrefetcher`, the prefetching operation will load the images into memory storage + /// aggressively. By default this is not contained in the options, that means if the requested image is already + /// in disk cache, Kingfisher will not try to load it to memory. + case alsoPrefetchToMemory + + /// If set, the disk storage loading will happen in the same calling queue. By default, disk storage file loading + /// happens in its own queue with an asynchronous dispatch behavior. Although it provides better non-blocking disk + /// loading performance, it also causes a flickering when you reload an image from disk, if the image view already + /// has an image set. + /// + /// Set this options will stop that flickering by keeping all loading in the same queue (typically the UI queue + /// if you are using Kingfisher's extension methods to set an image), with a tradeoff of loading performance. + case loadDiskFileSynchronously + + /// Options to control the writing of data to disk storage + /// If set, options will be passed the store operation for a new files. + case diskStoreWriteOptions(Data.WritingOptions) + + /// The expiration setting for memory cache. By default, the underlying `MemoryStorage.Backend` uses the + /// expiration in its config for all items. If set, the `MemoryStorage.Backend` will use this associated + /// value to overwrite the config setting for this caching item. + case memoryCacheExpiration(StorageExpiration) + + /// The expiration extending setting for memory cache. The item expiration time will be incremented by this + /// value after access. + /// By default, the underlying `MemoryStorage.Backend` uses the initial cache expiration as extending + /// value: .cacheTime. + /// + /// To disable extending option at all add memoryCacheAccessExtendingExpiration(.none) to options. + case memoryCacheAccessExtendingExpiration(ExpirationExtending) + + /// The expiration setting for disk cache. By default, the underlying `DiskStorage.Backend` uses the + /// expiration in its config for all items. If set, the `DiskStorage.Backend` will use this associated + /// value to overwrite the config setting for this caching item. + case diskCacheExpiration(StorageExpiration) + + /// The expiration extending setting for disk cache. The item expiration time will be incremented by this value after access. + /// By default, the underlying `DiskStorage.Backend` uses the initial cache expiration as extending value: .cacheTime. + /// To disable extending option at all add diskCacheAccessExtendingExpiration(.none) to options. + case diskCacheAccessExtendingExpiration(ExpirationExtending) + + /// Decides on which queue the image processing should happen. By default, Kingfisher uses a pre-defined serial + /// queue to process images. Use this option to change this behavior. For example, specify a `.mainCurrentOrAsync` + /// to let the image be processed in main queue to prevent a possible flickering (but with a possibility of + /// blocking the UI, especially if the processor needs a lot of time to run). + case processingQueue(CallbackQueue) + + /// Enable progressive image loading, Kingfisher will use the associated `ImageProgressive` value to process the + /// progressive JPEG data and display it in a progressive way. + case progressiveJPEG(ImageProgressive) + + /// The alternative sources will be used when the original input `Source` fails. The `Source`s in the associated + /// array will be used to start a new image loading task if the previous task fails due to an error. The image + /// source loading process will stop as soon as a source is loaded successfully. If all `[Source]`s are used but + /// the loading is still failing, an `imageSettingError` with `alternativeSourcesExhausted` as its reason will be + /// thrown out. + /// + /// This option is useful if you want to implement a fallback solution for setting image. + /// + /// User cancellation will not trigger the alternative source loading. + case alternativeSources([Source]) + + /// Provide a retry strategy which will be used when something gets wrong during the image retrieving process from + /// `KingfisherManager`. You can define a strategy by create a type conforming to the `RetryStrategy` protocol. + /// + /// - Note: + /// + /// All extension methods of Kingfisher (`kf` extensions on `UIImageView` or `UIButton`) retrieve images through + /// `KingfisherManager`, so the retry strategy also applies when using them. However, this option does not apply + /// when pass to an `ImageDownloader` or `ImageCache`. + /// + case retryStrategy(RetryStrategy) + + /// The `Source` should be loaded when user enables Low Data Mode and the original source fails with an + /// `NSURLErrorNetworkUnavailableReason.constrained` error. When this option is set, the + /// `allowsConstrainedNetworkAccess` property of the request for the original source will be set to `false` and the + /// `Source` in associated value will be used to retrieve the image for low data mode. Usually, you can provide a + /// low-resolution version of your image or a local image provider to display a placeholder. + /// + /// If not set or the `source` is `nil`, the device Low Data Mode will be ignored and the original source will + /// be loaded following the system default behavior, in a normal way. + case lowDataMode(Source?) +} + +// Improve performance by parsing the input `KingfisherOptionsInfo` (self) first. +// So we can prevent the iterating over the options array again and again. +/// The parsed options info used across Kingfisher methods. Each property in this type corresponds a case member +/// in `KingfisherOptionsInfoItem`. When a `KingfisherOptionsInfo` sent to Kingfisher related methods, it will be +/// parsed and converted to a `KingfisherParsedOptionsInfo` first, and pass through the internal methods. +public struct KingfisherParsedOptionsInfo { + + public var targetCache: ImageCache? = nil + public var originalCache: ImageCache? = nil + public var downloader: ImageDownloader? = nil + public var transition: ImageTransition = .none + public var downloadPriority: Float = URLSessionTask.defaultPriority + public var forceRefresh = false + public var fromMemoryCacheOrRefresh = false + public var forceTransition = false + public var cacheMemoryOnly = false + public var waitForCache = false + public var onlyFromCache = false + public var backgroundDecode = false + public var preloadAllAnimationData = false + public var callbackQueue: CallbackQueue = .mainCurrentOrAsync + public var scaleFactor: CGFloat = 1.0 + public var requestModifier: AsyncImageDownloadRequestModifier? = nil + public var redirectHandler: ImageDownloadRedirectHandler? = nil + public var processor: ImageProcessor = DefaultImageProcessor.default + public var imageModifier: ImageModifier? = nil + public var cacheSerializer: CacheSerializer = DefaultCacheSerializer.default + public var keepCurrentImageWhileLoading = false + public var onlyLoadFirstFrame = false + public var cacheOriginalImage = false + public var onFailureImage: Optional = .none + public var alsoPrefetchToMemory = false + public var loadDiskFileSynchronously = false + public var diskStoreWriteOptions: Data.WritingOptions = [] + public var memoryCacheExpiration: StorageExpiration? = nil + public var memoryCacheAccessExtendingExpiration: ExpirationExtending = .cacheTime + public var diskCacheExpiration: StorageExpiration? = nil + public var diskCacheAccessExtendingExpiration: ExpirationExtending = .cacheTime + public var processingQueue: CallbackQueue? = nil + public var progressiveJPEG: ImageProgressive? = nil + public var alternativeSources: [Source]? = nil + public var retryStrategy: RetryStrategy? = nil + public var lowDataModeSource: Source? = nil + + var onDataReceived: [DataReceivingSideEffect]? = nil + + public init(_ info: KingfisherOptionsInfo?) { + guard let info = info else { return } + for option in info { + switch option { + case .targetCache(let value): targetCache = value + case .originalCache(let value): originalCache = value + case .downloader(let value): downloader = value + case .transition(let value): transition = value + case .downloadPriority(let value): downloadPriority = value + case .forceRefresh: forceRefresh = true + case .fromMemoryCacheOrRefresh: fromMemoryCacheOrRefresh = true + case .forceTransition: forceTransition = true + case .cacheMemoryOnly: cacheMemoryOnly = true + case .waitForCache: waitForCache = true + case .onlyFromCache: onlyFromCache = true + case .backgroundDecode: backgroundDecode = true + case .preloadAllAnimationData: preloadAllAnimationData = true + case .callbackQueue(let value): callbackQueue = value + case .scaleFactor(let value): scaleFactor = value + case .requestModifier(let value): requestModifier = value + case .redirectHandler(let value): redirectHandler = value + case .processor(let value): processor = value + case .imageModifier(let value): imageModifier = value + case .cacheSerializer(let value): cacheSerializer = value + case .keepCurrentImageWhileLoading: keepCurrentImageWhileLoading = true + case .onlyLoadFirstFrame: onlyLoadFirstFrame = true + case .cacheOriginalImage: cacheOriginalImage = true + case .onFailureImage(let value): onFailureImage = .some(value) + case .alsoPrefetchToMemory: alsoPrefetchToMemory = true + case .loadDiskFileSynchronously: loadDiskFileSynchronously = true + case .diskStoreWriteOptions(let options): diskStoreWriteOptions = options + case .memoryCacheExpiration(let expiration): memoryCacheExpiration = expiration + case .memoryCacheAccessExtendingExpiration(let expirationExtending): memoryCacheAccessExtendingExpiration = expirationExtending + case .diskCacheExpiration(let expiration): diskCacheExpiration = expiration + case .diskCacheAccessExtendingExpiration(let expirationExtending): diskCacheAccessExtendingExpiration = expirationExtending + case .processingQueue(let queue): processingQueue = queue + case .progressiveJPEG(let value): progressiveJPEG = value + case .alternativeSources(let sources): alternativeSources = sources + case .retryStrategy(let strategy): retryStrategy = strategy + case .lowDataMode(let source): lowDataModeSource = source + } + } + + if originalCache == nil { + originalCache = targetCache + } + } +} + +extension KingfisherParsedOptionsInfo { + var imageCreatingOptions: ImageCreatingOptions { + return ImageCreatingOptions( + scale: scaleFactor, + duration: 0.0, + preloadAll: preloadAllAnimationData, + onlyFirstFrame: onlyLoadFirstFrame) + } +} + +protocol DataReceivingSideEffect: AnyObject { + var onShouldApply: () -> Bool { get set } + func onDataReceived(_ session: URLSession, task: SessionDataTask, data: Data) +} + +class ImageLoadingProgressSideEffect: DataReceivingSideEffect { + + var onShouldApply: () -> Bool = { return true } + + let block: DownloadProgressBlock + + init(_ block: @escaping DownloadProgressBlock) { + self.block = block + } + + func onDataReceived(_ session: URLSession, task: SessionDataTask, data: Data) { + guard self.onShouldApply() else { return } + guard let expectedContentLength = task.task.response?.expectedContentLength, + expectedContentLength != -1 else + { + return + } + + let dataLength = Int64(task.mutableData.count) + DispatchQueue.main.async { + self.block(dataLength, expectedContentLength) + } + } +} diff --git a/Pods/Kingfisher/Sources/Image/Filter.swift b/Pods/Kingfisher/Sources/Image/Filter.swift new file mode 100644 index 0000000..be357ce --- /dev/null +++ b/Pods/Kingfisher/Sources/Image/Filter.swift @@ -0,0 +1,152 @@ +// +// Filter.swift +// Kingfisher +// +// Created by Wei Wang on 2016/08/31. +// +// Copyright (c) 2019 Wei Wang +// +// Permission is hereby granted, free of charge, to any person obtaining a copy +// of this software and associated documentation files (the "Software"), to deal +// in the Software without restriction, including without limitation the rights +// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +// copies of the Software, and to permit persons to whom the Software is +// furnished to do so, subject to the following conditions: +// +// The above copyright notice and this permission notice shall be included in +// all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN +// THE SOFTWARE. + +#if !os(watchOS) + +#if os(macOS) +import AppKit +#else +import UIKit +#endif + +import CoreImage + +// Reuse the same CI Context for all CI drawing. +private let ciContext = CIContext(options: nil) + +/// Represents the type of transformer method, which will be used in to provide a `Filter`. +public typealias Transformer = (CIImage) -> CIImage? + +/// Represents a processor based on a `CIImage` `Filter`. +/// It requires a filter to create an `ImageProcessor`. +public protocol CIImageProcessor: ImageProcessor { + var filter: Filter { get } +} + +extension CIImageProcessor { + + /// Processes the input `ImageProcessItem` with this processor. + /// + /// - Parameters: + /// - item: Input item which will be processed by `self`. + /// - options: Options when processing the item. + /// - Returns: The processed image. + /// + /// - Note: See documentation of `ImageProcessor` protocol for more. + public func process(item: ImageProcessItem, options: KingfisherParsedOptionsInfo) -> KFCrossPlatformImage? { + switch item { + case .image(let image): + return image.kf.apply(filter) + case .data: + return (DefaultImageProcessor.default |> self).process(item: item, options: options) + } + } +} + +/// A wrapper struct for a `Transformer` of CIImage filters. A `Filter` +/// value could be used to create a `CIImage` processor. +public struct Filter { + + let transform: Transformer + + public init(transform: @escaping Transformer) { + self.transform = transform + } + + /// Tint filter which will apply a tint color to images. + public static var tint: (KFCrossPlatformColor) -> Filter = { + color in + Filter { + input in + + let colorFilter = CIFilter(name: "CIConstantColorGenerator")! + colorFilter.setValue(CIColor(color: color), forKey: kCIInputColorKey) + + let filter = CIFilter(name: "CISourceOverCompositing")! + + let colorImage = colorFilter.outputImage + filter.setValue(colorImage, forKey: kCIInputImageKey) + filter.setValue(input, forKey: kCIInputBackgroundImageKey) + + return filter.outputImage?.cropped(to: input.extent) + } + } + + /// Represents color control elements. It is a tuple of + /// `(brightness, contrast, saturation, inputEV)` + public typealias ColorElement = (CGFloat, CGFloat, CGFloat, CGFloat) + + /// Color control filter which will apply color control change to images. + public static var colorControl: (ColorElement) -> Filter = { arg -> Filter in + let (brightness, contrast, saturation, inputEV) = arg + return Filter { input in + let paramsColor = [kCIInputBrightnessKey: brightness, + kCIInputContrastKey: contrast, + kCIInputSaturationKey: saturation] + let blackAndWhite = input.applyingFilter("CIColorControls", parameters: paramsColor) + let paramsExposure = [kCIInputEVKey: inputEV] + return blackAndWhite.applyingFilter("CIExposureAdjust", parameters: paramsExposure) + } + } +} + +extension KingfisherWrapper where Base: KFCrossPlatformImage { + + /// Applies a `Filter` containing `CIImage` transformer to `self`. + /// + /// - Parameter filter: The filter used to transform `self`. + /// - Returns: A transformed image by input `Filter`. + /// + /// - Note: + /// Only CG-based images are supported. If any error happens + /// during transforming, `self` will be returned. + public func apply(_ filter: Filter) -> KFCrossPlatformImage { + + guard let cgImage = cgImage else { + assertionFailure("[Kingfisher] Tint image only works for CG-based image.") + return base + } + + let inputImage = CIImage(cgImage: cgImage) + guard let outputImage = filter.transform(inputImage) else { + return base + } + + guard let result = ciContext.createCGImage(outputImage, from: outputImage.extent) else { + assertionFailure("[Kingfisher] Can not make an tint image within context.") + return base + } + + #if os(macOS) + return fixedForRetinaPixel(cgImage: result, to: size) + #else + return KFCrossPlatformImage(cgImage: result, scale: base.scale, orientation: base.imageOrientation) + #endif + } + +} + +#endif diff --git a/Pods/Kingfisher/Sources/Image/GIFAnimatedImage.swift b/Pods/Kingfisher/Sources/Image/GIFAnimatedImage.swift new file mode 100644 index 0000000..323fe42 --- /dev/null +++ b/Pods/Kingfisher/Sources/Image/GIFAnimatedImage.swift @@ -0,0 +1,177 @@ +// +// AnimatedImage.swift +// Kingfisher +// +// Created by onevcat on 2018/09/26. +// +// Copyright (c) 2019 Wei Wang +// +// Permission is hereby granted, free of charge, to any person obtaining a copy +// of this software and associated documentation files (the "Software"), to deal +// in the Software without restriction, including without limitation the rights +// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +// copies of the Software, and to permit persons to whom the Software is +// furnished to do so, subject to the following conditions: +// +// The above copyright notice and this permission notice shall be included in +// all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN +// THE SOFTWARE. + +import Foundation +import ImageIO + +/// Represents a set of image creating options used in Kingfisher. +public struct ImageCreatingOptions { + + /// The target scale of image needs to be created. + public let scale: CGFloat + + /// The expected animation duration if an animated image being created. + public let duration: TimeInterval + + /// For an animated image, whether or not all frames should be loaded before displaying. + public let preloadAll: Bool + + /// For an animated image, whether or not only the first image should be + /// loaded as a static image. It is useful for preview purpose of an animated image. + public let onlyFirstFrame: Bool + + /// Creates an `ImageCreatingOptions` object. + /// + /// - Parameters: + /// - scale: The target scale of image needs to be created. Default is `1.0`. + /// - duration: The expected animation duration if an animated image being created. + /// A value less or equal to `0.0` means the animated image duration will + /// be determined by the frame data. Default is `0.0`. + /// - preloadAll: For an animated image, whether or not all frames should be loaded before displaying. + /// Default is `false`. + /// - onlyFirstFrame: For an animated image, whether or not only the first image should be + /// loaded as a static image. It is useful for preview purpose of an animated image. + /// Default is `false`. + public init( + scale: CGFloat = 1.0, + duration: TimeInterval = 0.0, + preloadAll: Bool = false, + onlyFirstFrame: Bool = false) + { + self.scale = scale + self.duration = duration + self.preloadAll = preloadAll + self.onlyFirstFrame = onlyFirstFrame + } +} + +/// Represents the decoding for a GIF image. This class extracts frames from an `imageSource`, then +/// hold the images for later use. +public class GIFAnimatedImage { + let images: [KFCrossPlatformImage] + let duration: TimeInterval + + init?(from frameSource: ImageFrameSource, options: ImageCreatingOptions) { + let frameCount = frameSource.frameCount + var images = [KFCrossPlatformImage]() + var gifDuration = 0.0 + + for i in 0 ..< frameCount { + guard let imageRef = frameSource.frame(at: i) else { + return nil + } + + if frameCount == 1 { + gifDuration = .infinity + } else { + // Get current animated GIF frame duration + gifDuration += frameSource.duration(at: i) + } + images.append(KingfisherWrapper.image(cgImage: imageRef, scale: options.scale, refImage: nil)) + if options.onlyFirstFrame { break } + } + self.images = images + self.duration = gifDuration + } + + convenience init?(from imageSource: CGImageSource, for info: [String: Any], options: ImageCreatingOptions) { + let frameSource = CGImageFrameSource(data: nil, imageSource: imageSource, options: info) + self.init(from: frameSource, options: options) + } + + /// Calculates frame duration for a gif frame out of the kCGImagePropertyGIFDictionary dictionary. + public static func getFrameDuration(from gifInfo: [String: Any]?) -> TimeInterval { + let defaultFrameDuration = 0.1 + guard let gifInfo = gifInfo else { return defaultFrameDuration } + + let unclampedDelayTime = gifInfo[kCGImagePropertyGIFUnclampedDelayTime as String] as? NSNumber + let delayTime = gifInfo[kCGImagePropertyGIFDelayTime as String] as? NSNumber + let duration = unclampedDelayTime ?? delayTime + + guard let frameDuration = duration else { return defaultFrameDuration } + return frameDuration.doubleValue > 0.011 ? frameDuration.doubleValue : defaultFrameDuration + } + + /// Calculates frame duration at a specific index for a gif from an `imageSource`. + public static func getFrameDuration(from imageSource: CGImageSource, at index: Int) -> TimeInterval { + guard let properties = CGImageSourceCopyPropertiesAtIndex(imageSource, index, nil) + as? [String: Any] else { return 0.0 } + + let gifInfo = properties[kCGImagePropertyGIFDictionary as String] as? [String: Any] + return getFrameDuration(from: gifInfo) + } +} + +/// Represents a frame source for animated image +public protocol ImageFrameSource { + /// Source data associated with this frame source. + var data: Data? { get } + + /// Count of total frames in this frame source. + var frameCount: Int { get } + + /// Retrieves the frame at a specific index. The result image is expected to be + /// no larger than `maxSize`. If the index is invalid, implementors should return `nil`. + func frame(at index: Int, maxSize: CGSize?) -> CGImage? + + /// Retrieves the duration at a specific index. If the index is invalid, implementors should return `0.0`. + func duration(at index: Int) -> TimeInterval +} + +public extension ImageFrameSource { + /// Retrieves the frame at a specific index. If the index is invalid, implementors should return `nil`. + func frame(at index: Int) -> CGImage? { + return frame(at: index, maxSize: nil) + } +} + +struct CGImageFrameSource: ImageFrameSource { + let data: Data? + let imageSource: CGImageSource + let options: [String: Any]? + + var frameCount: Int { + return CGImageSourceGetCount(imageSource) + } + + func frame(at index: Int, maxSize: CGSize?) -> CGImage? { + var options = self.options as? [CFString: Any] + if let maxSize = maxSize, maxSize != .zero { + options = (options ?? [:]).merging([ + kCGImageSourceCreateThumbnailFromImageIfAbsent: true, + kCGImageSourceCreateThumbnailWithTransform: true, + kCGImageSourceShouldCacheImmediately: true, + kCGImageSourceThumbnailMaxPixelSize: max(maxSize.width, maxSize.height) + ], uniquingKeysWith: { $1 }) + } + return CGImageSourceCreateImageAtIndex(imageSource, index, options as CFDictionary?) + } + + func duration(at index: Int) -> TimeInterval { + return GIFAnimatedImage.getFrameDuration(from: imageSource, at: index) + } +} + diff --git a/Pods/Kingfisher/Sources/Image/GraphicsContext.swift b/Pods/Kingfisher/Sources/Image/GraphicsContext.swift new file mode 100644 index 0000000..6d8443c --- /dev/null +++ b/Pods/Kingfisher/Sources/Image/GraphicsContext.swift @@ -0,0 +1,88 @@ +// +// GraphicsContext.swift +// Kingfisher +// +// Created by taras on 19/04/2021. +// +// Copyright (c) 2021 Wei Wang +// +// Permission is hereby granted, free of charge, to any person obtaining a copy +// of this software and associated documentation files (the "Software"), to deal +// in the Software without restriction, including without limitation the rights +// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +// copies of the Software, and to permit persons to whom the Software is +// furnished to do so, subject to the following conditions: +// +// The above copyright notice and this permission notice shall be included in +// all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN +// THE SOFTWARE. + +#if canImport(AppKit) && !targetEnvironment(macCatalyst) +import AppKit +#endif +#if canImport(UIKit) +import UIKit +#endif + +enum GraphicsContext { + static func begin(size: CGSize, scale: CGFloat) { + #if os(macOS) + NSGraphicsContext.saveGraphicsState() + #else + UIGraphicsBeginImageContextWithOptions(size, false, scale) + #endif + } + + static func current(size: CGSize, scale: CGFloat, inverting: Bool, cgImage: CGImage?) -> CGContext? { + #if os(macOS) + guard let rep = NSBitmapImageRep( + bitmapDataPlanes: nil, + pixelsWide: Int(size.width), + pixelsHigh: Int(size.height), + bitsPerSample: cgImage?.bitsPerComponent ?? 8, + samplesPerPixel: 4, + hasAlpha: true, + isPlanar: false, + colorSpaceName: .calibratedRGB, + bytesPerRow: 0, + bitsPerPixel: 0) else + { + assertionFailure("[Kingfisher] Image representation cannot be created.") + return nil + } + rep.size = size + guard let context = NSGraphicsContext(bitmapImageRep: rep) else { + assertionFailure("[Kingfisher] Image context cannot be created.") + return nil + } + + NSGraphicsContext.current = context + return context.cgContext + #else + guard let context = UIGraphicsGetCurrentContext() else { + return nil + } + if inverting { // If drawing a CGImage, we need to make context flipped. + context.scaleBy(x: 1.0, y: -1.0) + context.translateBy(x: 0, y: -size.height) + } + return context + #endif + } + + static func end() { + #if os(macOS) + NSGraphicsContext.restoreGraphicsState() + #else + UIGraphicsEndImageContext() + #endif + } +} + diff --git a/Pods/Kingfisher/Sources/Image/Image.swift b/Pods/Kingfisher/Sources/Image/Image.swift new file mode 100644 index 0000000..30d3590 --- /dev/null +++ b/Pods/Kingfisher/Sources/Image/Image.swift @@ -0,0 +1,426 @@ +// +// Image.swift +// Kingfisher +// +// Created by Wei Wang on 16/1/6. +// +// Copyright (c) 2019 Wei Wang +// +// Permission is hereby granted, free of charge, to any person obtaining a copy +// of this software and associated documentation files (the "Software"), to deal +// in the Software without restriction, including without limitation the rights +// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +// copies of the Software, and to permit persons to whom the Software is +// furnished to do so, subject to the following conditions: +// +// The above copyright notice and this permission notice shall be included in +// all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN +// THE SOFTWARE. + + +#if os(macOS) +import AppKit +private var imagesKey: Void? +private var durationKey: Void? +#else +import UIKit +import MobileCoreServices +private var imageSourceKey: Void? +#endif + +#if !os(watchOS) +import CoreImage +#endif + +import CoreGraphics +import ImageIO + +#if canImport(UniformTypeIdentifiers) +import UniformTypeIdentifiers +#endif + +private var animatedImageDataKey: Void? +private var imageFrameCountKey: Void? + +// MARK: - Image Properties +extension KingfisherWrapper where Base: KFCrossPlatformImage { + private(set) var animatedImageData: Data? { + get { return getAssociatedObject(base, &animatedImageDataKey) } + set { setRetainedAssociatedObject(base, &animatedImageDataKey, newValue) } + } + + public var imageFrameCount: Int? { + get { return getAssociatedObject(base, &imageFrameCountKey) } + set { setRetainedAssociatedObject(base, &imageFrameCountKey, newValue) } + } + + #if os(macOS) + var cgImage: CGImage? { + return base.cgImage(forProposedRect: nil, context: nil, hints: nil) + } + + var scale: CGFloat { + return 1.0 + } + + private(set) var images: [KFCrossPlatformImage]? { + get { return getAssociatedObject(base, &imagesKey) } + set { setRetainedAssociatedObject(base, &imagesKey, newValue) } + } + + private(set) var duration: TimeInterval { + get { return getAssociatedObject(base, &durationKey) ?? 0.0 } + set { setRetainedAssociatedObject(base, &durationKey, newValue) } + } + + var size: CGSize { + return base.representations.reduce(.zero) { size, rep in + let width = max(size.width, CGFloat(rep.pixelsWide)) + let height = max(size.height, CGFloat(rep.pixelsHigh)) + return CGSize(width: width, height: height) + } + } + #else + var cgImage: CGImage? { return base.cgImage } + var scale: CGFloat { return base.scale } + var images: [KFCrossPlatformImage]? { return base.images } + var duration: TimeInterval { return base.duration } + var size: CGSize { return base.size } + + /// The image source reference of current image. + public var imageSource: CGImageSource? { + get { + guard let frameSource = frameSource as? CGImageFrameSource else { return nil } + return frameSource.imageSource + } + } + + /// The custom frame source of current image. + public private(set) var frameSource: ImageFrameSource? { + get { return getAssociatedObject(base, &imageSourceKey) } + set { setRetainedAssociatedObject(base, &imageSourceKey, newValue) } + } + #endif + + // Bitmap memory cost with bytes. + var cost: Int { + let pixel = Int(size.width * size.height * scale * scale) + guard let cgImage = cgImage else { + return pixel * 4 + } + let bytesPerPixel = cgImage.bitsPerPixel / 8 + guard let imageCount = images?.count else { + return pixel * bytesPerPixel + } + return pixel * bytesPerPixel * imageCount + } +} + +// MARK: - Image Conversion +extension KingfisherWrapper where Base: KFCrossPlatformImage { + #if os(macOS) + static func image(cgImage: CGImage, scale: CGFloat, refImage: KFCrossPlatformImage?) -> KFCrossPlatformImage { + return KFCrossPlatformImage(cgImage: cgImage, size: .zero) + } + + /// Normalize the image. This getter does nothing on macOS but return the image itself. + public var normalized: KFCrossPlatformImage { return base } + + #else + /// Creating an image from a give `CGImage` at scale and orientation for refImage. The method signature is for + /// compatibility of macOS version. + static func image(cgImage: CGImage, scale: CGFloat, refImage: KFCrossPlatformImage?) -> KFCrossPlatformImage { + return KFCrossPlatformImage(cgImage: cgImage, scale: scale, orientation: refImage?.imageOrientation ?? .up) + } + + /// Returns normalized image for current `base` image. + /// This method will try to redraw an image with orientation and scale considered. + public var normalized: KFCrossPlatformImage { + // prevent animated image (GIF) lose it's images + guard images == nil else { return base.copy() as! KFCrossPlatformImage } + // No need to do anything if already up + guard base.imageOrientation != .up else { return base.copy() as! KFCrossPlatformImage } + + return draw(to: size, inverting: true, refImage: KFCrossPlatformImage()) { + fixOrientation(in: $0) + return true + } + } + + func fixOrientation(in context: CGContext) { + + var transform = CGAffineTransform.identity + + let orientation = base.imageOrientation + + switch orientation { + case .down, .downMirrored: + transform = transform.translatedBy(x: size.width, y: size.height) + transform = transform.rotated(by: .pi) + case .left, .leftMirrored: + transform = transform.translatedBy(x: size.width, y: 0) + transform = transform.rotated(by: .pi / 2.0) + case .right, .rightMirrored: + transform = transform.translatedBy(x: 0, y: size.height) + transform = transform.rotated(by: .pi / -2.0) + case .up, .upMirrored: + break + #if compiler(>=5) + @unknown default: + break + #endif + } + + // Flip image one more time if needed to, this is to prevent flipped image + switch orientation { + case .upMirrored, .downMirrored: + transform = transform.translatedBy(x: size.width, y: 0) + transform = transform.scaledBy(x: -1, y: 1) + case .leftMirrored, .rightMirrored: + transform = transform.translatedBy(x: size.height, y: 0) + transform = transform.scaledBy(x: -1, y: 1) + case .up, .down, .left, .right: + break + #if compiler(>=5) + @unknown default: + break + #endif + } + + context.concatenate(transform) + switch orientation { + case .left, .leftMirrored, .right, .rightMirrored: + context.draw(cgImage!, in: CGRect(x: 0, y: 0, width: size.height, height: size.width)) + default: + context.draw(cgImage!, in: CGRect(x: 0, y: 0, width: size.width, height: size.height)) + } + } + #endif +} + +// MARK: - Image Representation +extension KingfisherWrapper where Base: KFCrossPlatformImage { + /// Returns PNG representation of `base` image. + /// + /// - Returns: PNG data of image. + public func pngRepresentation() -> Data? { + #if os(macOS) + guard let cgImage = cgImage else { + return nil + } + let rep = NSBitmapImageRep(cgImage: cgImage) + return rep.representation(using: .png, properties: [:]) + #else + return base.pngData() + #endif + } + + /// Returns JPEG representation of `base` image. + /// + /// - Parameter compressionQuality: The compression quality when converting image to JPEG data. + /// - Returns: JPEG data of image. + public func jpegRepresentation(compressionQuality: CGFloat) -> Data? { + #if os(macOS) + guard let cgImage = cgImage else { + return nil + } + let rep = NSBitmapImageRep(cgImage: cgImage) + return rep.representation(using:.jpeg, properties: [.compressionFactor: compressionQuality]) + #else + return base.jpegData(compressionQuality: compressionQuality) + #endif + } + + /// Returns GIF representation of `base` image. + /// + /// - Returns: Original GIF data of image. + public func gifRepresentation() -> Data? { + return animatedImageData + } + + /// Returns a data representation for `base` image, with the `format` as the format indicator. + /// - Parameters: + /// - format: The format in which the output data should be. If `unknown`, the `base` image will be + /// converted in the PNG representation. + /// - compressionQuality: The compression quality when converting image to a lossy format data. + /// + /// - Returns: The output data representing. + public func data(format: ImageFormat, compressionQuality: CGFloat = 1.0) -> Data? { + return autoreleasepool { () -> Data? in + let data: Data? + switch format { + case .PNG: data = pngRepresentation() + case .JPEG: data = jpegRepresentation(compressionQuality: compressionQuality) + case .GIF: data = gifRepresentation() + case .unknown: data = normalized.kf.pngRepresentation() + } + + return data + } + } +} + +// MARK: - Creating Images +extension KingfisherWrapper where Base: KFCrossPlatformImage { + + /// Creates an animated image from a given data and options. Currently only GIF data is supported. + /// + /// - Parameters: + /// - data: The animated image data. + /// - options: Options to use when creating the animated image. + /// - Returns: An `Image` object represents the animated image. It is in form of an array of image frames with a + /// certain duration. `nil` if anything wrong when creating animated image. + public static func animatedImage(data: Data, options: ImageCreatingOptions) -> KFCrossPlatformImage? { + #if os(visionOS) + let info: [String: Any] = [ + kCGImageSourceShouldCache as String: true, + kCGImageSourceTypeIdentifierHint as String: UTType.gif.identifier + ] + #else + let info: [String: Any] = [ + kCGImageSourceShouldCache as String: true, + kCGImageSourceTypeIdentifierHint as String: kUTTypeGIF + ] + #endif + + guard let imageSource = CGImageSourceCreateWithData(data as CFData, info as CFDictionary) else { + return nil + } + let frameSource = CGImageFrameSource(data: data, imageSource: imageSource, options: info) + #if os(macOS) + let baseImage = KFCrossPlatformImage(data: data) + #else + let baseImage = KFCrossPlatformImage(data: data, scale: options.scale) + #endif + return animatedImage(source: frameSource, options: options, baseImage: baseImage) + } + + /// Creates an animated image from a given frame source. + /// + /// - Parameters: + /// - source: The frame source to create animated image from. + /// - options: Options to use when creating the animated image. + /// - baseImage: An optional image object to be used as the key frame of the animated image. If `nil`, the first + /// frame of the `source` will be used. + /// - Returns: An `Image` object represents the animated image. It is in form of an array of image frames with a + /// certain duration. `nil` if anything wrong when creating animated image. + public static func animatedImage(source: ImageFrameSource, options: ImageCreatingOptions, baseImage: KFCrossPlatformImage? = nil) -> KFCrossPlatformImage? { + #if os(macOS) + guard let animatedImage = GIFAnimatedImage(from: source, options: options) else { + return nil + } + var image: KFCrossPlatformImage? + if options.onlyFirstFrame { + image = animatedImage.images.first + } else { + if let baseImage = baseImage { + image = baseImage + } else { + image = animatedImage.images.first + } + var kf = image?.kf + kf?.images = animatedImage.images + kf?.duration = animatedImage.duration + } + image?.kf.animatedImageData = source.data + image?.kf.imageFrameCount = source.frameCount + return image + #else + + var image: KFCrossPlatformImage? + if options.preloadAll || options.onlyFirstFrame { + // Use `images` image if you want to preload all animated data + guard let animatedImage = GIFAnimatedImage(from: source, options: options) else { + return nil + } + if options.onlyFirstFrame { + image = animatedImage.images.first + } else { + let duration = options.duration <= 0.0 ? animatedImage.duration : options.duration + image = .animatedImage(with: animatedImage.images, duration: duration) + } + image?.kf.animatedImageData = source.data + } else { + if let baseImage = baseImage { + image = baseImage + } else { + guard let firstFrame = source.frame(at: 0) else { + return nil + } + image = KFCrossPlatformImage(cgImage: firstFrame, scale: options.scale, orientation: .up) + } + var kf = image?.kf + kf?.frameSource = source + kf?.animatedImageData = source.data + } + + image?.kf.imageFrameCount = source.frameCount + return image + #endif + } + + /// Creates an image from a given data and options. `.JPEG`, `.PNG` or `.GIF` is supported. For other + /// image format, image initializer from system will be used. If no image object could be created from + /// the given `data`, `nil` will be returned. + /// + /// - Parameters: + /// - data: The image data representation. + /// - options: Options to use when creating the image. + /// - Returns: An `Image` object represents the image if created. If the `data` is invalid or not supported, `nil` + /// will be returned. + public static func image(data: Data, options: ImageCreatingOptions) -> KFCrossPlatformImage? { + var image: KFCrossPlatformImage? + switch data.kf.imageFormat { + case .JPEG: + image = KFCrossPlatformImage(data: data, scale: options.scale) + case .PNG: + image = KFCrossPlatformImage(data: data, scale: options.scale) + case .GIF: + image = KingfisherWrapper.animatedImage(data: data, options: options) + case .unknown: + image = KFCrossPlatformImage(data: data, scale: options.scale) + } + return image + } + + /// Creates a downsampled image from given data to a certain size and scale. + /// + /// - Parameters: + /// - data: The image data contains a JPEG or PNG image. + /// - pointSize: The target size in point to which the image should be downsampled. + /// - scale: The scale of result image. + /// - Returns: A downsampled `Image` object following the input conditions. + /// + /// - Note: + /// Different from image `resize` methods, downsampling will not render the original + /// input image in pixel format. It does downsampling from the image data, so it is much + /// more memory efficient and friendly. Choose to use downsampling as possible as you can. + /// + /// The pointsize should be smaller than the size of input image. If it is larger than the + /// original image size, the result image will be the same size of input without downsampling. + public static func downsampledImage(data: Data, to pointSize: CGSize, scale: CGFloat) -> KFCrossPlatformImage? { + let imageSourceOptions = [kCGImageSourceShouldCache: false] as CFDictionary + guard let imageSource = CGImageSourceCreateWithData(data as CFData, imageSourceOptions) else { + return nil + } + + let maxDimensionInPixels = max(pointSize.width, pointSize.height) * scale + let downsampleOptions: [CFString : Any] = [ + kCGImageSourceCreateThumbnailFromImageAlways: true, + kCGImageSourceShouldCacheImmediately: true, + kCGImageSourceCreateThumbnailWithTransform: true, + kCGImageSourceThumbnailMaxPixelSize: maxDimensionInPixels + ] + guard let downsampledImage = CGImageSourceCreateThumbnailAtIndex(imageSource, 0, downsampleOptions as CFDictionary) else { + return nil + } + return KingfisherWrapper.image(cgImage: downsampledImage, scale: scale, refImage: nil) + } +} diff --git a/Pods/Kingfisher/Sources/Image/ImageDrawing.swift b/Pods/Kingfisher/Sources/Image/ImageDrawing.swift new file mode 100644 index 0000000..fd1c126 --- /dev/null +++ b/Pods/Kingfisher/Sources/Image/ImageDrawing.swift @@ -0,0 +1,655 @@ +// +// ImageDrawing.swift +// Kingfisher +// +// Created by onevcat on 2018/09/28. +// +// Copyright (c) 2019 Wei Wang +// +// Permission is hereby granted, free of charge, to any person obtaining a copy +// of this software and associated documentation files (the "Software"), to deal +// in the Software without restriction, including without limitation the rights +// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +// copies of the Software, and to permit persons to whom the Software is +// furnished to do so, subject to the following conditions: +// +// The above copyright notice and this permission notice shall be included in +// all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN +// THE SOFTWARE. + +import Accelerate + +#if canImport(AppKit) && !targetEnvironment(macCatalyst) +import AppKit +#endif +#if canImport(UIKit) +import UIKit +#endif + +// MARK: - Image Transforming +extension KingfisherWrapper where Base: KFCrossPlatformImage { + // MARK: Blend Mode + /// Create image from `base` image and apply blend mode. + /// + /// - parameter blendMode: The blend mode of creating image. + /// - parameter alpha: The alpha should be used for image. + /// - parameter backgroundColor: The background color for the output image. + /// + /// - returns: An image with blend mode applied. + /// + /// - Note: This method only works for CG-based image. + #if !os(macOS) + public func image(withBlendMode blendMode: CGBlendMode, + alpha: CGFloat = 1.0, + backgroundColor: KFCrossPlatformColor? = nil) -> KFCrossPlatformImage + { + guard let _ = cgImage else { + assertionFailure("[Kingfisher] Blend mode image only works for CG-based image.") + return base + } + + let rect = CGRect(origin: .zero, size: size) + return draw(to: rect.size, inverting: false) { _ in + if let backgroundColor = backgroundColor { + backgroundColor.setFill() + UIRectFill(rect) + } + + base.draw(in: rect, blendMode: blendMode, alpha: alpha) + return false + } + } + #endif + + #if os(macOS) + // MARK: Compositing + /// Creates image from `base` image and apply compositing operation. + /// + /// - Parameters: + /// - compositingOperation: The compositing operation of creating image. + /// - alpha: The alpha should be used for image. + /// - backgroundColor: The background color for the output image. + /// - Returns: An image with compositing operation applied. + /// + /// - Note: This method only works for CG-based image. For any non-CG-based image, `base` itself is returned. + public func image(withCompositingOperation compositingOperation: NSCompositingOperation, + alpha: CGFloat = 1.0, + backgroundColor: KFCrossPlatformColor? = nil) -> KFCrossPlatformImage + { + guard let _ = cgImage else { + assertionFailure("[Kingfisher] Compositing Operation image only works for CG-based image.") + return base + } + + let rect = CGRect(origin: .zero, size: size) + return draw(to: rect.size, inverting: false) { _ in + if let backgroundColor = backgroundColor { + backgroundColor.setFill() + rect.fill() + } + base.draw(in: rect, from: .zero, operation: compositingOperation, fraction: alpha) + return false + } + } + #endif + + // MARK: Round Corner + + /// Creates a round corner image from on `base` image. + /// + /// - Parameters: + /// - radius: The round corner radius of creating image. + /// - size: The target size of creating image. + /// - corners: The target corners which will be applied rounding. + /// - backgroundColor: The background color for the output image + /// - Returns: An image with round corner of `self`. + /// + /// - Note: This method only works for CG-based image. The current image scale is kept. + /// For any non-CG-based image, `base` itself is returned. + public func image( + withRadius radius: Radius, + fit size: CGSize, + roundingCorners corners: RectCorner = .all, + backgroundColor: KFCrossPlatformColor? = nil + ) -> KFCrossPlatformImage + { + + guard let _ = cgImage else { + assertionFailure("[Kingfisher] Round corner image only works for CG-based image.") + return base + } + + let rect = CGRect(origin: CGPoint(x: 0, y: 0), size: size) + return draw(to: size, inverting: false) { _ in + #if os(macOS) + if let backgroundColor = backgroundColor { + let rectPath = NSBezierPath(rect: rect) + backgroundColor.setFill() + rectPath.fill() + } + + let path = pathForRoundCorner(rect: rect, radius: radius, corners: corners) + path.addClip() + base.draw(in: rect) + #else + guard let context = UIGraphicsGetCurrentContext() else { + assertionFailure("[Kingfisher] Failed to create CG context for image.") + return false + } + + if let backgroundColor = backgroundColor { + let rectPath = UIBezierPath(rect: rect) + backgroundColor.setFill() + rectPath.fill() + } + + let path = pathForRoundCorner(rect: rect, radius: radius, corners: corners) + context.addPath(path.cgPath) + context.clip() + base.draw(in: rect) + #endif + return false + } + } + + /// Creates a round corner image from on `base` image. + /// + /// - Parameters: + /// - radius: The round corner radius of creating image. + /// - size: The target size of creating image. + /// - corners: The target corners which will be applied rounding. + /// - backgroundColor: The background color for the output image + /// - Returns: An image with round corner of `self`. + /// + /// - Note: This method only works for CG-based image. The current image scale is kept. + /// For any non-CG-based image, `base` itself is returned. + public func image( + withRoundRadius radius: CGFloat, + fit size: CGSize, + roundingCorners corners: RectCorner = .all, + backgroundColor: KFCrossPlatformColor? = nil + ) -> KFCrossPlatformImage + { + image(withRadius: .point(radius), fit: size, roundingCorners: corners, backgroundColor: backgroundColor) + } + + #if os(macOS) + func pathForRoundCorner(rect: CGRect, radius: Radius, corners: RectCorner, offsetBase: CGFloat = 0) -> NSBezierPath { + let cornerRadius = radius.compute(with: rect.size) + let path = NSBezierPath(roundedRect: rect, byRoundingCorners: corners, radius: cornerRadius - offsetBase / 2) + path.windingRule = .evenOdd + return path + } + #else + func pathForRoundCorner(rect: CGRect, radius: Radius, corners: RectCorner, offsetBase: CGFloat = 0) -> UIBezierPath { + let cornerRadius = radius.compute(with: rect.size) + return UIBezierPath( + roundedRect: rect, + byRoundingCorners: corners.uiRectCorner, + cornerRadii: CGSize( + width: cornerRadius - offsetBase / 2, + height: cornerRadius - offsetBase / 2 + ) + ) + } + #endif + + #if os(iOS) || os(tvOS) || os(visionOS) + func resize(to size: CGSize, for contentMode: UIView.ContentMode) -> KFCrossPlatformImage { + switch contentMode { + case .scaleAspectFit: + return resize(to: size, for: .aspectFit) + case .scaleAspectFill: + return resize(to: size, for: .aspectFill) + default: + return resize(to: size) + } + } + #endif + + // MARK: Resizing + /// Resizes `base` image to an image with new size. + /// + /// - Parameter size: The target size in point. + /// - Returns: An image with new size. + /// - Note: This method only works for CG-based image. The current image scale is kept. + /// For any non-CG-based image, `base` itself is returned. + public func resize(to size: CGSize) -> KFCrossPlatformImage { + guard let _ = cgImage else { + assertionFailure("[Kingfisher] Resize only works for CG-based image.") + return base + } + + let rect = CGRect(origin: CGPoint(x: 0, y: 0), size: size) + return draw(to: size, inverting: false) { _ in + #if os(macOS) + base.draw(in: rect, from: .zero, operation: .copy, fraction: 1.0) + #else + base.draw(in: rect) + #endif + return false + } + } + + /// Resizes `base` image to an image of new size, respecting the given content mode. + /// + /// - Parameters: + /// - targetSize: The target size in point. + /// - contentMode: Content mode of output image should be. + /// - Returns: An image with new size. + /// + /// - Note: This method only works for CG-based image. The current image scale is kept. + /// For any non-CG-based image, `base` itself is returned. + public func resize(to targetSize: CGSize, for contentMode: ContentMode) -> KFCrossPlatformImage { + let newSize = size.kf.resize(to: targetSize, for: contentMode) + return resize(to: newSize) + } + + // MARK: Cropping + /// Crops `base` image to a new size with a given anchor. + /// + /// - Parameters: + /// - size: The target size. + /// - anchor: The anchor point from which the size should be calculated. + /// - Returns: An image with new size. + /// + /// - Note: This method only works for CG-based image. The current image scale is kept. + /// For any non-CG-based image, `base` itself is returned. + public func crop(to size: CGSize, anchorOn anchor: CGPoint) -> KFCrossPlatformImage { + guard let cgImage = cgImage else { + assertionFailure("[Kingfisher] Crop only works for CG-based image.") + return base + } + + let rect = self.size.kf.constrainedRect(for: size, anchor: anchor) + guard let image = cgImage.cropping(to: rect.scaled(scale)) else { + assertionFailure("[Kingfisher] Cropping image failed.") + return base + } + + return KingfisherWrapper.image(cgImage: image, scale: scale, refImage: base) + } + + // MARK: Blur + /// Creates an image with blur effect based on `base` image. + /// + /// - Parameter radius: The blur radius should be used when creating blur effect. + /// - Returns: An image with blur effect applied. + /// + /// - Note: This method only works for CG-based image. The current image scale is kept. + /// For any non-CG-based image, `base` itself is returned. + public func blurred(withRadius radius: CGFloat) -> KFCrossPlatformImage { + + guard let cgImage = cgImage else { + assertionFailure("[Kingfisher] Blur only works for CG-based image.") + return base + } + + // http://www.w3.org/TR/SVG/filters.html#feGaussianBlurElement + // let d = floor(s * 3*sqrt(2*pi)/4 + 0.5) + // if d is odd, use three box-blurs of size 'd', centered on the output pixel. + let s = max(radius, 2.0) + // We will do blur on a resized image (*0.5), so the blur radius could be half as well. + + // Fix the slow compiling time for Swift 3. + // See https://github.com/onevcat/Kingfisher/issues/611 + let pi2 = 2 * CGFloat.pi + let sqrtPi2 = sqrt(pi2) + var targetRadius = floor(s * 3.0 * sqrtPi2 / 4.0 + 0.5) + + if targetRadius.isEven { targetRadius += 1 } + + // Determine necessary iteration count by blur radius. + let iterations: Int + if radius < 0.5 { + iterations = 1 + } else if radius < 1.5 { + iterations = 2 + } else { + iterations = 3 + } + + let w = Int(size.width) + let h = Int(size.height) + + func createEffectBuffer(_ context: CGContext) -> vImage_Buffer { + let data = context.data + let width = vImagePixelCount(context.width) + let height = vImagePixelCount(context.height) + let rowBytes = context.bytesPerRow + + return vImage_Buffer(data: data, height: height, width: width, rowBytes: rowBytes) + } + GraphicsContext.begin(size: size, scale: scale) + guard let context = GraphicsContext.current(size: size, scale: scale, inverting: true, cgImage: cgImage) else { + assertionFailure("[Kingfisher] Failed to create CG context for blurring image.") + return base + } + context.draw(cgImage, in: CGRect(x: 0, y: 0, width: w, height: h)) + GraphicsContext.end() + + var inBuffer = createEffectBuffer(context) + + GraphicsContext.begin(size: size, scale: scale) + guard let outContext = GraphicsContext.current(size: size, scale: scale, inverting: true, cgImage: cgImage) else { + assertionFailure("[Kingfisher] Failed to create CG context for blurring image.") + return base + } + defer { GraphicsContext.end() } + var outBuffer = createEffectBuffer(outContext) + + for _ in 0 ..< iterations { + let flag = vImage_Flags(kvImageEdgeExtend) + vImageBoxConvolve_ARGB8888( + &inBuffer, &outBuffer, nil, 0, 0, UInt32(targetRadius), UInt32(targetRadius), nil, flag) + // Next inBuffer should be the outButter of current iteration + (inBuffer, outBuffer) = (outBuffer, inBuffer) + } + + #if os(macOS) + let result = outContext.makeImage().flatMap { + fixedForRetinaPixel(cgImage: $0, to: size) + } + #else + let result = outContext.makeImage().flatMap { + KFCrossPlatformImage(cgImage: $0, scale: base.scale, orientation: base.imageOrientation) + } + #endif + guard let blurredImage = result else { + assertionFailure("[Kingfisher] Can not make an blurred image within this context.") + return base + } + + return blurredImage + } + + public func addingBorder(_ border: Border) -> KFCrossPlatformImage + { + guard let _ = cgImage else { + assertionFailure("[Kingfisher] Blend mode image only works for CG-based image.") + return base + } + + let rect = CGRect(origin: .zero, size: size) + return draw(to: rect.size, inverting: false) { context in + + #if os(macOS) + base.draw(in: rect) + #else + base.draw(in: rect, blendMode: .normal, alpha: 1.0) + #endif + + + let strokeRect = rect.insetBy(dx: border.lineWidth / 2, dy: border.lineWidth / 2) + context.setStrokeColor(border.color.cgColor) + context.setAlpha(border.color.rgba.a) + + let line = pathForRoundCorner( + rect: strokeRect, + radius: border.radius, + corners: border.roundingCorners, + offsetBase: border.lineWidth + ) + line.lineCapStyle = .square + line.lineWidth = border.lineWidth + line.stroke() + + return false + } + } + + // MARK: Overlay + /// Creates an image from `base` image with a color overlay layer. + /// + /// - Parameters: + /// - color: The color should be use to overlay. + /// - fraction: Fraction of input color. From 0.0 to 1.0. 0.0 means solid color, + /// 1.0 means transparent overlay. + /// - Returns: An image with a color overlay applied. + /// + /// - Note: This method only works for CG-based image. The current image scale is kept. + /// For any non-CG-based image, `base` itself is returned. + public func overlaying(with color: KFCrossPlatformColor, fraction: CGFloat) -> KFCrossPlatformImage { + + guard let _ = cgImage else { + assertionFailure("[Kingfisher] Overlaying only works for CG-based image.") + return base + } + + let rect = CGRect(x: 0, y: 0, width: size.width, height: size.height) + return draw(to: rect.size, inverting: false) { context in + #if os(macOS) + base.draw(in: rect) + if fraction > 0 { + color.withAlphaComponent(1 - fraction).set() + rect.fill(using: .sourceAtop) + } + #else + color.set() + UIRectFill(rect) + base.draw(in: rect, blendMode: .destinationIn, alpha: 1.0) + + if fraction > 0 { + base.draw(in: rect, blendMode: .sourceAtop, alpha: fraction) + } + #endif + return false + } + } + + // MARK: Tint + /// Creates an image from `base` image with a color tint. + /// + /// - Parameter color: The color should be used to tint `base` + /// - Returns: An image with a color tint applied. + public func tinted(with color: KFCrossPlatformColor) -> KFCrossPlatformImage { + #if os(watchOS) + return base + #else + return apply(.tint(color)) + #endif + } + + // MARK: Color Control + + /// Create an image from `self` with color control. + /// + /// - Parameters: + /// - brightness: Brightness changing to image. + /// - contrast: Contrast changing to image. + /// - saturation: Saturation changing to image. + /// - inputEV: InputEV changing to image. + /// - Returns: An image with color control applied. + public func adjusted(brightness: CGFloat, contrast: CGFloat, saturation: CGFloat, inputEV: CGFloat) -> KFCrossPlatformImage { + #if os(watchOS) + return base + #else + return apply(.colorControl((brightness, contrast, saturation, inputEV))) + #endif + } + + /// Return an image with given scale. + /// + /// - Parameter scale: Target scale factor the new image should have. + /// - Returns: The image with target scale. If the base image is already in the scale, `base` will be returned. + public func scaled(to scale: CGFloat) -> KFCrossPlatformImage { + guard scale != self.scale else { + return base + } + guard let cgImage = cgImage else { + assertionFailure("[Kingfisher] Scaling only works for CG-based image.") + return base + } + return KingfisherWrapper.image(cgImage: cgImage, scale: scale, refImage: base) + } +} + +// MARK: - Decoding Image +extension KingfisherWrapper where Base: KFCrossPlatformImage { + + /// Returns the decoded image of the `base` image. It will draw the image in a plain context and return the data + /// from it. This could improve the drawing performance when an image is just created from data but not yet + /// displayed for the first time. + /// + /// - Note: This method only works for CG-based image. The current image scale is kept. + /// For any non-CG-based image or animated image, `base` itself is returned. + public var decoded: KFCrossPlatformImage { return decoded(scale: scale) } + + /// Returns decoded image of the `base` image at a given scale. It will draw the image in a plain context and + /// return the data from it. This could improve the drawing performance when an image is just created from + /// data but not yet displayed for the first time. + /// + /// - Parameter scale: The given scale of target image should be. + /// - Returns: The decoded image ready to be displayed. + /// + /// - Note: This method only works for CG-based image. The current image scale is kept. + /// For any non-CG-based image or animated image, `base` itself is returned. + public func decoded(scale: CGFloat) -> KFCrossPlatformImage { + // Prevent animated image (GIF) losing it's images + #if os(iOS) || os(visionOS) + if frameSource != nil { return base } + #else + if images != nil { return base } + #endif + + guard let imageRef = cgImage else { + assertionFailure("[Kingfisher] Decoding only works for CG-based image.") + return base + } + + let size = CGSize(width: CGFloat(imageRef.width) / scale, height: CGFloat(imageRef.height) / scale) + return draw(to: size, inverting: true, scale: scale) { context in + context.draw(imageRef, in: CGRect(origin: .zero, size: size)) + return true + } + } + + /// Returns decoded image of the `base` image at a given scale. It will draw the image in a plain context and + /// return the data from it. This could improve the drawing performance when an image is just created from + /// data but not yet displayed for the first time. + /// + /// - Parameter context: The context for drawing. + /// - Returns: The decoded image ready to be displayed. + /// + /// - Note: This method only works for CG-based image. The current image scale is kept. + /// For any non-CG-based image or animated image, `base` itself is returned. + public func decoded(on context: CGContext) -> KFCrossPlatformImage { + // Prevent animated image (GIF) losing it's images + #if os(iOS) || os(visionOS) + if frameSource != nil { return base } + #else + if images != nil { return base } + #endif + + guard let refImage = cgImage, + let decodedRefImage = refImage.decoded(on: context, scale: scale) else + { + assertionFailure("[Kingfisher] Decoding only works for CG-based image.") + return base + } + return KingfisherWrapper.image(cgImage: decodedRefImage, scale: scale, refImage: base) + } +} + +extension CGImage { + func decoded(on context: CGContext, scale: CGFloat) -> CGImage? { + let size = CGSize(width: CGFloat(self.width) / scale, height: CGFloat(self.height) / scale) + context.draw(self, in: CGRect(origin: .zero, size: size)) + guard let decodedImageRef = context.makeImage() else { + return nil + } + return decodedImageRef + } + + static func create(ref: CGImage) -> CGImage? { + guard let space = ref.colorSpace, let provider = ref.dataProvider else { + return nil + } + return CGImage( + width: ref.width, + height: ref.height, + bitsPerComponent: ref.bitsPerComponent, + bitsPerPixel: ref.bitsPerPixel, + bytesPerRow: ref.bytesPerRow, + space: space, + bitmapInfo: ref.bitmapInfo, + provider: provider, + decode: ref.decode, + shouldInterpolate: ref.shouldInterpolate, + intent: ref.renderingIntent + ) + } +} + +extension KingfisherWrapper where Base: KFCrossPlatformImage { + func draw( + to size: CGSize, + inverting: Bool, + scale: CGFloat? = nil, + refImage: KFCrossPlatformImage? = nil, + draw: (CGContext) -> Bool // Whether use the refImage (`true`) or ignore image orientation (`false`) + ) -> KFCrossPlatformImage + { + #if os(macOS) || os(watchOS) + let targetScale = scale ?? self.scale + GraphicsContext.begin(size: size, scale: targetScale) + guard let context = GraphicsContext.current(size: size, scale: targetScale, inverting: inverting, cgImage: cgImage) else { + assertionFailure("[Kingfisher] Failed to create CG context for blurring image.") + return base + } + defer { GraphicsContext.end() } + let useRefImage = draw(context) + guard let cgImage = context.makeImage() else { + return base + } + let ref = useRefImage ? (refImage ?? base) : nil + return KingfisherWrapper.image(cgImage: cgImage, scale: targetScale, refImage: ref) + #else + + let format = UIGraphicsImageRendererFormat.preferred() + format.scale = scale ?? self.scale + let renderer = UIGraphicsImageRenderer(size: size, format: format) + + var useRefImage: Bool = false + let image = renderer.image { rendererContext in + + let context = rendererContext.cgContext + if inverting { // If drawing a CGImage, we need to make context flipped. + context.scaleBy(x: 1.0, y: -1.0) + context.translateBy(x: 0, y: -size.height) + } + + useRefImage = draw(context) + } + if useRefImage { + guard let cgImage = image.cgImage else { + return base + } + let ref = refImage ?? base + return KingfisherWrapper.image(cgImage: cgImage, scale: format.scale, refImage: ref) + } else { + return image + } + #endif + } + + #if os(macOS) + func fixedForRetinaPixel(cgImage: CGImage, to size: CGSize) -> KFCrossPlatformImage { + + let image = KFCrossPlatformImage(cgImage: cgImage, size: base.size) + let rect = CGRect(origin: CGPoint(x: 0, y: 0), size: size) + + return draw(to: self.size, inverting: false) { context in + image.draw(in: rect, from: .zero, operation: .copy, fraction: 1.0) + return false + } + } + #endif +} diff --git a/Pods/Kingfisher/Sources/Image/ImageFormat.swift b/Pods/Kingfisher/Sources/Image/ImageFormat.swift new file mode 100644 index 0000000..464a855 --- /dev/null +++ b/Pods/Kingfisher/Sources/Image/ImageFormat.swift @@ -0,0 +1,130 @@ +// +// ImageFormat.swift +// Kingfisher +// +// Created by onevcat on 2018/09/28. +// +// Copyright (c) 2019 Wei Wang +// +// Permission is hereby granted, free of charge, to any person obtaining a copy +// of this software and associated documentation files (the "Software"), to deal +// in the Software without restriction, including without limitation the rights +// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +// copies of the Software, and to permit persons to whom the Software is +// furnished to do so, subject to the following conditions: +// +// The above copyright notice and this permission notice shall be included in +// all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN +// THE SOFTWARE. + +import Foundation + +/// Represents image format. +/// +/// - unknown: The format cannot be recognized or not supported yet. +/// - PNG: PNG image format. +/// - JPEG: JPEG image format. +/// - GIF: GIF image format. +public enum ImageFormat { + /// The format cannot be recognized or not supported yet. + case unknown + /// PNG image format. + case PNG + /// JPEG image format. + case JPEG + /// GIF image format. + case GIF + + struct HeaderData { + static var PNG: [UInt8] = [0x89, 0x50, 0x4E, 0x47, 0x0D, 0x0A, 0x1A, 0x0A] + static var JPEG_SOI: [UInt8] = [0xFF, 0xD8] + static var JPEG_IF: [UInt8] = [0xFF] + static var GIF: [UInt8] = [0x47, 0x49, 0x46] + } + + /// https://en.wikipedia.org/wiki/JPEG + public enum JPEGMarker { + case SOF0 //baseline + case SOF2 //progressive + case DHT //Huffman Table + case DQT //Quantization Table + case DRI //Restart Interval + case SOS //Start Of Scan + case RSTn(UInt8) //Restart + case APPn //Application-specific + case COM //Comment + case EOI //End Of Image + + var bytes: [UInt8] { + switch self { + case .SOF0: return [0xFF, 0xC0] + case .SOF2: return [0xFF, 0xC2] + case .DHT: return [0xFF, 0xC4] + case .DQT: return [0xFF, 0xDB] + case .DRI: return [0xFF, 0xDD] + case .SOS: return [0xFF, 0xDA] + case .RSTn(let n): return [0xFF, 0xD0 + n] + case .APPn: return [0xFF, 0xE0] + case .COM: return [0xFF, 0xFE] + case .EOI: return [0xFF, 0xD9] + } + } + } +} + + +extension Data: KingfisherCompatibleValue {} + +// MARK: - Misc Helpers +extension KingfisherWrapper where Base == Data { + /// Gets the image format corresponding to the data. + public var imageFormat: ImageFormat { + guard base.count > 8 else { return .unknown } + + var buffer = [UInt8](repeating: 0, count: 8) + base.copyBytes(to: &buffer, count: 8) + + if buffer == ImageFormat.HeaderData.PNG { + return .PNG + + } else if buffer[0] == ImageFormat.HeaderData.JPEG_SOI[0], + buffer[1] == ImageFormat.HeaderData.JPEG_SOI[1], + buffer[2] == ImageFormat.HeaderData.JPEG_IF[0] + { + return .JPEG + + } else if buffer[0] == ImageFormat.HeaderData.GIF[0], + buffer[1] == ImageFormat.HeaderData.GIF[1], + buffer[2] == ImageFormat.HeaderData.GIF[2] + { + return .GIF + } + + return .unknown + } + + public func contains(jpeg marker: ImageFormat.JPEGMarker) -> Bool { + guard imageFormat == .JPEG else { + return false + } + + let bytes = [UInt8](base) + let markerBytes = marker.bytes + for (index, item) in bytes.enumerated() where bytes.count > index + 1 { + guard + item == markerBytes.first, + bytes[index + 1] == markerBytes[1] else { + continue + } + return true + } + return false + } +} diff --git a/Pods/Kingfisher/Sources/Image/ImageProcessor.swift b/Pods/Kingfisher/Sources/Image/ImageProcessor.swift new file mode 100644 index 0000000..0a5dc0b --- /dev/null +++ b/Pods/Kingfisher/Sources/Image/ImageProcessor.swift @@ -0,0 +1,922 @@ +// +// ImageProcessor.swift +// Kingfisher +// +// Created by Wei Wang on 2016/08/26. +// +// Copyright (c) 2019 Wei Wang +// +// Permission is hereby granted, free of charge, to any person obtaining a copy +// of this software and associated documentation files (the "Software"), to deal +// in the Software without restriction, including without limitation the rights +// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +// copies of the Software, and to permit persons to whom the Software is +// furnished to do so, subject to the following conditions: +// +// The above copyright notice and this permission notice shall be included in +// all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN +// THE SOFTWARE. + +import Foundation +import CoreGraphics + +#if canImport(AppKit) && !targetEnvironment(macCatalyst) +import AppKit +#else +import UIKit +#endif + +/// Represents an item which could be processed by an `ImageProcessor`. +/// +/// - image: Input image. The processor should provide a way to apply +/// processing on this `image` and return the result image. +/// - data: Input data. The processor should provide a way to apply +/// processing on this `data` and return the result image. +public enum ImageProcessItem { + + /// Input image. The processor should provide a way to apply + /// processing on this `image` and return the result image. + case image(KFCrossPlatformImage) + + /// Input data. The processor should provide a way to apply + /// processing on this `data` and return the result image. + case data(Data) +} + +/// An `ImageProcessor` would be used to convert some downloaded data to an image. +public protocol ImageProcessor { + /// Identifier of the processor. It will be used to identify the processor when + /// caching and retrieving an image. You might want to make sure that processors with + /// same properties/functionality have the same identifiers, so correct processed images + /// could be retrieved with proper key. + /// + /// - Note: Do not supply an empty string for a customized processor, which is already reserved by + /// the `DefaultImageProcessor`. It is recommended to use a reverse domain name notation string of + /// your own for the identifier. + var identifier: String { get } + + /// Processes the input `ImageProcessItem` with this processor. + /// + /// - Parameters: + /// - item: Input item which will be processed by `self`. + /// - options: The parsed options when processing the item. + /// - Returns: The processed image. + /// + /// - Note: The return value should be `nil` if processing failed while converting an input item to image. + /// If `nil` received by the processing caller, an error will be reported and the process flow stops. + /// If the processing flow is not critical for your flow, then when the input item is already an image + /// (`.image` case) and there is any errors in the processing, you could return the input image itself + /// to keep the processing pipeline continuing. + /// - Note: Most processor only supports CG-based images. watchOS is not supported for processors containing + /// a filter, the input image will be returned directly on watchOS. + func process(item: ImageProcessItem, options: KingfisherParsedOptionsInfo) -> KFCrossPlatformImage? +} + +extension ImageProcessor { + + /// Appends an `ImageProcessor` to another. The identifier of the new `ImageProcessor` + /// will be "\(self.identifier)|>\(another.identifier)". + /// + /// - Parameter another: An `ImageProcessor` you want to append to `self`. + /// - Returns: The new `ImageProcessor` will process the image in the order + /// of the two processors concatenated. + public func append(another: ImageProcessor) -> ImageProcessor { + let newIdentifier = identifier.appending("|>\(another.identifier)") + return GeneralProcessor(identifier: newIdentifier) { + item, options in + if let image = self.process(item: item, options: options) { + return another.process(item: .image(image), options: options) + } else { + return nil + } + } + } +} + +func ==(left: ImageProcessor, right: ImageProcessor) -> Bool { + return left.identifier == right.identifier +} + +func !=(left: ImageProcessor, right: ImageProcessor) -> Bool { + return !(left == right) +} + +typealias ProcessorImp = ((ImageProcessItem, KingfisherParsedOptionsInfo) -> KFCrossPlatformImage?) +struct GeneralProcessor: ImageProcessor { + let identifier: String + let p: ProcessorImp + func process(item: ImageProcessItem, options: KingfisherParsedOptionsInfo) -> KFCrossPlatformImage? { + return p(item, options) + } +} + +/// The default processor. It converts the input data to a valid image. +/// Images of .PNG, .JPEG and .GIF format are supported. +/// If an image item is given as `.image` case, `DefaultImageProcessor` will +/// do nothing on it and return the associated image. +public struct DefaultImageProcessor: ImageProcessor { + + /// A default `DefaultImageProcessor` could be used across. + public static let `default` = DefaultImageProcessor() + + /// Identifier of the processor. + /// - Note: See documentation of `ImageProcessor` protocol for more. + public let identifier = "" + + /// Creates a `DefaultImageProcessor`. Use `DefaultImageProcessor.default` to get an instance, + /// if you do not have a good reason to create your own `DefaultImageProcessor`. + public init() {} + + /// Processes the input `ImageProcessItem` with this processor. + /// + /// - Parameters: + /// - item: Input item which will be processed by `self`. + /// - options: Options when processing the item. + /// - Returns: The processed image. + /// + /// - Note: See documentation of `ImageProcessor` protocol for more. + public func process(item: ImageProcessItem, options: KingfisherParsedOptionsInfo) -> KFCrossPlatformImage? { + switch item { + case .image(let image): + return image.kf.scaled(to: options.scaleFactor) + case .data(let data): + return KingfisherWrapper.image(data: data, options: options.imageCreatingOptions) + } + } +} + +/// Represents the rect corner setting when processing a round corner image. +public struct RectCorner: OptionSet { + + /// Raw value of the rect corner. + public let rawValue: Int + + /// Represents the top left corner. + public static let topLeft = RectCorner(rawValue: 1 << 0) + + /// Represents the top right corner. + public static let topRight = RectCorner(rawValue: 1 << 1) + + /// Represents the bottom left corner. + public static let bottomLeft = RectCorner(rawValue: 1 << 2) + + /// Represents the bottom right corner. + public static let bottomRight = RectCorner(rawValue: 1 << 3) + + /// Represents all corners. + public static let all: RectCorner = [.topLeft, .topRight, .bottomLeft, .bottomRight] + + /// Creates a `RectCorner` option set with a given value. + /// + /// - Parameter rawValue: The value represents a certain corner option. + public init(rawValue: Int) { + self.rawValue = rawValue + } + + var cornerIdentifier: String { + if self == .all { + return "" + } + return "_corner(\(rawValue))" + } +} + +#if !os(macOS) +/// Processor for adding an blend mode to images. Only CG-based images are supported. +public struct BlendImageProcessor: ImageProcessor { + + /// Identifier of the processor. + /// - Note: See documentation of `ImageProcessor` protocol for more. + public let identifier: String + + /// Blend Mode will be used to blend the input image. + public let blendMode: CGBlendMode + + /// Alpha will be used when blend image. + public let alpha: CGFloat + + /// Background color of the output image. If `nil`, it will stay transparent. + public let backgroundColor: KFCrossPlatformColor? + + /// Creates a `BlendImageProcessor`. + /// + /// - Parameters: + /// - blendMode: Blend Mode will be used to blend the input image. + /// - alpha: Alpha will be used when blend image. From 0.0 to 1.0. 1.0 means solid image, + /// 0.0 means transparent image (not visible at all). Default is 1.0. + /// - backgroundColor: Background color to apply for the output image. Default is `nil`. + public init(blendMode: CGBlendMode, alpha: CGFloat = 1.0, backgroundColor: KFCrossPlatformColor? = nil) { + self.blendMode = blendMode + self.alpha = alpha + self.backgroundColor = backgroundColor + var identifier = "com.onevcat.Kingfisher.BlendImageProcessor(\(blendMode.rawValue),\(alpha))" + if let color = backgroundColor { + identifier.append("_\(color.rgbaDescription)") + } + self.identifier = identifier + } + + /// Processes the input `ImageProcessItem` with this processor. + /// + /// - Parameters: + /// - item: Input item which will be processed by `self`. + /// - options: Options when processing the item. + /// - Returns: The processed image. + /// + /// - Note: See documentation of `ImageProcessor` protocol for more. + public func process(item: ImageProcessItem, options: KingfisherParsedOptionsInfo) -> KFCrossPlatformImage? { + switch item { + case .image(let image): + return image.kf.scaled(to: options.scaleFactor) + .kf.image(withBlendMode: blendMode, alpha: alpha, backgroundColor: backgroundColor) + case .data: + return (DefaultImageProcessor.default |> self).process(item: item, options: options) + } + } +} +#endif + +#if os(macOS) +/// Processor for adding an compositing operation to images. Only CG-based images are supported in macOS. +public struct CompositingImageProcessor: ImageProcessor { + + /// Identifier of the processor. + /// - Note: See documentation of `ImageProcessor` protocol for more. + public let identifier: String + + /// Compositing operation will be used to the input image. + public let compositingOperation: NSCompositingOperation + + /// Alpha will be used when compositing image. + public let alpha: CGFloat + + /// Background color of the output image. If `nil`, it will stay transparent. + public let backgroundColor: KFCrossPlatformColor? + + /// Creates a `CompositingImageProcessor` + /// + /// - Parameters: + /// - compositingOperation: Compositing operation will be used to the input image. + /// - alpha: Alpha will be used when compositing image. + /// From 0.0 to 1.0. 1.0 means solid image, 0.0 means transparent image. + /// Default is 1.0. + /// - backgroundColor: Background color to apply for the output image. Default is `nil`. + public init(compositingOperation: NSCompositingOperation, + alpha: CGFloat = 1.0, + backgroundColor: KFCrossPlatformColor? = nil) + { + self.compositingOperation = compositingOperation + self.alpha = alpha + self.backgroundColor = backgroundColor + var identifier = "com.onevcat.Kingfisher.CompositingImageProcessor(\(compositingOperation.rawValue),\(alpha))" + if let color = backgroundColor { + identifier.append("_\(color.rgbaDescription)") + } + self.identifier = identifier + } + + /// Processes the input `ImageProcessItem` with this processor. + /// + /// - Parameters: + /// - item: Input item which will be processed by `self`. + /// - options: Options when processing the item. + /// - Returns: The processed image. + /// + /// - Note: See documentation of `ImageProcessor` protocol for more. + public func process(item: ImageProcessItem, options: KingfisherParsedOptionsInfo) -> KFCrossPlatformImage? { + switch item { + case .image(let image): + return image.kf.scaled(to: options.scaleFactor) + .kf.image( + withCompositingOperation: compositingOperation, + alpha: alpha, + backgroundColor: backgroundColor) + case .data: + return (DefaultImageProcessor.default |> self).process(item: item, options: options) + } + } +} +#endif + +/// Represents a radius specified in a `RoundCornerImageProcessor`. +public enum Radius { + /// The radius should be calculated as a fraction of the image width. Typically the associated value should be + /// between 0 and 0.5, where 0 represents no radius and 0.5 represents using half of the image width. + case widthFraction(CGFloat) + /// The radius should be calculated as a fraction of the image height. Typically the associated value should be + /// between 0 and 0.5, where 0 represents no radius and 0.5 represents using half of the image height. + case heightFraction(CGFloat) + /// Use a fixed point value as the round corner radius. + case point(CGFloat) + + var radiusIdentifier: String { + switch self { + case .widthFraction(let f): + return "w_frac_\(f)" + case .heightFraction(let f): + return "h_frac_\(f)" + case .point(let p): + return p.description + } + } + + public func compute(with size: CGSize) -> CGFloat { + let cornerRadius: CGFloat + switch self { + case .point(let point): + cornerRadius = point + case .widthFraction(let widthFraction): + cornerRadius = size.width * widthFraction + case .heightFraction(let heightFraction): + cornerRadius = size.height * heightFraction + } + return cornerRadius + } +} + +/// Processor for making round corner images. Only CG-based images are supported in macOS, +/// if a non-CG image passed in, the processor will do nothing. +/// +/// - Note: The input image will be rendered with round corner pixels removed. If the image itself does not contain +/// alpha channel (for example, a JPEG image), the processed image will contain an alpha channel in memory in order +/// to show correctly. However, when cached to disk, Kingfisher respects the original image format by default. That +/// means the alpha channel will be removed for these images. When you load the processed image from cache again, you +/// will lose transparent corner. +/// +/// You could use `FormatIndicatedCacheSerializer.png` to force Kingfisher to serialize the image to PNG format in this +/// case. +/// +public struct RoundCornerImageProcessor: ImageProcessor { + + /// Identifier of the processor. + /// - Note: See documentation of `ImageProcessor` protocol for more. + public let identifier: String + + /// The radius will be applied in processing. Specify a certain point value with `.point`, or a fraction of the + /// target image with `.widthFraction`. or `.heightFraction`. For example, given a square image with width and + /// height equals, `.widthFraction(0.5)` means use half of the length of size and makes the final image a round one. + public let radius: Radius + + /// The target corners which will be applied rounding. + public let roundingCorners: RectCorner + + /// Target size of output image should be. If `nil`, the image will keep its original size after processing. + public let targetSize: CGSize? + + /// Background color of the output image. If `nil`, it will use a transparent background. + public let backgroundColor: KFCrossPlatformColor? + + /// Creates a `RoundCornerImageProcessor`. + /// + /// - Parameters: + /// - cornerRadius: Corner radius in point will be applied in processing. + /// - targetSize: Target size of output image should be. If `nil`, + /// the image will keep its original size after processing. + /// Default is `nil`. + /// - corners: The target corners which will be applied rounding. Default is `.all`. + /// - backgroundColor: Background color to apply for the output image. Default is `nil`. + /// + /// - Note: + /// + /// This initializer accepts a concrete point value for `cornerRadius`. If you do not know the image size, but still + /// want to apply a full round-corner (making the final image a round one), or specify the corner radius as a + /// fraction of one dimension of the target image, use the `Radius` version instead. + /// + public init( + cornerRadius: CGFloat, + targetSize: CGSize? = nil, + roundingCorners corners: RectCorner = .all, + backgroundColor: KFCrossPlatformColor? = nil + ) + { + let radius = Radius.point(cornerRadius) + self.init(radius: radius, targetSize: targetSize, roundingCorners: corners, backgroundColor: backgroundColor) + } + + /// Creates a `RoundCornerImageProcessor`. + /// + /// - Parameters: + /// - radius: The radius will be applied in processing. + /// - targetSize: Target size of output image should be. If `nil`, + /// the image will keep its original size after processing. + /// Default is `nil`. + /// - corners: The target corners which will be applied rounding. Default is `.all`. + /// - backgroundColor: Background color to apply for the output image. Default is `nil`. + public init( + radius: Radius, + targetSize: CGSize? = nil, + roundingCorners corners: RectCorner = .all, + backgroundColor: KFCrossPlatformColor? = nil + ) + { + self.radius = radius + self.targetSize = targetSize + self.roundingCorners = corners + self.backgroundColor = backgroundColor + + self.identifier = { + var identifier = "" + + if let size = targetSize { + identifier = "com.onevcat.Kingfisher.RoundCornerImageProcessor" + + "(\(radius.radiusIdentifier)_\(size)\(corners.cornerIdentifier))" + } else { + identifier = "com.onevcat.Kingfisher.RoundCornerImageProcessor" + + "(\(radius.radiusIdentifier)\(corners.cornerIdentifier))" + } + if let backgroundColor = backgroundColor { + identifier += "_\(backgroundColor)" + } + + return identifier + }() + } + + /// Processes the input `ImageProcessItem` with this processor. + /// + /// - Parameters: + /// - item: Input item which will be processed by `self`. + /// - options: Options when processing the item. + /// - Returns: The processed image. + /// + /// - Note: See documentation of `ImageProcessor` protocol for more. + public func process(item: ImageProcessItem, options: KingfisherParsedOptionsInfo) -> KFCrossPlatformImage? { + switch item { + case .image(let image): + let size = targetSize ?? image.kf.size + return image.kf.scaled(to: options.scaleFactor) + .kf.image( + withRadius: radius, + fit: size, + roundingCorners: roundingCorners, + backgroundColor: backgroundColor) + case .data: + return (DefaultImageProcessor.default |> self).process(item: item, options: options) + } + } +} + +public struct Border { + public var color: KFCrossPlatformColor + public var lineWidth: CGFloat + + /// The radius will be applied in processing. Specify a certain point value with `.point`, or a fraction of the + /// target image with `.widthFraction`. or `.heightFraction`. For example, given a square image with width and + /// height equals, `.widthFraction(0.5)` means use half of the length of size and makes the final image a round one. + public var radius: Radius + + /// The target corners which will be applied rounding. + public var roundingCorners: RectCorner + + public init( + color: KFCrossPlatformColor = .black, + lineWidth: CGFloat = 4, + radius: Radius = .point(0), + roundingCorners: RectCorner = .all + ) { + self.color = color + self.lineWidth = lineWidth + self.radius = radius + self.roundingCorners = roundingCorners + } + + var identifier: String { + "\(color.rgbaDescription)_\(lineWidth)_\(radius.radiusIdentifier)_\(roundingCorners.cornerIdentifier)" + } +} + +public struct BorderImageProcessor: ImageProcessor { + public var identifier: String { "com.onevcat.Kingfisher.RoundCornerImageProcessor(\(border)" } + public let border: Border + + public init(border: Border) { + self.border = border + } + + public func process(item: ImageProcessItem, options: KingfisherParsedOptionsInfo) -> KFCrossPlatformImage? { + switch item { + case .image(let image): + return image.kf.addingBorder(border) + case .data: + return (DefaultImageProcessor.default |> self).process(item: item, options: options) + } + } +} + +/// Represents how a size adjusts itself to fit a target size. +/// +/// - none: Not scale the content. +/// - aspectFit: Scales the content to fit the size of the view by maintaining the aspect ratio. +/// - aspectFill: Scales the content to fill the size of the view. +public enum ContentMode { + /// Not scale the content. + case none + /// Scales the content to fit the size of the view by maintaining the aspect ratio. + case aspectFit + /// Scales the content to fill the size of the view. + case aspectFill +} + +/// Processor for resizing images. +/// If you need to resize a data represented image to a smaller size, use `DownsamplingImageProcessor` +/// instead, which is more efficient and uses less memory. +public struct ResizingImageProcessor: ImageProcessor { + + /// Identifier of the processor. + /// - Note: See documentation of `ImageProcessor` protocol for more. + public let identifier: String + + /// The reference size for resizing operation in point. + public let referenceSize: CGSize + + /// Target content mode of output image should be. + /// Default is `.none`. + public let targetContentMode: ContentMode + + /// Creates a `ResizingImageProcessor`. + /// + /// - Parameters: + /// - referenceSize: The reference size for resizing operation in point. + /// - mode: Target content mode of output image should be. + /// + /// - Note: + /// The instance of `ResizingImageProcessor` will follow its `mode` property + /// and try to resizing the input images to fit or fill the `referenceSize`. + /// That means if you are using a `mode` besides of `.none`, you may get an + /// image with its size not be the same as the `referenceSize`. + /// + /// **Example**: With input image size: {100, 200}, + /// `referenceSize`: {100, 100}, `mode`: `.aspectFit`, + /// you will get an output image with size of {50, 100}, which "fit"s + /// the `referenceSize`. + /// + /// If you need an output image exactly to be a specified size, append or use + /// a `CroppingImageProcessor`. + public init(referenceSize: CGSize, mode: ContentMode = .none) { + self.referenceSize = referenceSize + self.targetContentMode = mode + + if mode == .none { + self.identifier = "com.onevcat.Kingfisher.ResizingImageProcessor(\(referenceSize))" + } else { + self.identifier = "com.onevcat.Kingfisher.ResizingImageProcessor(\(referenceSize), \(mode))" + } + } + + /// Processes the input `ImageProcessItem` with this processor. + /// + /// - Parameters: + /// - item: Input item which will be processed by `self`. + /// - options: Options when processing the item. + /// - Returns: The processed image. + /// + /// - Note: See documentation of `ImageProcessor` protocol for more. + public func process(item: ImageProcessItem, options: KingfisherParsedOptionsInfo) -> KFCrossPlatformImage? { + switch item { + case .image(let image): + return image.kf.scaled(to: options.scaleFactor) + .kf.resize(to: referenceSize, for: targetContentMode) + case .data: + return (DefaultImageProcessor.default |> self).process(item: item, options: options) + } + } +} + +/// Processor for adding blur effect to images. `Accelerate.framework` is used underhood for +/// a better performance. A simulated Gaussian blur with specified blur radius will be applied. +public struct BlurImageProcessor: ImageProcessor { + + /// Identifier of the processor. + /// - Note: See documentation of `ImageProcessor` protocol for more. + public let identifier: String + + /// Blur radius for the simulated Gaussian blur. + public let blurRadius: CGFloat + + /// Creates a `BlurImageProcessor` + /// + /// - parameter blurRadius: Blur radius for the simulated Gaussian blur. + public init(blurRadius: CGFloat) { + self.blurRadius = blurRadius + self.identifier = "com.onevcat.Kingfisher.BlurImageProcessor(\(blurRadius))" + } + + /// Processes the input `ImageProcessItem` with this processor. + /// + /// - Parameters: + /// - item: Input item which will be processed by `self`. + /// - options: Options when processing the item. + /// - Returns: The processed image. + /// + /// - Note: See documentation of `ImageProcessor` protocol for more. + public func process(item: ImageProcessItem, options: KingfisherParsedOptionsInfo) -> KFCrossPlatformImage? { + switch item { + case .image(let image): + let radius = blurRadius * options.scaleFactor + return image.kf.scaled(to: options.scaleFactor) + .kf.blurred(withRadius: radius) + case .data: + return (DefaultImageProcessor.default |> self).process(item: item, options: options) + } + } +} + +/// Processor for adding an overlay to images. Only CG-based images are supported in macOS. +public struct OverlayImageProcessor: ImageProcessor { + + /// Identifier of the processor. + /// - Note: See documentation of `ImageProcessor` protocol for more. + public let identifier: String + + /// Overlay color will be used to overlay the input image. + public let overlay: KFCrossPlatformColor + + /// Fraction will be used when overlay the color to image. + public let fraction: CGFloat + + /// Creates an `OverlayImageProcessor` + /// + /// - parameter overlay: Overlay color will be used to overlay the input image. + /// - parameter fraction: Fraction will be used when overlay the color to image. + /// From 0.0 to 1.0. 0.0 means solid color, 1.0 means transparent overlay. + public init(overlay: KFCrossPlatformColor, fraction: CGFloat = 0.5) { + self.overlay = overlay + self.fraction = fraction + self.identifier = "com.onevcat.Kingfisher.OverlayImageProcessor(\(overlay.rgbaDescription)_\(fraction))" + } + + /// Processes the input `ImageProcessItem` with this processor. + /// + /// - Parameters: + /// - item: Input item which will be processed by `self`. + /// - options: Options when processing the item. + /// - Returns: The processed image. + /// + /// - Note: See documentation of `ImageProcessor` protocol for more. + public func process(item: ImageProcessItem, options: KingfisherParsedOptionsInfo) -> KFCrossPlatformImage? { + switch item { + case .image(let image): + return image.kf.scaled(to: options.scaleFactor) + .kf.overlaying(with: overlay, fraction: fraction) + case .data: + return (DefaultImageProcessor.default |> self).process(item: item, options: options) + } + } +} + +/// Processor for tint images with color. Only CG-based images are supported. +public struct TintImageProcessor: ImageProcessor { + + /// Identifier of the processor. + /// - Note: See documentation of `ImageProcessor` protocol for more. + public let identifier: String + + /// Tint color will be used to tint the input image. + public let tint: KFCrossPlatformColor + + /// Creates a `TintImageProcessor` + /// + /// - parameter tint: Tint color will be used to tint the input image. + public init(tint: KFCrossPlatformColor) { + self.tint = tint + self.identifier = "com.onevcat.Kingfisher.TintImageProcessor(\(tint.rgbaDescription))" + } + + /// Processes the input `ImageProcessItem` with this processor. + /// + /// - Parameters: + /// - item: Input item which will be processed by `self`. + /// - options: Options when processing the item. + /// - Returns: The processed image. + /// + /// - Note: See documentation of `ImageProcessor` protocol for more. + public func process(item: ImageProcessItem, options: KingfisherParsedOptionsInfo) -> KFCrossPlatformImage? { + switch item { + case .image(let image): + return image.kf.scaled(to: options.scaleFactor) + .kf.tinted(with: tint) + case .data: + return (DefaultImageProcessor.default |> self).process(item: item, options: options) + } + } +} + +/// Processor for applying some color control to images. Only CG-based images are supported. +/// watchOS is not supported. +public struct ColorControlsProcessor: ImageProcessor { + + /// Identifier of the processor. + /// - Note: See documentation of `ImageProcessor` protocol for more. + public let identifier: String + + /// Brightness changing to image. + public let brightness: CGFloat + + /// Contrast changing to image. + public let contrast: CGFloat + + /// Saturation changing to image. + public let saturation: CGFloat + + /// InputEV changing to image. + public let inputEV: CGFloat + + /// Creates a `ColorControlsProcessor` + /// + /// - Parameters: + /// - brightness: Brightness changing to image. + /// - contrast: Contrast changing to image. + /// - saturation: Saturation changing to image. + /// - inputEV: InputEV changing to image. + public init(brightness: CGFloat, contrast: CGFloat, saturation: CGFloat, inputEV: CGFloat) { + self.brightness = brightness + self.contrast = contrast + self.saturation = saturation + self.inputEV = inputEV + self.identifier = "com.onevcat.Kingfisher.ColorControlsProcessor(\(brightness)_\(contrast)_\(saturation)_\(inputEV))" + } + + /// Processes the input `ImageProcessItem` with this processor. + /// + /// - Parameters: + /// - item: Input item which will be processed by `self`. + /// - options: Options when processing the item. + /// - Returns: The processed image. + /// + /// - Note: See documentation of `ImageProcessor` protocol for more. + public func process(item: ImageProcessItem, options: KingfisherParsedOptionsInfo) -> KFCrossPlatformImage? { + switch item { + case .image(let image): + return image.kf.scaled(to: options.scaleFactor) + .kf.adjusted(brightness: brightness, contrast: contrast, saturation: saturation, inputEV: inputEV) + case .data: + return (DefaultImageProcessor.default |> self).process(item: item, options: options) + } + } +} + +/// Processor for applying black and white effect to images. Only CG-based images are supported. +/// watchOS is not supported. +public struct BlackWhiteProcessor: ImageProcessor { + + /// Identifier of the processor. + /// - Note: See documentation of `ImageProcessor` protocol for more. + public let identifier = "com.onevcat.Kingfisher.BlackWhiteProcessor" + + /// Creates a `BlackWhiteProcessor` + public init() {} + + /// Processes the input `ImageProcessItem` with this processor. + /// + /// - Parameters: + /// - item: Input item which will be processed by `self`. + /// - options: Options when processing the item. + /// - Returns: The processed image. + /// + /// - Note: See documentation of `ImageProcessor` protocol for more. + public func process(item: ImageProcessItem, options: KingfisherParsedOptionsInfo) -> KFCrossPlatformImage? { + return ColorControlsProcessor(brightness: 0.0, contrast: 1.0, saturation: 0.0, inputEV: 0.7) + .process(item: item, options: options) + } +} + +/// Processor for cropping an image. Only CG-based images are supported. +/// watchOS is not supported. +public struct CroppingImageProcessor: ImageProcessor { + + /// Identifier of the processor. + /// - Note: See documentation of `ImageProcessor` protocol for more. + public let identifier: String + + /// Target size of output image should be. + public let size: CGSize + + /// Anchor point from which the output size should be calculate. + /// The anchor point is consisted by two values between 0.0 and 1.0. + /// It indicates a related point in current image. + /// See `CroppingImageProcessor.init(size:anchor:)` for more. + public let anchor: CGPoint + + /// Creates a `CroppingImageProcessor`. + /// + /// - Parameters: + /// - size: Target size of output image should be. + /// - anchor: The anchor point from which the size should be calculated. + /// Default is `CGPoint(x: 0.5, y: 0.5)`, which means the center of input image. + /// - Note: + /// The anchor point is consisted by two values between 0.0 and 1.0. + /// It indicates a related point in current image, eg: (0.0, 0.0) for top-left + /// corner, (0.5, 0.5) for center and (1.0, 1.0) for bottom-right corner. + /// The `size` property of `CroppingImageProcessor` will be used along with + /// `anchor` to calculate a target rectangle in the size of image. + /// + /// The target size will be automatically calculated with a reasonable behavior. + /// For example, when you have an image size of `CGSize(width: 100, height: 100)`, + /// and a target size of `CGSize(width: 20, height: 20)`: + /// - with a (0.0, 0.0) anchor (top-left), the crop rect will be `{0, 0, 20, 20}`; + /// - with a (0.5, 0.5) anchor (center), it will be `{40, 40, 20, 20}` + /// - while with a (1.0, 1.0) anchor (bottom-right), it will be `{80, 80, 20, 20}` + public init(size: CGSize, anchor: CGPoint = CGPoint(x: 0.5, y: 0.5)) { + self.size = size + self.anchor = anchor + self.identifier = "com.onevcat.Kingfisher.CroppingImageProcessor(\(size)_\(anchor))" + } + + /// Processes the input `ImageProcessItem` with this processor. + /// + /// - Parameters: + /// - item: Input item which will be processed by `self`. + /// - options: Options when processing the item. + /// - Returns: The processed image. + /// + /// - Note: See documentation of `ImageProcessor` protocol for more. + public func process(item: ImageProcessItem, options: KingfisherParsedOptionsInfo) -> KFCrossPlatformImage? { + switch item { + case .image(let image): + return image.kf.scaled(to: options.scaleFactor) + .kf.crop(to: size, anchorOn: anchor) + case .data: return (DefaultImageProcessor.default |> self).process(item: item, options: options) + } + } +} + +/// Processor for downsampling an image. Compared to `ResizingImageProcessor`, this processor +/// does not render the images to resize. Instead, it downsamples the input data directly to an +/// image. It is a more efficient than `ResizingImageProcessor`. Prefer to use `DownsamplingImageProcessor` as possible +/// as you can than the `ResizingImageProcessor`. +/// +/// Only CG-based images are supported. Animated images (like GIF) is not supported. +public struct DownsamplingImageProcessor: ImageProcessor { + + /// Target size of output image should be. It should be smaller than the size of + /// input image. If it is larger, the result image will be the same size of input + /// data without downsampling. + public let size: CGSize + + /// Identifier of the processor. + /// - Note: See documentation of `ImageProcessor` protocol for more. + public let identifier: String + + /// Creates a `DownsamplingImageProcessor`. + /// + /// - Parameter size: The target size of the downsample operation. + public init(size: CGSize) { + self.size = size + self.identifier = "com.onevcat.Kingfisher.DownsamplingImageProcessor(\(size))" + } + + /// Processes the input `ImageProcessItem` with this processor. + /// + /// - Parameters: + /// - item: Input item which will be processed by `self`. + /// - options: Options when processing the item. + /// - Returns: The processed image. + /// + /// - Note: See documentation of `ImageProcessor` protocol for more. + public func process(item: ImageProcessItem, options: KingfisherParsedOptionsInfo) -> KFCrossPlatformImage? { + switch item { + case .image(let image): + guard let data = image.kf.data(format: .unknown) else { + return nil + } + return KingfisherWrapper.downsampledImage(data: data, to: size, scale: options.scaleFactor) + case .data(let data): + return KingfisherWrapper.downsampledImage(data: data, to: size, scale: options.scaleFactor) + } + } +} + +infix operator |>: AdditionPrecedence +public func |>(left: ImageProcessor, right: ImageProcessor) -> ImageProcessor { + return left.append(another: right) +} + +extension KFCrossPlatformColor { + + var rgba: (r: CGFloat, g: CGFloat, b: CGFloat, a: CGFloat) { + var r: CGFloat = 0 + var g: CGFloat = 0 + var b: CGFloat = 0 + var a: CGFloat = 0 + + #if os(macOS) + (usingColorSpace(.extendedSRGB) ?? self).getRed(&r, green: &g, blue: &b, alpha: &a) + #else + getRed(&r, green: &g, blue: &b, alpha: &a) + #endif + + return (r, g, b, a) + } + + var rgbaDescription: String { + let components = self.rgba + return String(format: "(%.2f,%.2f,%.2f,%.2f)", components.r, components.g, components.b, components.a) + } +} diff --git a/Pods/Kingfisher/Sources/Image/ImageProgressive.swift b/Pods/Kingfisher/Sources/Image/ImageProgressive.swift new file mode 100644 index 0000000..8ce8f32 --- /dev/null +++ b/Pods/Kingfisher/Sources/Image/ImageProgressive.swift @@ -0,0 +1,353 @@ +// +// ImageProgressive.swift +// Kingfisher +// +// Created by lixiang on 2019/5/10. +// +// Copyright (c) 2019 Wei Wang +// +// Permission is hereby granted, free of charge, to any person obtaining a copy +// of this software and associated documentation files (the "Software"), to deal +// in the Software without restriction, including without limitation the rights +// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +// copies of the Software, and to permit persons to whom the Software is +// furnished to do so, subject to the following conditions: +// +// The above copyright notice and this permission notice shall be included in +// all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN +// THE SOFTWARE. + +import Foundation +import CoreGraphics +#if os(macOS) +import AppKit +#else +import UIKit +#endif + +private let sharedProcessingQueue: CallbackQueue = + .dispatch(DispatchQueue(label: "com.onevcat.Kingfisher.ImageDownloader.Process")) + +public struct ImageProgressive { + + /// The updating strategy when an intermediate progressive image is generated and about to be set to the hosting view. + /// + /// - default: Use the progressive image as it is. It is the standard behavior when handling the progressive image. + /// - keepCurrent: Discard this progressive image and keep the current displayed one. + /// - replace: Replace the image to a new one. If the progressive loading is initialized by a view extension in + /// Kingfisher, the replacing image will be used to update the view. + public enum UpdatingStrategy { + case `default` + case keepCurrent + case replace(KFCrossPlatformImage?) + } + + /// A default `ImageProgressive` could be used across. It blurs the progressive loading with the fastest + /// scan enabled and scan interval as 0. + @available(*, deprecated, message: "Getting a default `ImageProgressive` is deprecated due to its syntax symatic is not clear. Use `ImageProgressive.init` instead.", renamed: "init()") + public static let `default` = ImageProgressive( + isBlur: true, + isFastestScan: true, + scanInterval: 0 + ) + + /// Whether to enable blur effect processing + let isBlur: Bool + /// Whether to enable the fastest scan + let isFastestScan: Bool + /// Minimum time interval for each scan + let scanInterval: TimeInterval + + /// Called when an intermediate image is prepared and about to be set to the image view. The return value of this + /// delegate will be used to update the hosting view, if any. Otherwise, if there is no hosting view (a.k.a the + /// image retrieving is not happening from a view extension method), the returned `UpdatingStrategy` is ignored. + public let onImageUpdated = Delegate() + + /// Creates an `ImageProgressive` value with default sets. It blurs the progressive loading with the fastest + /// scan enabled and scan interval as 0. + public init() { + self.init(isBlur: true, isFastestScan: true, scanInterval: 0) + } + + /// Creates an `ImageProgressive` value the given values. + /// - Parameters: + /// - isBlur: Whether to enable blur effect processing. + /// - isFastestScan: Whether to enable the fastest scan. + /// - scanInterval: Minimum time interval for each scan. + public init(isBlur: Bool, + isFastestScan: Bool, + scanInterval: TimeInterval + ) + { + self.isBlur = isBlur + self.isFastestScan = isFastestScan + self.scanInterval = scanInterval + } +} + +final class ImageProgressiveProvider: DataReceivingSideEffect { + + var onShouldApply: () -> Bool = { return true } + + func onDataReceived(_ session: URLSession, task: SessionDataTask, data: Data) { + + DispatchQueue.main.async { + guard self.onShouldApply() else { return } + self.update(data: task.mutableData, with: task.callbacks) + } + } + + private let option: ImageProgressive + private let refresh: (KFCrossPlatformImage) -> Void + + private let decoder: ImageProgressiveDecoder + private let queue = ImageProgressiveSerialQueue() + + init?(_ options: KingfisherParsedOptionsInfo, + refresh: @escaping (KFCrossPlatformImage) -> Void) { + guard let option = options.progressiveJPEG else { return nil } + + self.option = option + self.refresh = refresh + self.decoder = ImageProgressiveDecoder( + option, + processingQueue: options.processingQueue ?? sharedProcessingQueue, + creatingOptions: options.imageCreatingOptions + ) + } + + func update(data: Data, with callbacks: [SessionDataTask.TaskCallback]) { + guard !data.isEmpty else { return } + + queue.add(minimum: option.scanInterval) { completion in + + func decode(_ data: Data) { + self.decoder.decode(data, with: callbacks) { image in + defer { completion() } + guard self.onShouldApply() else { return } + guard let image = image else { return } + self.refresh(image) + } + } + + let semaphore = DispatchSemaphore(value: 0) + var onShouldApply: Bool = false + + CallbackQueue.mainAsync.execute { + onShouldApply = self.onShouldApply() + semaphore.signal() + } + semaphore.wait() + guard onShouldApply else { + self.queue.clean() + completion() + return + } + + if self.option.isFastestScan { + decode(self.decoder.scanning(data) ?? Data()) + } else { + self.decoder.scanning(data).forEach { decode($0) } + } + } + } +} + +private final class ImageProgressiveDecoder { + + private let option: ImageProgressive + private let processingQueue: CallbackQueue + private let creatingOptions: ImageCreatingOptions + private(set) var scannedCount = 0 + private(set) var scannedIndex = -1 + + init(_ option: ImageProgressive, + processingQueue: CallbackQueue, + creatingOptions: ImageCreatingOptions) { + self.option = option + self.processingQueue = processingQueue + self.creatingOptions = creatingOptions + } + + func scanning(_ data: Data) -> [Data] { + guard data.kf.contains(jpeg: .SOF2) else { + return [] + } + guard scannedIndex + 1 < data.count else { + return [] + } + + var datas: [Data] = [] + var index = scannedIndex + 1 + var count = scannedCount + + while index < data.count - 1 { + scannedIndex = index + // 0xFF, 0xDA - Start Of Scan + let SOS = ImageFormat.JPEGMarker.SOS.bytes + if data[index] == SOS[0], data[index + 1] == SOS[1] { + if count > 0 { + datas.append(data[0 ..< index]) + } + count += 1 + } + index += 1 + } + + // Found more scans this the previous time + guard count > scannedCount else { return [] } + scannedCount = count + + // `> 1` checks that we've received a first scan (SOS) and then received + // and also received a second scan (SOS). This way we know that we have + // at least one full scan available. + guard count > 1 else { return [] } + return datas + } + + func scanning(_ data: Data) -> Data? { + guard data.kf.contains(jpeg: .SOF2) else { + return nil + } + guard scannedIndex + 1 < data.count else { + return nil + } + + var index = scannedIndex + 1 + var count = scannedCount + var lastSOSIndex = 0 + + while index < data.count - 1 { + scannedIndex = index + // 0xFF, 0xDA - Start Of Scan + let SOS = ImageFormat.JPEGMarker.SOS.bytes + if data[index] == SOS[0], data[index + 1] == SOS[1] { + lastSOSIndex = index + count += 1 + } + index += 1 + } + + // Found more scans this the previous time + guard count > scannedCount else { return nil } + scannedCount = count + + // `> 1` checks that we've received a first scan (SOS) and then received + // and also received a second scan (SOS). This way we know that we have + // at least one full scan available. + guard count > 1 && lastSOSIndex > 0 else { return nil } + return data[0 ..< lastSOSIndex] + } + + func decode(_ data: Data, + with callbacks: [SessionDataTask.TaskCallback], + completion: @escaping (KFCrossPlatformImage?) -> Void) { + guard data.kf.contains(jpeg: .SOF2) else { + CallbackQueue.mainCurrentOrAsync.execute { completion(nil) } + return + } + + func processing(_ data: Data) { + let processor = ImageDataProcessor( + data: data, + callbacks: callbacks, + processingQueue: processingQueue + ) + processor.onImageProcessed.delegate(on: self) { (self, result) in + guard let image = try? result.0.get() else { + CallbackQueue.mainCurrentOrAsync.execute { completion(nil) } + return + } + + CallbackQueue.mainCurrentOrAsync.execute { completion(image) } + } + processor.process() + } + + // Blur partial images. + let count = scannedCount + + if option.isBlur, count < 6 { + processingQueue.execute { + // Progressively reduce blur as we load more scans. + let image = KingfisherWrapper.image( + data: data, + options: self.creatingOptions + ) + let radius = max(2, 14 - count * 4) + let temp = image?.kf.blurred(withRadius: CGFloat(radius)) + processing(temp?.kf.data(format: .JPEG) ?? data) + } + + } else { + processing(data) + } + } +} + +private final class ImageProgressiveSerialQueue { + typealias ClosureCallback = ((@escaping () -> Void)) -> Void + + private let queue: DispatchQueue + private var items: [DispatchWorkItem] = [] + private var notify: (() -> Void)? + private var lastTime: TimeInterval? + + init() { + self.queue = DispatchQueue(label: "com.onevcat.Kingfisher.ImageProgressive.SerialQueue") + } + + func add(minimum interval: TimeInterval, closure: @escaping ClosureCallback) { + let completion = { [weak self] in + guard let self = self else { return } + + self.queue.async { [weak self] in + guard let self = self else { return } + guard !self.items.isEmpty else { return } + + self.items.removeFirst() + + if let next = self.items.first { + self.queue.asyncAfter( + deadline: .now() + interval, + execute: next + ) + + } else { + self.lastTime = Date().timeIntervalSince1970 + self.notify?() + self.notify = nil + } + } + } + + queue.async { [weak self] in + guard let self = self else { return } + + let item = DispatchWorkItem { + closure(completion) + } + if self.items.isEmpty { + let difference = Date().timeIntervalSince1970 - (self.lastTime ?? 0) + let delay = difference < interval ? interval - difference : 0 + self.queue.asyncAfter(deadline: .now() + delay, execute: item) + } + self.items.append(item) + } + } + + func clean() { + queue.async { [weak self] in + guard let self = self else { return } + self.items.forEach { $0.cancel() } + self.items.removeAll() + } + } +} diff --git a/Pods/Kingfisher/Sources/Image/ImageTransition.swift b/Pods/Kingfisher/Sources/Image/ImageTransition.swift new file mode 100644 index 0000000..3080995 --- /dev/null +++ b/Pods/Kingfisher/Sources/Image/ImageTransition.swift @@ -0,0 +1,118 @@ +// +// ImageTransition.swift +// Kingfisher +// +// Created by Wei Wang on 15/9/18. +// +// Copyright (c) 2019 Wei Wang +// +// Permission is hereby granted, free of charge, to any person obtaining a copy +// of this software and associated documentation files (the "Software"), to deal +// in the Software without restriction, including without limitation the rights +// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +// copies of the Software, and to permit persons to whom the Software is +// furnished to do so, subject to the following conditions: +// +// The above copyright notice and this permission notice shall be included in +// all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN +// THE SOFTWARE. + +import Foundation +#if os(iOS) || os(tvOS) || os(visionOS) +import UIKit + +/// Transition effect which will be used when an image downloaded and set by `UIImageView` +/// extension API in Kingfisher. You can assign an enum value with transition duration as +/// an item in `KingfisherOptionsInfo` to enable the animation transition. +/// +/// Apple's UIViewAnimationOptions is used under the hood. +/// For custom transition, you should specified your own transition options, animations and +/// completion handler as well. +/// +/// - none: No animation transition. +/// - fade: Fade in the loaded image in a given duration. +/// - flipFromLeft: Flip from left transition. +/// - flipFromRight: Flip from right transition. +/// - flipFromTop: Flip from top transition. +/// - flipFromBottom: Flip from bottom transition. +/// - custom: Custom transition. +public enum ImageTransition { + /// No animation transition. + case none + /// Fade in the loaded image in a given duration. + case fade(TimeInterval) + /// Flip from left transition. + case flipFromLeft(TimeInterval) + /// Flip from right transition. + case flipFromRight(TimeInterval) + /// Flip from top transition. + case flipFromTop(TimeInterval) + /// Flip from bottom transition. + case flipFromBottom(TimeInterval) + /// Custom transition defined by a general animation block. + /// - duration: The time duration of this custom transition. + /// - options: `UIView.AnimationOptions` should be used in the transition. + /// - animations: The animation block will be applied when setting image. + /// - completion: A block called when the transition animation finishes. + case custom(duration: TimeInterval, + options: UIView.AnimationOptions, + animations: ((UIImageView, UIImage) -> Void)?, + completion: ((Bool) -> Void)?) + + var duration: TimeInterval { + switch self { + case .none: return 0 + case .fade(let duration): return duration + + case .flipFromLeft(let duration): return duration + case .flipFromRight(let duration): return duration + case .flipFromTop(let duration): return duration + case .flipFromBottom(let duration): return duration + + case .custom(let duration, _, _, _): return duration + } + } + + var animationOptions: UIView.AnimationOptions { + switch self { + case .none: return [] + case .fade: return .transitionCrossDissolve + + case .flipFromLeft: return .transitionFlipFromLeft + case .flipFromRight: return .transitionFlipFromRight + case .flipFromTop: return .transitionFlipFromTop + case .flipFromBottom: return .transitionFlipFromBottom + + case .custom(_, let options, _, _): return options + } + } + + var animations: ((UIImageView, UIImage) -> Void)? { + switch self { + case .custom(_, _, let animations, _): return animations + default: return { $0.image = $1 } + } + } + + var completion: ((Bool) -> Void)? { + switch self { + case .custom(_, _, _, let completion): return completion + default: return nil + } + } +} +#else +// Just a placeholder for compiling on macOS. +public enum ImageTransition { + case none + /// This is a placeholder on macOS now. It is for SwiftUI (KFImage) to identify the fade option only. + case fade(TimeInterval) +} +#endif diff --git a/Pods/Kingfisher/Sources/Image/Placeholder.swift b/Pods/Kingfisher/Sources/Image/Placeholder.swift new file mode 100644 index 0000000..94d9e3a --- /dev/null +++ b/Pods/Kingfisher/Sources/Image/Placeholder.swift @@ -0,0 +1,82 @@ +// +// Placeholder.swift +// Kingfisher +// +// Created by Tieme van Veen on 28/08/2017. +// +// Copyright (c) 2019 Wei Wang +// +// Permission is hereby granted, free of charge, to any person obtaining a copy +// of this software and associated documentation files (the "Software"), to deal +// in the Software without restriction, including without limitation the rights +// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +// copies of the Software, and to permit persons to whom the Software is +// furnished to do so, subject to the following conditions: +// +// The above copyright notice and this permission notice shall be included in +// all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN +// THE SOFTWARE. + +#if !os(watchOS) + +#if canImport(AppKit) && !targetEnvironment(macCatalyst) +import AppKit +#endif + +#if canImport(UIKit) +import UIKit +#endif + +/// Represents a placeholder type which could be set while loading as well as +/// loading finished without getting an image. +public protocol Placeholder { + + /// How the placeholder should be added to a given image view. + func add(to imageView: KFCrossPlatformImageView) + + /// How the placeholder should be removed from a given image view. + func remove(from imageView: KFCrossPlatformImageView) +} + +/// Default implementation of an image placeholder. The image will be set or +/// reset directly for `image` property of the image view. +extension KFCrossPlatformImage: Placeholder { + /// How the placeholder should be added to a given image view. + public func add(to imageView: KFCrossPlatformImageView) { imageView.image = self } + + /// How the placeholder should be removed from a given image view. + public func remove(from imageView: KFCrossPlatformImageView) { imageView.image = nil } +} + +/// Default implementation of an arbitrary view as placeholder. The view will be +/// added as a subview when adding and be removed from its super view when removing. +/// +/// To use your customize View type as placeholder, simply let it conforming to +/// `Placeholder` by `extension MyView: Placeholder {}`. +extension Placeholder where Self: KFCrossPlatformView { + + /// How the placeholder should be added to a given image view. + public func add(to imageView: KFCrossPlatformImageView) { + imageView.addSubview(self) + translatesAutoresizingMaskIntoConstraints = false + + centerXAnchor.constraint(equalTo: imageView.centerXAnchor).isActive = true + centerYAnchor.constraint(equalTo: imageView.centerYAnchor).isActive = true + heightAnchor.constraint(equalTo: imageView.heightAnchor).isActive = true + widthAnchor.constraint(equalTo: imageView.widthAnchor).isActive = true + } + + /// How the placeholder should be removed from a given image view. + public func remove(from imageView: KFCrossPlatformImageView) { + removeFromSuperview() + } +} + +#endif diff --git a/Pods/Kingfisher/Sources/Networking/AuthenticationChallengeResponsable.swift b/Pods/Kingfisher/Sources/Networking/AuthenticationChallengeResponsable.swift new file mode 100644 index 0000000..d3b3ea1 --- /dev/null +++ b/Pods/Kingfisher/Sources/Networking/AuthenticationChallengeResponsable.swift @@ -0,0 +1,94 @@ +// +// AuthenticationChallengeResponsable.swift +// Kingfisher +// +// Created by Wei Wang on 2018/10/11. +// +// Copyright (c) 2019 Wei Wang +// +// Permission is hereby granted, free of charge, to any person obtaining a copy +// of this software and associated documentation files (the "Software"), to deal +// in the Software without restriction, including without limitation the rights +// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +// copies of the Software, and to permit persons to whom the Software is +// furnished to do so, subject to the following conditions: +// +// The above copyright notice and this permission notice shall be included in +// all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN +// THE SOFTWARE. + +import Foundation + +@available(*, deprecated, message: "Typo. Use `AuthenticationChallengeResponsible` instead", renamed: "AuthenticationChallengeResponsible") +public typealias AuthenticationChallengeResponsable = AuthenticationChallengeResponsible + +/// Protocol indicates that an authentication challenge could be handled. +public protocol AuthenticationChallengeResponsible: AnyObject { + + /// Called when a session level authentication challenge is received. + /// This method provide a chance to handle and response to the authentication + /// challenge before downloading could start. + /// + /// - Parameters: + /// - downloader: The downloader which receives this challenge. + /// - challenge: An object that contains the request for authentication. + /// - completionHandler: A handler that your delegate method must call. + /// + /// - Note: This method is a forward from `URLSessionDelegate.urlSession(:didReceiveChallenge:completionHandler:)`. + /// Please refer to the document of it in `URLSessionDelegate`. + func downloader( + _ downloader: ImageDownloader, + didReceive challenge: URLAuthenticationChallenge, + completionHandler: @escaping (URLSession.AuthChallengeDisposition, URLCredential?) -> Void) + + /// Called when a task level authentication challenge is received. + /// This method provide a chance to handle and response to the authentication + /// challenge before downloading could start. + /// + /// - Parameters: + /// - downloader: The downloader which receives this challenge. + /// - task: The task whose request requires authentication. + /// - challenge: An object that contains the request for authentication. + /// - completionHandler: A handler that your delegate method must call. + func downloader( + _ downloader: ImageDownloader, + task: URLSessionTask, + didReceive challenge: URLAuthenticationChallenge, + completionHandler: @escaping (URLSession.AuthChallengeDisposition, URLCredential?) -> Void) +} + +extension AuthenticationChallengeResponsible { + + public func downloader( + _ downloader: ImageDownloader, + didReceive challenge: URLAuthenticationChallenge, + completionHandler: @escaping (URLSession.AuthChallengeDisposition, URLCredential?) -> Void) + { + if challenge.protectionSpace.authenticationMethod == NSURLAuthenticationMethodServerTrust { + if let trustedHosts = downloader.trustedHosts, trustedHosts.contains(challenge.protectionSpace.host) { + let credential = URLCredential(trust: challenge.protectionSpace.serverTrust!) + completionHandler(.useCredential, credential) + return + } + } + + completionHandler(.performDefaultHandling, nil) + } + + public func downloader( + _ downloader: ImageDownloader, + task: URLSessionTask, + didReceive challenge: URLAuthenticationChallenge, + completionHandler: @escaping (URLSession.AuthChallengeDisposition, URLCredential?) -> Void) + { + completionHandler(.performDefaultHandling, nil) + } + +} diff --git a/Pods/Kingfisher/Sources/Networking/ImageDataProcessor.swift b/Pods/Kingfisher/Sources/Networking/ImageDataProcessor.swift new file mode 100644 index 0000000..b368972 --- /dev/null +++ b/Pods/Kingfisher/Sources/Networking/ImageDataProcessor.swift @@ -0,0 +1,74 @@ +// +// ImageDataProcessor.swift +// Kingfisher +// +// Created by Wei Wang on 2018/10/11. +// +// Copyright (c) 2019 Wei Wang +// +// Permission is hereby granted, free of charge, to any person obtaining a copy +// of this software and associated documentation files (the "Software"), to deal +// in the Software without restriction, including without limitation the rights +// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +// copies of the Software, and to permit persons to whom the Software is +// furnished to do so, subject to the following conditions: +// +// The above copyright notice and this permission notice shall be included in +// all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN +// THE SOFTWARE. + +import Foundation + +private let sharedProcessingQueue: CallbackQueue = + .dispatch(DispatchQueue(label: "com.onevcat.Kingfisher.ImageDownloader.Process")) + +// Handles image processing work on an own process queue. +class ImageDataProcessor { + let data: Data + let callbacks: [SessionDataTask.TaskCallback] + let queue: CallbackQueue + + // Note: We have an optimization choice there, to reduce queue dispatch by checking callback + // queue settings in each option... + let onImageProcessed = Delegate<(Result, SessionDataTask.TaskCallback), Void>() + + init(data: Data, callbacks: [SessionDataTask.TaskCallback], processingQueue: CallbackQueue?) { + self.data = data + self.callbacks = callbacks + self.queue = processingQueue ?? sharedProcessingQueue + } + + func process() { + queue.execute(doProcess) + } + + private func doProcess() { + var processedImages = [String: KFCrossPlatformImage]() + for callback in callbacks { + let processor = callback.options.processor + var image = processedImages[processor.identifier] + if image == nil { + image = processor.process(item: .data(data), options: callback.options) + processedImages[processor.identifier] = image + } + + let result: Result + if let image = image { + let finalImage = callback.options.backgroundDecode ? image.kf.decoded : image + result = .success(finalImage) + } else { + let error = KingfisherError.processorError( + reason: .processingFailed(processor: processor, item: .data(data))) + result = .failure(error) + } + onImageProcessed.call((result, callback)) + } + } +} diff --git a/Pods/Kingfisher/Sources/Networking/ImageDownloader.swift b/Pods/Kingfisher/Sources/Networking/ImageDownloader.swift new file mode 100644 index 0000000..7078d88 --- /dev/null +++ b/Pods/Kingfisher/Sources/Networking/ImageDownloader.swift @@ -0,0 +1,502 @@ +// +// ImageDownloader.swift +// Kingfisher +// +// Created by Wei Wang on 15/4/6. +// +// Copyright (c) 2019 Wei Wang +// +// Permission is hereby granted, free of charge, to any person obtaining a copy +// of this software and associated documentation files (the "Software"), to deal +// in the Software without restriction, including without limitation the rights +// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +// copies of the Software, and to permit persons to whom the Software is +// furnished to do so, subject to the following conditions: +// +// The above copyright notice and this permission notice shall be included in +// all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN +// THE SOFTWARE. + +#if os(macOS) +import AppKit +#else +import UIKit +#endif + +typealias DownloadResult = Result + +/// Represents a success result of an image downloading progress. +public struct ImageLoadingResult { + + /// The downloaded image. + public let image: KFCrossPlatformImage + + /// Original URL of the image request. + public let url: URL? + + /// The raw data received from downloader. + public let originalData: Data + + /// Creates an `ImageDownloadResult` + /// + /// - parameter image: Image of the download result + /// - parameter url: URL from where the image was downloaded from + /// - parameter originalData: The image's binary data + public init(image: KFCrossPlatformImage, url: URL? = nil, originalData: Data) { + self.image = image + self.url = url + self.originalData = originalData + } +} + +/// Represents a task of an image downloading process. +public struct DownloadTask { + + /// The `SessionDataTask` object bounded to this download task. Multiple `DownloadTask`s could refer + /// to a same `sessionTask`. This is an optimization in Kingfisher to prevent multiple downloading task + /// for the same URL resource at the same time. + /// + /// When you `cancel` a `DownloadTask`, this `SessionDataTask` and its cancel token will be pass through. + /// You can use them to identify the cancelled task. + public let sessionTask: SessionDataTask + + /// The cancel token which is used to cancel the task. This is only for identify the task when it is cancelled. + /// To cancel a `DownloadTask`, use `cancel` instead. + public let cancelToken: SessionDataTask.CancelToken + + /// Cancel this task if it is running. It will do nothing if this task is not running. + /// + /// - Note: + /// In Kingfisher, there is an optimization to prevent starting another download task if the target URL is being + /// downloading. However, even when internally no new session task created, a `DownloadTask` will be still created + /// and returned when you call related methods, but it will share the session downloading task with a previous task. + /// In this case, if multiple `DownloadTask`s share a single session download task, cancelling a `DownloadTask` + /// does not affect other `DownloadTask`s. + /// + /// If you need to cancel all `DownloadTask`s of a url, use `ImageDownloader.cancel(url:)`. If you need to cancel + /// all downloading tasks of an `ImageDownloader`, use `ImageDownloader.cancelAll()`. + public func cancel() { + sessionTask.cancel(token: cancelToken) + } +} + +extension DownloadTask { + enum WrappedTask { + case download(DownloadTask) + case dataProviding + + func cancel() { + switch self { + case .download(let task): task.cancel() + case .dataProviding: break + } + } + + var value: DownloadTask? { + switch self { + case .download(let task): return task + case .dataProviding: return nil + } + } + } +} + +/// Represents a downloading manager for requesting the image with a URL from server. +open class ImageDownloader { + + // MARK: Singleton + /// The default downloader. + public static let `default` = ImageDownloader(name: "default") + + // MARK: Public Properties + /// The duration before the downloading is timeout. Default is 15 seconds. + open var downloadTimeout: TimeInterval = 15.0 + + /// A set of trusted hosts when receiving server trust challenges. A challenge with host name contained in this + /// set will be ignored. You can use this set to specify the self-signed site. It only will be used if you don't + /// specify the `authenticationChallengeResponder`. + /// + /// If `authenticationChallengeResponder` is set, this property will be ignored and the implementation of + /// `authenticationChallengeResponder` will be used instead. + open var trustedHosts: Set? + + /// Use this to set supply a configuration for the downloader. By default, + /// NSURLSessionConfiguration.ephemeralSessionConfiguration() will be used. + /// + /// You could change the configuration before a downloading task starts. + /// A configuration without persistent storage for caches is requested for downloader working correctly. + open var sessionConfiguration = URLSessionConfiguration.ephemeral { + didSet { + session.invalidateAndCancel() + session = URLSession(configuration: sessionConfiguration, delegate: sessionDelegate, delegateQueue: nil) + } + } + open var sessionDelegate: SessionDelegate { + didSet { + session.invalidateAndCancel() + session = URLSession(configuration: sessionConfiguration, delegate: sessionDelegate, delegateQueue: nil) + setupSessionHandler() + } + } + + /// Whether the download requests should use pipeline or not. Default is false. + open var requestsUsePipelining = false + + /// Delegate of this `ImageDownloader` object. See `ImageDownloaderDelegate` protocol for more. + open weak var delegate: ImageDownloaderDelegate? + + /// A responder for authentication challenge. + /// Downloader will forward the received authentication challenge for the downloading session to this responder. + open weak var authenticationChallengeResponder: AuthenticationChallengeResponsible? + + private let name: String + private var session: URLSession + + // MARK: Initializers + + /// Creates a downloader with name. + /// + /// - Parameter name: The name for the downloader. It should not be empty. + public init(name: String) { + if name.isEmpty { + fatalError("[Kingfisher] You should specify a name for the downloader. " + + "A downloader with empty name is not permitted.") + } + + self.name = name + + sessionDelegate = SessionDelegate() + session = URLSession( + configuration: sessionConfiguration, + delegate: sessionDelegate, + delegateQueue: nil) + + authenticationChallengeResponder = self + setupSessionHandler() + } + + deinit { session.invalidateAndCancel() } + + private func setupSessionHandler() { + sessionDelegate.onReceiveSessionChallenge.delegate(on: self) { (self, invoke) in + self.authenticationChallengeResponder?.downloader(self, didReceive: invoke.1, completionHandler: invoke.2) + } + sessionDelegate.onReceiveSessionTaskChallenge.delegate(on: self) { (self, invoke) in + self.authenticationChallengeResponder?.downloader( + self, task: invoke.1, didReceive: invoke.2, completionHandler: invoke.3) + } + sessionDelegate.onValidStatusCode.delegate(on: self) { (self, code) in + return (self.delegate ?? self).isValidStatusCode(code, for: self) + } + sessionDelegate.onResponseReceived.delegate(on: self) { (self, invoke) in + (self.delegate ?? self).imageDownloader(self, didReceive: invoke.0, completionHandler: invoke.1) + } + sessionDelegate.onDownloadingFinished.delegate(on: self) { (self, value) in + let (url, result) = value + do { + let value = try result.get() + self.delegate?.imageDownloader(self, didFinishDownloadingImageForURL: url, with: value, error: nil) + } catch { + self.delegate?.imageDownloader(self, didFinishDownloadingImageForURL: url, with: nil, error: error) + } + } + sessionDelegate.onDidDownloadData.delegate(on: self) { (self, task) in + return (self.delegate ?? self).imageDownloader(self, didDownload: task.mutableData, with: task) + } + } + + // Wraps `completionHandler` to `onCompleted` respectively. + private func createCompletionCallBack(_ completionHandler: ((DownloadResult) -> Void)?) -> Delegate? { + return completionHandler.map { block -> Delegate in + + let delegate = Delegate, Void>() + delegate.delegate(on: self) { (self, callback) in + block(callback) + } + return delegate + } + } + + private func createTaskCallback( + _ completionHandler: ((DownloadResult) -> Void)?, + options: KingfisherParsedOptionsInfo + ) -> SessionDataTask.TaskCallback + { + return SessionDataTask.TaskCallback( + onCompleted: createCompletionCallBack(completionHandler), + options: options + ) + } + + private func createDownloadContext( + with url: URL, + options: KingfisherParsedOptionsInfo, + done: @escaping ((Result) -> Void) + ) + { + func checkRequestAndDone(r: URLRequest) { + + // There is a possibility that request modifier changed the url to `nil` or empty. + // In this case, throw an error. + guard let url = r.url, !url.absoluteString.isEmpty else { + done(.failure(KingfisherError.requestError(reason: .invalidURL(request: r)))) + return + } + + done(.success(DownloadingContext(url: url, request: r, options: options))) + } + + // Creates default request. + var request = URLRequest(url: url, cachePolicy: .reloadIgnoringLocalCacheData, timeoutInterval: downloadTimeout) + request.httpShouldUsePipelining = requestsUsePipelining + if #available(macOS 10.15, iOS 13.0, watchOS 6.0, tvOS 13.0, *) , options.lowDataModeSource != nil { + request.allowsConstrainedNetworkAccess = false + } + + if let requestModifier = options.requestModifier { + // Modifies request before sending. + requestModifier.modified(for: request) { result in + guard let finalRequest = result else { + done(.failure(KingfisherError.requestError(reason: .emptyRequest))) + return + } + checkRequestAndDone(r: finalRequest) + } + } else { + checkRequestAndDone(r: request) + } + } + + private func addDownloadTask( + context: DownloadingContext, + callback: SessionDataTask.TaskCallback + ) -> DownloadTask + { + // Ready to start download. Add it to session task manager (`sessionHandler`) + let downloadTask: DownloadTask + if let existingTask = sessionDelegate.task(for: context.url) { + downloadTask = sessionDelegate.append(existingTask, callback: callback) + } else { + let sessionDataTask = session.dataTask(with: context.request) + sessionDataTask.priority = context.options.downloadPriority + downloadTask = sessionDelegate.add(sessionDataTask, url: context.url, callback: callback) + } + return downloadTask + } + + + private func reportWillDownloadImage(url: URL, request: URLRequest) { + delegate?.imageDownloader(self, willDownloadImageForURL: url, with: request) + } + + private func reportDidDownloadImageData(result: Result<(Data, URLResponse?), KingfisherError>, url: URL) { + var response: URLResponse? + var err: Error? + do { + response = try result.get().1 + } catch { + err = error + } + self.delegate?.imageDownloader( + self, + didFinishDownloadingImageForURL: url, + with: response, + error: err + ) + } + + private func reportDidProcessImage( + result: Result, url: URL, response: URLResponse? + ) + { + if let image = try? result.get() { + self.delegate?.imageDownloader(self, didDownload: image, for: url, with: response) + } + + } + + private func startDownloadTask( + context: DownloadingContext, + callback: SessionDataTask.TaskCallback + ) -> DownloadTask + { + + let downloadTask = addDownloadTask(context: context, callback: callback) + + let sessionTask = downloadTask.sessionTask + guard !sessionTask.started else { + return downloadTask + } + + sessionTask.onTaskDone.delegate(on: self) { (self, done) in + // Underlying downloading finishes. + // result: Result<(Data, URLResponse?)>, callbacks: [TaskCallback] + let (result, callbacks) = done + + // Before processing the downloaded data. + self.reportDidDownloadImageData(result: result, url: context.url) + + switch result { + // Download finished. Now process the data to an image. + case .success(let (data, response)): + let processor = ImageDataProcessor( + data: data, callbacks: callbacks, processingQueue: context.options.processingQueue + ) + processor.onImageProcessed.delegate(on: self) { (self, done) in + // `onImageProcessed` will be called for `callbacks.count` times, with each + // `SessionDataTask.TaskCallback` as the input parameter. + // result: Result, callback: SessionDataTask.TaskCallback + let (result, callback) = done + + self.reportDidProcessImage(result: result, url: context.url, response: response) + + let imageResult = result.map { ImageLoadingResult(image: $0, url: context.url, originalData: data) } + let queue = callback.options.callbackQueue + queue.execute { callback.onCompleted?.call(imageResult) } + } + processor.process() + + case .failure(let error): + callbacks.forEach { callback in + let queue = callback.options.callbackQueue + queue.execute { callback.onCompleted?.call(.failure(error)) } + } + } + } + + reportWillDownloadImage(url: context.url, request: context.request) + sessionTask.resume() + return downloadTask + } + + // MARK: Downloading Task + /// Downloads an image with a URL and option. Invoked internally by Kingfisher. Subclasses must invoke super. + /// + /// - Parameters: + /// - url: Target URL. + /// - options: The options could control download behavior. See `KingfisherOptionsInfo`. + /// - completionHandler: Called when the download progress finishes. This block will be called in the queue + /// defined in `.callbackQueue` in `options` parameter. + /// - Returns: A downloading task. You could call `cancel` on it to stop the download task. + @discardableResult + open func downloadImage( + with url: URL, + options: KingfisherParsedOptionsInfo, + completionHandler: ((Result) -> Void)? = nil) -> DownloadTask? + { + var downloadTask: DownloadTask? + createDownloadContext(with: url, options: options) { result in + switch result { + case .success(let context): + // `downloadTask` will be set if the downloading started immediately. This is the case when no request + // modifier or a sync modifier (`ImageDownloadRequestModifier`) is used. Otherwise, when an + // `AsyncImageDownloadRequestModifier` is used the returned `downloadTask` of this method will be `nil` + // and the actual "delayed" task is given in `AsyncImageDownloadRequestModifier.onDownloadTaskStarted` + // callback. + downloadTask = self.startDownloadTask( + context: context, + callback: self.createTaskCallback(completionHandler, options: options) + ) + if let modifier = options.requestModifier { + modifier.onDownloadTaskStarted?(downloadTask) + } + case .failure(let error): + options.callbackQueue.execute { + completionHandler?(.failure(error)) + } + } + } + + return downloadTask + } + + /// Downloads an image with a URL and option. + /// + /// - Parameters: + /// - url: Target URL. + /// - options: The options could control download behavior. See `KingfisherOptionsInfo`. + /// - progressBlock: Called when the download progress updated. This block will be always be called in main queue. + /// - completionHandler: Called when the download progress finishes. This block will be called in the queue + /// defined in `.callbackQueue` in `options` parameter. + /// - Returns: A downloading task. You could call `cancel` on it to stop the download task. + @discardableResult + open func downloadImage( + with url: URL, + options: KingfisherOptionsInfo? = nil, + progressBlock: DownloadProgressBlock? = nil, + completionHandler: ((Result) -> Void)? = nil) -> DownloadTask? + { + var info = KingfisherParsedOptionsInfo(options) + if let block = progressBlock { + info.onDataReceived = (info.onDataReceived ?? []) + [ImageLoadingProgressSideEffect(block)] + } + return downloadImage( + with: url, + options: info, + completionHandler: completionHandler) + } + + /// Downloads an image with a URL and option. + /// + /// - Parameters: + /// - url: Target URL. + /// - options: The options could control download behavior. See `KingfisherOptionsInfo`. + /// - completionHandler: Called when the download progress finishes. This block will be called in the queue + /// defined in `.callbackQueue` in `options` parameter. + /// - Returns: A downloading task. You could call `cancel` on it to stop the download task. + @discardableResult + open func downloadImage( + with url: URL, + options: KingfisherOptionsInfo? = nil, + completionHandler: ((Result) -> Void)? = nil) -> DownloadTask? + { + downloadImage( + with: url, + options: KingfisherParsedOptionsInfo(options), + completionHandler: completionHandler + ) + } +} + +// MARK: Cancelling Task +extension ImageDownloader { + + /// Cancel all downloading tasks for this `ImageDownloader`. It will trigger the completion handlers + /// for all not-yet-finished downloading tasks. + /// + /// If you need to only cancel a certain task, call `cancel()` on the `DownloadTask` + /// returned by the downloading methods. If you need to cancel all `DownloadTask`s of a certain url, + /// use `ImageDownloader.cancel(url:)`. + public func cancelAll() { + sessionDelegate.cancelAll() + } + + /// Cancel all downloading tasks for a given URL. It will trigger the completion handlers for + /// all not-yet-finished downloading tasks for the URL. + /// + /// - Parameter url: The URL which you want to cancel downloading. + public func cancel(url: URL) { + sessionDelegate.cancel(url: url) + } +} + +// Use the default implementation from extension of `AuthenticationChallengeResponsible`. +extension ImageDownloader: AuthenticationChallengeResponsible {} + +// Use the default implementation from extension of `ImageDownloaderDelegate`. +extension ImageDownloader: ImageDownloaderDelegate {} + +extension ImageDownloader { + struct DownloadingContext { + let url: URL + let request: URLRequest + let options: KingfisherParsedOptionsInfo + } +} diff --git a/Pods/Kingfisher/Sources/Networking/ImageDownloaderDelegate.swift b/Pods/Kingfisher/Sources/Networking/ImageDownloaderDelegate.swift new file mode 100644 index 0000000..7343a24 --- /dev/null +++ b/Pods/Kingfisher/Sources/Networking/ImageDownloaderDelegate.swift @@ -0,0 +1,189 @@ +// +// ImageDownloaderDelegate.swift +// Kingfisher +// +// Created by Wei Wang on 2018/10/11. +// +// Copyright (c) 2019 Wei Wang +// +// Permission is hereby granted, free of charge, to any person obtaining a copy +// of this software and associated documentation files (the "Software"), to deal +// in the Software without restriction, including without limitation the rights +// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +// copies of the Software, and to permit persons to whom the Software is +// furnished to do so, subject to the following conditions: +// +// The above copyright notice and this permission notice shall be included in +// all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN +// THE SOFTWARE. + +import Foundation +#if os(macOS) +import AppKit +#else +import UIKit +#endif + +/// Protocol of `ImageDownloader`. This protocol provides a set of methods which are related to image downloader +/// working stages and rules. +public protocol ImageDownloaderDelegate: AnyObject { + + /// Called when the `ImageDownloader` object will start downloading an image from a specified URL. + /// + /// - Parameters: + /// - downloader: The `ImageDownloader` object which is used for the downloading operation. + /// - url: URL of the starting request. + /// - request: The request object for the download process. + /// + func imageDownloader(_ downloader: ImageDownloader, willDownloadImageForURL url: URL, with request: URLRequest?) + + /// Called when the `ImageDownloader` completes a downloading request with success or failure. + /// + /// - Parameters: + /// - downloader: The `ImageDownloader` object which is used for the downloading operation. + /// - url: URL of the original request URL. + /// - response: The response object of the downloading process. + /// - error: The error in case of failure. + /// + func imageDownloader( + _ downloader: ImageDownloader, + didFinishDownloadingImageForURL url: URL, + with response: URLResponse?, + error: Error?) + + /// Called when the `ImageDownloader` object successfully downloaded image data from specified URL. This is + /// your last chance to verify or modify the downloaded data before Kingfisher tries to perform addition + /// processing on the image data. + /// + /// - Parameters: + /// - downloader: The `ImageDownloader` object which is used for the downloading operation. + /// - data: The original downloaded data. + /// - dataTask: The data task contains request and response information of the download. + /// - Note: + /// This can be used to pre-process raw image data before creation of `Image` instance (i.e. + /// decrypting or verification). If `nil` returned, the processing is interrupted and a `KingfisherError` with + /// `ResponseErrorReason.dataModifyingFailed` will be raised. You could use this fact to stop the image + /// processing flow if you find the data is corrupted or malformed. + /// + /// If this method is implemented, `imageDownloader(_:didDownload:for:)` will not be called anymore. + func imageDownloader(_ downloader: ImageDownloader, didDownload data: Data, with dataTask: SessionDataTask) -> Data? + + /// Called when the `ImageDownloader` object successfully downloaded image data from specified URL. This is + /// your last chance to verify or modify the downloaded data before Kingfisher tries to perform addition + /// processing on the image data. + /// + /// - Parameters: + /// - downloader: The `ImageDownloader` object which is used for the downloading operation. + /// - data: The original downloaded data. + /// - url: The URL of the original request URL. + /// - Returns: The data from which Kingfisher should use to create an image. You need to provide valid data + /// which content is one of the supported image file format. Kingfisher will perform process on this + /// data and try to convert it to an image object. + /// - Note: + /// This can be used to pre-process raw image data before creation of `Image` instance (i.e. + /// decrypting or verification). If `nil` returned, the processing is interrupted and a `KingfisherError` with + /// `ResponseErrorReason.dataModifyingFailed` will be raised. You could use this fact to stop the image + /// processing flow if you find the data is corrupted or malformed. + /// + /// If `imageDownloader(_:didDownload:with:)` is implemented, this method will not be called anymore. + func imageDownloader(_ downloader: ImageDownloader, didDownload data: Data, for url: URL) -> Data? + + /// Called when the `ImageDownloader` object successfully downloads and processes an image from specified URL. + /// + /// - Parameters: + /// - downloader: The `ImageDownloader` object which is used for the downloading operation. + /// - image: The downloaded and processed image. + /// - url: URL of the original request URL. + /// - response: The original response object of the downloading process. + /// + func imageDownloader( + _ downloader: ImageDownloader, + didDownload image: KFCrossPlatformImage, + for url: URL, + with response: URLResponse?) + + /// Checks if a received HTTP status code is valid or not. + /// By default, a status code in range 200..<400 is considered as valid. + /// If an invalid code is received, the downloader will raise an `KingfisherError` with + /// `ResponseErrorReason.invalidHTTPStatusCode` as its reason. + /// + /// - Parameters: + /// - code: The received HTTP status code. + /// - downloader: The `ImageDownloader` object asks for validate status code. + /// - Returns: Returns a value to indicate whether this HTTP status code is valid or not. + /// - Note: If the default 200 to 400 valid code does not suit your need, + /// you can implement this method to change that behavior. + func isValidStatusCode(_ code: Int, for downloader: ImageDownloader) -> Bool + + /// Called when the task has received a valid HTTP response after it passes other checks such as the status code. + /// You can perform additional checks or verification on the response to determine if the download should be allowed. + /// + /// For example, it is useful if you want to verify some header values in the response before actually starting the + /// download. + /// + /// If implemented, it is your responsibility to call the `completionHandler` with a proper response disposition, + /// such as `.allow` to start the actual downloading or `.cancel` to cancel the task. If `.cancel` is used as the + /// disposition, the downloader will raise an `KingfisherError` with + /// `ResponseErrorReason.cancelledByDelegate` as its reason. If not implemented, any response which passes other + /// checked will be allowed and the download starts. + /// + /// - Parameters: + /// - downloader: The `ImageDownloader` object which is used for the downloading operation. + /// - response: The original response object of the downloading process. + /// - completionHandler: A completion handler that receives the disposition for the download task. You must call + /// this handler with either `.allow` or `.cancel`. + func imageDownloader( + _ downloader: ImageDownloader, + didReceive response: URLResponse, + completionHandler: @escaping (URLSession.ResponseDisposition) -> Void) +} + +// Default implementation for `ImageDownloaderDelegate`. +extension ImageDownloaderDelegate { + public func imageDownloader( + _ downloader: ImageDownloader, + willDownloadImageForURL url: URL, + with request: URLRequest?) {} + + public func imageDownloader( + _ downloader: ImageDownloader, + didFinishDownloadingImageForURL url: URL, + with response: URLResponse?, + error: Error?) {} + + public func imageDownloader( + _ downloader: ImageDownloader, + didDownload image: KFCrossPlatformImage, + for url: URL, + with response: URLResponse?) {} + + public func isValidStatusCode(_ code: Int, for downloader: ImageDownloader) -> Bool { + return (200..<400).contains(code) + } + + public func imageDownloader(_ downloader: ImageDownloader, didDownload data: Data, with task: SessionDataTask) -> Data? { + guard let url = task.originalURL else { + return data + } + return imageDownloader(downloader, didDownload: data, for: url) + } + + public func imageDownloader(_ downloader: ImageDownloader, didDownload data: Data, for url: URL) -> Data? { + return data + } + + public func imageDownloader( + _ downloader: ImageDownloader, + didReceive response: URLResponse, + completionHandler: @escaping (URLSession.ResponseDisposition) -> Void) { + completionHandler(.allow) + } + +} diff --git a/Pods/Kingfisher/Sources/Networking/ImageModifier.swift b/Pods/Kingfisher/Sources/Networking/ImageModifier.swift new file mode 100644 index 0000000..955ab76 --- /dev/null +++ b/Pods/Kingfisher/Sources/Networking/ImageModifier.swift @@ -0,0 +1,120 @@ +// +// ImageModifier.swift +// Kingfisher +// +// Created by Ethan Gill on 2017/11/28. +// +// Copyright (c) 2019 Ethan Gill +// +// Permission is hereby granted, free of charge, to any person obtaining a copy +// of this software and associated documentation files (the "Software"), to deal +// in the Software without restriction, including without limitation the rights +// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +// copies of the Software, and to permit persons to whom the Software is +// furnished to do so, subject to the following conditions: +// +// The above copyright notice and this permission notice shall be included in +// all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN +// THE SOFTWARE. + +#if os(macOS) +import AppKit +#else +import UIKit +#endif + +/// An `ImageModifier` can be used to change properties on an image between cache serialization and the actual use of +/// the image. The `modify(_:)` method will be called after the image retrieved from its source and before it returned +/// to the caller. This modified image is expected to be only used for rendering purpose, any changes applied by the +/// `ImageModifier` will not be serialized or cached. +public protocol ImageModifier { + /// Modify an input `Image`. + /// + /// - parameter image: Image which will be modified by `self` + /// + /// - returns: The modified image. + /// + /// - Note: The return value will be unmodified if modifying is not possible on + /// the current platform. + /// - Note: Most modifiers support UIImage or NSImage, but not CGImage. + func modify(_ image: KFCrossPlatformImage) -> KFCrossPlatformImage +} + +/// A wrapper for creating an `ImageModifier` easier. +/// This type conforms to `ImageModifier` and wraps an image modify block. +/// If the `block` throws an error, the original image will be used. +public struct AnyImageModifier: ImageModifier { + + /// A block which modifies images, or returns the original image + /// if modification cannot be performed with an error. + let block: (KFCrossPlatformImage) throws -> KFCrossPlatformImage + + /// Creates an `AnyImageModifier` with a given `modify` block. + public init(modify: @escaping (KFCrossPlatformImage) throws -> KFCrossPlatformImage) { + block = modify + } + + /// Modify an input `Image`. See `ImageModifier` protocol for more. + public func modify(_ image: KFCrossPlatformImage) -> KFCrossPlatformImage { + return (try? block(image)) ?? image + } +} + +#if os(iOS) || os(tvOS) || os(watchOS) || os(visionOS) +import UIKit + +/// Modifier for setting the rendering mode of images. +public struct RenderingModeImageModifier: ImageModifier { + + /// The rendering mode to apply to the image. + public let renderingMode: UIImage.RenderingMode + + /// Creates a `RenderingModeImageModifier`. + /// + /// - Parameter renderingMode: The rendering mode to apply to the image. Default is `.automatic`. + public init(renderingMode: UIImage.RenderingMode = .automatic) { + self.renderingMode = renderingMode + } + + /// Modify an input `Image`. See `ImageModifier` protocol for more. + public func modify(_ image: KFCrossPlatformImage) -> KFCrossPlatformImage { + return image.withRenderingMode(renderingMode) + } +} + +/// Modifier for setting the `flipsForRightToLeftLayoutDirection` property of images. +public struct FlipsForRightToLeftLayoutDirectionImageModifier: ImageModifier { + + /// Creates a `FlipsForRightToLeftLayoutDirectionImageModifier`. + public init() {} + + /// Modify an input `Image`. See `ImageModifier` protocol for more. + public func modify(_ image: KFCrossPlatformImage) -> KFCrossPlatformImage { + return image.imageFlippedForRightToLeftLayoutDirection() + } +} + +/// Modifier for setting the `alignmentRectInsets` property of images. +public struct AlignmentRectInsetsImageModifier: ImageModifier { + + /// The alignment insets to apply to the image + public let alignmentInsets: UIEdgeInsets + + /// Creates an `AlignmentRectInsetsImageModifier`. + public init(alignmentInsets: UIEdgeInsets) { + self.alignmentInsets = alignmentInsets + } + + /// Modify an input `Image`. See `ImageModifier` protocol for more. + public func modify(_ image: KFCrossPlatformImage) -> KFCrossPlatformImage { + return image.withAlignmentRectInsets(alignmentInsets) + } +} +#endif diff --git a/Pods/Kingfisher/Sources/Networking/ImagePrefetcher.swift b/Pods/Kingfisher/Sources/Networking/ImagePrefetcher.swift new file mode 100644 index 0000000..e8011ed --- /dev/null +++ b/Pods/Kingfisher/Sources/Networking/ImagePrefetcher.swift @@ -0,0 +1,442 @@ +// +// ImagePrefetcher.swift +// Kingfisher +// +// Created by Claire Knight on 24/02/2016 +// +// Copyright (c) 2019 Wei Wang +// +// Permission is hereby granted, free of charge, to any person obtaining a copy +// of this software and associated documentation files (the "Software"), to deal +// in the Software without restriction, including without limitation the rights +// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +// copies of the Software, and to permit persons to whom the Software is +// furnished to do so, subject to the following conditions: +// +// The above copyright notice and this permission notice shall be included in +// all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN +// THE SOFTWARE. + + +#if os(macOS) +import AppKit +#else +import UIKit +#endif + +/// Progress update block of prefetcher when initialized with a list of resources. +/// +/// - `skippedResources`: An array of resources that are already cached before the prefetching starting. +/// - `failedResources`: An array of resources that fail to be downloaded. It could because of being cancelled while +/// downloading, encountered an error when downloading or the download not being started at all. +/// - `completedResources`: An array of resources that are downloaded and cached successfully. +public typealias PrefetcherProgressBlock = + ((_ skippedResources: [Resource], _ failedResources: [Resource], _ completedResources: [Resource]) -> Void) + +/// Progress update block of prefetcher when initialized with a list of resources. +/// +/// - `skippedSources`: An array of sources that are already cached before the prefetching starting. +/// - `failedSources`: An array of sources that fail to be fetched. +/// - `completedResources`: An array of sources that are fetched and cached successfully. +public typealias PrefetcherSourceProgressBlock = + ((_ skippedSources: [Source], _ failedSources: [Source], _ completedSources: [Source]) -> Void) + +/// Completion block of prefetcher when initialized with a list of sources. +/// +/// - `skippedResources`: An array of resources that are already cached before the prefetching starting. +/// - `failedResources`: An array of resources that fail to be downloaded. It could because of being cancelled while +/// downloading, encountered an error when downloading or the download not being started at all. +/// - `completedResources`: An array of resources that are downloaded and cached successfully. +public typealias PrefetcherCompletionHandler = + ((_ skippedResources: [Resource], _ failedResources: [Resource], _ completedResources: [Resource]) -> Void) + +/// Completion block of prefetcher when initialized with a list of sources. +/// +/// - `skippedSources`: An array of sources that are already cached before the prefetching starting. +/// - `failedSources`: An array of sources that fail to be fetched. +/// - `completedSources`: An array of sources that are fetched and cached successfully. +public typealias PrefetcherSourceCompletionHandler = + ((_ skippedSources: [Source], _ failedSources: [Source], _ completedSources: [Source]) -> Void) + +/// `ImagePrefetcher` represents a downloading manager for requesting many images via URLs, then caching them. +/// This is useful when you know a list of image resources and want to download them before showing. It also works with +/// some Cocoa prefetching mechanism like table view or collection view `prefetchDataSource`, to start image downloading +/// and caching before they display on screen. +public class ImagePrefetcher: CustomStringConvertible { + + public var description: String { + return "\(Unmanaged.passUnretained(self).toOpaque())" + } + + /// The maximum concurrent downloads to use when prefetching images. Default is 5. + public var maxConcurrentDownloads = 5 + + private let prefetchSources: [Source] + private let optionsInfo: KingfisherParsedOptionsInfo + + private var progressBlock: PrefetcherProgressBlock? + private var completionHandler: PrefetcherCompletionHandler? + + private var progressSourceBlock: PrefetcherSourceProgressBlock? + private var completionSourceHandler: PrefetcherSourceCompletionHandler? + + private var tasks = [String: DownloadTask.WrappedTask]() + + private var pendingSources: ArraySlice + private var skippedSources = [Source]() + private var completedSources = [Source]() + private var failedSources = [Source]() + + private var stopped = false + + // A manager used for prefetching. We will use the helper methods in manager. + private let manager: KingfisherManager + + private let prefetchQueue = DispatchQueue(label: "com.onevcat.Kingfisher.ImagePrefetcher.prefetchQueue") + private static let requestingQueue = DispatchQueue(label: "com.onevcat.Kingfisher.ImagePrefetcher.requestingQueue") + + private var finished: Bool { + let totalFinished: Int = failedSources.count + skippedSources.count + completedSources.count + return totalFinished == prefetchSources.count && tasks.isEmpty + } + + /// Creates an image prefetcher with an array of URLs. + /// + /// The prefetcher should be initiated with a list of prefetching targets. The URLs list is immutable. + /// After you get a valid `ImagePrefetcher` object, you call `start()` on it to begin the prefetching process. + /// The images which are already cached will be skipped without downloading again. + /// + /// - Parameters: + /// - urls: The URLs which should be prefetched. + /// - options: Options could control some behaviors. See `KingfisherOptionsInfo` for more. + /// - progressBlock: Called every time an resource is downloaded, skipped or cancelled. + /// - completionHandler: Called when the whole prefetching process finished. + /// + /// - Note: + /// By default, the `ImageDownloader.defaultDownloader` and `ImageCache.defaultCache` will be used as + /// the downloader and cache target respectively. You can specify another downloader or cache by using + /// a customized `KingfisherOptionsInfo`. Both the progress and completion block will be invoked in + /// main thread. The `.callbackQueue` value in `optionsInfo` will be ignored in this method. + public convenience init( + urls: [URL], + options: KingfisherOptionsInfo? = nil, + progressBlock: PrefetcherProgressBlock? = nil, + completionHandler: PrefetcherCompletionHandler? = nil) + { + let resources: [Resource] = urls.map { $0 } + self.init( + resources: resources, + options: options, + progressBlock: progressBlock, + completionHandler: completionHandler) + } + + /// Creates an image prefetcher with an array of URLs. + /// + /// The prefetcher should be initiated with a list of prefetching targets. The URLs list is immutable. + /// After you get a valid `ImagePrefetcher` object, you call `start()` on it to begin the prefetching process. + /// The images which are already cached will be skipped without downloading again. + /// + /// - Parameters: + /// - urls: The URLs which should be prefetched. + /// - options: Options could control some behaviors. See `KingfisherOptionsInfo` for more. + /// - completionHandler: Called when the whole prefetching process finished. + /// + /// - Note: + /// By default, the `ImageDownloader.defaultDownloader` and `ImageCache.defaultCache` will be used as + /// the downloader and cache target respectively. You can specify another downloader or cache by using + /// a customized `KingfisherOptionsInfo`. Both the progress and completion block will be invoked in + /// main thread. The `.callbackQueue` value in `optionsInfo` will be ignored in this method. + public convenience init( + urls: [URL], + options: KingfisherOptionsInfo? = nil, + completionHandler: PrefetcherCompletionHandler? = nil) + { + let resources: [Resource] = urls.map { $0 } + self.init( + resources: resources, + options: options, + progressBlock: nil, + completionHandler: completionHandler) + } + + /// Creates an image prefetcher with an array of resources. + /// + /// - Parameters: + /// - resources: The resources which should be prefetched. See `Resource` type for more. + /// - options: Options could control some behaviors. See `KingfisherOptionsInfo` for more. + /// - progressBlock: Called every time an resource is downloaded, skipped or cancelled. + /// - completionHandler: Called when the whole prefetching process finished. + /// + /// - Note: + /// By default, the `ImageDownloader.defaultDownloader` and `ImageCache.defaultCache` will be used as + /// the downloader and cache target respectively. You can specify another downloader or cache by using + /// a customized `KingfisherOptionsInfo`. Both the progress and completion block will be invoked in + /// main thread. The `.callbackQueue` value in `optionsInfo` will be ignored in this method. + public convenience init( + resources: [Resource], + options: KingfisherOptionsInfo? = nil, + progressBlock: PrefetcherProgressBlock? = nil, + completionHandler: PrefetcherCompletionHandler? = nil) + { + self.init(sources: resources.map { $0.convertToSource() }, options: options) + self.progressBlock = progressBlock + self.completionHandler = completionHandler + } + + /// Creates an image prefetcher with an array of resources. + /// + /// - Parameters: + /// - resources: The resources which should be prefetched. See `Resource` type for more. + /// - options: Options could control some behaviors. See `KingfisherOptionsInfo` for more. + /// - completionHandler: Called when the whole prefetching process finished. + /// + /// - Note: + /// By default, the `ImageDownloader.defaultDownloader` and `ImageCache.defaultCache` will be used as + /// the downloader and cache target respectively. You can specify another downloader or cache by using + /// a customized `KingfisherOptionsInfo`. Both the progress and completion block will be invoked in + /// main thread. The `.callbackQueue` value in `optionsInfo` will be ignored in this method. + public convenience init( + resources: [Resource], + options: KingfisherOptionsInfo? = nil, + completionHandler: PrefetcherCompletionHandler? = nil) + { + self.init(sources: resources.map { $0.convertToSource() }, options: options) + self.completionHandler = completionHandler + } + + /// Creates an image prefetcher with an array of sources. + /// + /// - Parameters: + /// - sources: The sources which should be prefetched. See `Source` type for more. + /// - options: Options could control some behaviors. See `KingfisherOptionsInfo` for more. + /// - progressBlock: Called every time an source fetching successes, fails, is skipped. + /// - completionHandler: Called when the whole prefetching process finished. + /// + /// - Note: + /// By default, the `ImageDownloader.defaultDownloader` and `ImageCache.defaultCache` will be used as + /// the downloader and cache target respectively. You can specify another downloader or cache by using + /// a customized `KingfisherOptionsInfo`. Both the progress and completion block will be invoked in + /// main thread. The `.callbackQueue` value in `optionsInfo` will be ignored in this method. + public convenience init(sources: [Source], + options: KingfisherOptionsInfo? = nil, + progressBlock: PrefetcherSourceProgressBlock? = nil, + completionHandler: PrefetcherSourceCompletionHandler? = nil) + { + self.init(sources: sources, options: options) + self.progressSourceBlock = progressBlock + self.completionSourceHandler = completionHandler + } + + /// Creates an image prefetcher with an array of sources. + /// + /// - Parameters: + /// - sources: The sources which should be prefetched. See `Source` type for more. + /// - options: Options could control some behaviors. See `KingfisherOptionsInfo` for more. + /// - completionHandler: Called when the whole prefetching process finished. + /// + /// - Note: + /// By default, the `ImageDownloader.defaultDownloader` and `ImageCache.defaultCache` will be used as + /// the downloader and cache target respectively. You can specify another downloader or cache by using + /// a customized `KingfisherOptionsInfo`. Both the progress and completion block will be invoked in + /// main thread. The `.callbackQueue` value in `optionsInfo` will be ignored in this method. + public convenience init(sources: [Source], + options: KingfisherOptionsInfo? = nil, + completionHandler: PrefetcherSourceCompletionHandler? = nil) + { + self.init(sources: sources, options: options) + self.completionSourceHandler = completionHandler + } + + init(sources: [Source], options: KingfisherOptionsInfo?) { + var options = KingfisherParsedOptionsInfo(options) + prefetchSources = sources + pendingSources = ArraySlice(sources) + + // We want all callbacks from our prefetch queue, so we should ignore the callback queue in options. + // Add our own callback dispatch queue to make sure all internal callbacks are + // coming back in our expected queue. + options.callbackQueue = .dispatch(prefetchQueue) + optionsInfo = options + + let cache = optionsInfo.targetCache ?? .default + let downloader = optionsInfo.downloader ?? .default + manager = KingfisherManager(downloader: downloader, cache: cache) + } + + /// Starts to download the resources and cache them. This can be useful for background downloading + /// of assets that are required for later use in an app. This code will not try and update any UI + /// with the results of the process. + public func start() { + prefetchQueue.async { + guard !self.stopped else { + assertionFailure("You can not restart the same prefetcher. Try to create a new prefetcher.") + self.handleComplete() + return + } + + guard self.maxConcurrentDownloads > 0 else { + assertionFailure("There should be concurrent downloads value should be at least 1.") + self.handleComplete() + return + } + + // Empty case. + guard self.prefetchSources.count > 0 else { + self.handleComplete() + return + } + + let initialConcurrentDownloads = min(self.prefetchSources.count, self.maxConcurrentDownloads) + for _ in 0 ..< initialConcurrentDownloads { + if let resource = self.pendingSources.popFirst() { + self.startPrefetching(resource) + } + } + } + } + + /// Stops current downloading progress, and cancel any future prefetching activity that might be occuring. + public func stop() { + prefetchQueue.async { + if self.finished { return } + self.stopped = true + self.tasks.values.forEach { $0.cancel() } + } + } + + private func downloadAndCache(_ source: Source) { + + let downloadTaskCompletionHandler: ((Result) -> Void) = { result in + self.tasks.removeValue(forKey: source.cacheKey) + do { + let _ = try result.get() + self.completedSources.append(source) + } catch { + self.failedSources.append(source) + } + + self.reportProgress() + if self.stopped { + if self.tasks.isEmpty { + self.failedSources.append(contentsOf: self.pendingSources) + self.handleComplete() + } + } else { + self.reportCompletionOrStartNext() + } + } + + var downloadTask: DownloadTask.WrappedTask? + ImagePrefetcher.requestingQueue.sync { + let context = RetrievingContext( + options: optionsInfo, originalSource: source + ) + downloadTask = manager.loadAndCacheImage( + source: source, + context: context, + completionHandler: downloadTaskCompletionHandler) + } + + if let downloadTask = downloadTask { + tasks[source.cacheKey] = downloadTask + } + } + + private func append(cached source: Source) { + skippedSources.append(source) + + reportProgress() + reportCompletionOrStartNext() + } + + private func startPrefetching(_ source: Source) + { + if optionsInfo.forceRefresh { + downloadAndCache(source) + return + } + + let cacheType = manager.cache.imageCachedType( + forKey: source.cacheKey, + processorIdentifier: optionsInfo.processor.identifier) + switch cacheType { + case .memory: + append(cached: source) + case .disk: + if optionsInfo.alsoPrefetchToMemory { + let context = RetrievingContext(options: optionsInfo, originalSource: source) + _ = manager.retrieveImageFromCache( + source: source, + context: context) + { + _ in + self.append(cached: source) + } + } else { + append(cached: source) + } + case .none: + downloadAndCache(source) + } + } + + private func reportProgress() { + + if progressBlock == nil && progressSourceBlock == nil { + return + } + + let skipped = self.skippedSources + let failed = self.failedSources + let completed = self.completedSources + CallbackQueue.mainCurrentOrAsync.execute { + self.progressSourceBlock?(skipped, failed, completed) + self.progressBlock?( + skipped.compactMap { $0.asResource }, + failed.compactMap { $0.asResource }, + completed.compactMap { $0.asResource } + ) + } + } + + private func reportCompletionOrStartNext() { + if let resource = self.pendingSources.popFirst() { + // Loose call stack for huge ammount of sources. + prefetchQueue.async { self.startPrefetching(resource) } + } else { + guard allFinished else { return } + self.handleComplete() + } + } + + var allFinished: Bool { + return skippedSources.count + failedSources.count + completedSources.count == prefetchSources.count + } + + private func handleComplete() { + + if completionHandler == nil && completionSourceHandler == nil { + return + } + + // The completion handler should be called on the main thread + CallbackQueue.mainCurrentOrAsync.execute { + self.completionSourceHandler?(self.skippedSources, self.failedSources, self.completedSources) + self.completionHandler?( + self.skippedSources.compactMap { $0.asResource }, + self.failedSources.compactMap { $0.asResource }, + self.completedSources.compactMap { $0.asResource } + ) + self.completionHandler = nil + self.progressBlock = nil + } + } +} diff --git a/Pods/Kingfisher/Sources/Networking/RedirectHandler.swift b/Pods/Kingfisher/Sources/Networking/RedirectHandler.swift new file mode 100644 index 0000000..0d13cbe --- /dev/null +++ b/Pods/Kingfisher/Sources/Networking/RedirectHandler.swift @@ -0,0 +1,76 @@ +// +// RedirectHandler.swift +// Kingfisher +// +// Created by Roman Maidanovych on 2018/12/10. +// +// Copyright (c) 2019 Wei Wang +// +// Permission is hereby granted, free of charge, to any person obtaining a copy +// of this software and associated documentation files (the "Software"), to deal +// in the Software without restriction, including without limitation the rights +// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +// copies of the Software, and to permit persons to whom the Software is +// furnished to do so, subject to the following conditions: +// +// The above copyright notice and this permission notice shall be included in +// all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN +// THE SOFTWARE. + +import Foundation + +/// Represents and wraps a method for modifying request during an image download request redirection. +public protocol ImageDownloadRedirectHandler { + + /// The `ImageDownloadRedirectHandler` contained will be used to change the request before redirection. + /// This is the posibility you can modify the image download request during redirection. You can modify the + /// request for some customizing purpose, such as adding auth token to the header, do basic HTTP auth or + /// something like url mapping. + /// + /// Usually, you pass an `ImageDownloadRedirectHandler` as the associated value of + /// `KingfisherOptionsInfoItem.redirectHandler` and use it as the `options` parameter in related methods. + /// + /// If you do nothing with the input `request` and return it as is, a downloading process will redirect with it. + /// + /// - Parameters: + /// - task: The current `SessionDataTask` which triggers this redirect. + /// - response: The response received during redirection. + /// - newRequest: The request for redirection which can be modified. + /// - completionHandler: A closure for being called with modified request. + func handleHTTPRedirection( + for task: SessionDataTask, + response: HTTPURLResponse, + newRequest: URLRequest, + completionHandler: @escaping (URLRequest?) -> Void) +} + +/// A wrapper for creating an `ImageDownloadRedirectHandler` easier. +/// This type conforms to `ImageDownloadRedirectHandler` and wraps a redirect request modify block. +public struct AnyRedirectHandler: ImageDownloadRedirectHandler { + + let block: (SessionDataTask, HTTPURLResponse, URLRequest, @escaping (URLRequest?) -> Void) -> Void + + public func handleHTTPRedirection( + for task: SessionDataTask, + response: HTTPURLResponse, + newRequest: URLRequest, + completionHandler: @escaping (URLRequest?) -> Void) + { + block(task, response, newRequest, completionHandler) + } + + /// Creates a value of `ImageDownloadRedirectHandler` which runs `modify` block. + /// + /// - Parameter modify: The request modifying block runs when a request modifying task comes. + /// + public init(handle: @escaping (SessionDataTask, HTTPURLResponse, URLRequest, @escaping (URLRequest?) -> Void) -> Void) { + block = handle + } +} diff --git a/Pods/Kingfisher/Sources/Networking/RequestModifier.swift b/Pods/Kingfisher/Sources/Networking/RequestModifier.swift new file mode 100644 index 0000000..a1d972d --- /dev/null +++ b/Pods/Kingfisher/Sources/Networking/RequestModifier.swift @@ -0,0 +1,108 @@ +// +// RequestModifier.swift +// Kingfisher +// +// Created by Wei Wang on 2016/09/05. +// +// Copyright (c) 2019 Wei Wang +// +// Permission is hereby granted, free of charge, to any person obtaining a copy +// of this software and associated documentation files (the "Software"), to deal +// in the Software without restriction, including without limitation the rights +// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +// copies of the Software, and to permit persons to whom the Software is +// furnished to do so, subject to the following conditions: +// +// The above copyright notice and this permission notice shall be included in +// all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN +// THE SOFTWARE. + +import Foundation + +/// Represents and wraps a method for modifying request before an image download request starts in an asynchronous way. +public protocol AsyncImageDownloadRequestModifier { + + /// This method will be called just before the `request` being sent. + /// This is the last chance you can modify the image download request. You can modify the request for some + /// customizing purpose, such as adding auth token to the header, do basic HTTP auth or something like url mapping. + /// When you have done with the modification, call the `reportModified` block with the modified request and the data + /// download will happen with this request. + /// + /// Usually, you pass an `AsyncImageDownloadRequestModifier` as the associated value of + /// `KingfisherOptionsInfoItem.requestModifier` and use it as the `options` parameter in related methods. + /// + /// If you do nothing with the input `request` and return it as is, a downloading process will start with it. + /// + /// - Parameters: + /// - request: The input request contains necessary information like `url`. This request is generated + /// according to your resource url as a GET request. + /// - reportModified: The callback block you need to call after the asynchronous modifying done. + /// + func modified(for request: URLRequest, reportModified: @escaping (URLRequest?) -> Void) + + /// A block will be called when the download task started. + /// + /// If an `AsyncImageDownloadRequestModifier` and the asynchronous modification happens before the download, the + /// related download method will not return a valid `DownloadTask` value. Instead, you can get one from this method. + var onDownloadTaskStarted: ((DownloadTask?) -> Void)? { get } +} + +/// Represents and wraps a method for modifying request before an image download request starts. +public protocol ImageDownloadRequestModifier: AsyncImageDownloadRequestModifier { + + /// This method will be called just before the `request` being sent. + /// This is the last chance you can modify the image download request. You can modify the request for some + /// customizing purpose, such as adding auth token to the header, do basic HTTP auth or something like url mapping. + /// + /// Usually, you pass an `ImageDownloadRequestModifier` as the associated value of + /// `KingfisherOptionsInfoItem.requestModifier` and use it as the `options` parameter in related methods. + /// + /// If you do nothing with the input `request` and return it as is, a downloading process will start with it. + /// + /// - Parameter request: The input request contains necessary information like `url`. This request is generated + /// according to your resource url as a GET request. + /// - Returns: A modified version of request, which you wish to use for downloading an image. If `nil` returned, + /// a `KingfisherError.requestError` with `.emptyRequest` as its reason will occur. + /// + func modified(for request: URLRequest) -> URLRequest? +} + +extension ImageDownloadRequestModifier { + public func modified(for request: URLRequest, reportModified: @escaping (URLRequest?) -> Void) { + let request = modified(for: request) + reportModified(request) + } + + /// This is `nil` for a sync `ImageDownloadRequestModifier` by default. You can get the `DownloadTask` from the + /// return value of downloader method. + public var onDownloadTaskStarted: ((DownloadTask?) -> Void)? { return nil } +} + +/// A wrapper for creating an `ImageDownloadRequestModifier` easier. +/// This type conforms to `ImageDownloadRequestModifier` and wraps an image modify block. +public struct AnyModifier: ImageDownloadRequestModifier { + + let block: (URLRequest) -> URLRequest? + + /// For `ImageDownloadRequestModifier` conformation. + public func modified(for request: URLRequest) -> URLRequest? { + return block(request) + } + + /// Creates a value of `ImageDownloadRequestModifier` which runs `modify` block. + /// + /// - Parameter modify: The request modifying block runs when a request modifying task comes. + /// The return `URLRequest?` value of this block will be used as the image download request. + /// If `nil` returned, a `KingfisherError.requestError` with `.emptyRequest` as its + /// reason will occur. + public init(modify: @escaping (URLRequest) -> URLRequest?) { + block = modify + } +} diff --git a/Pods/Kingfisher/Sources/Networking/RetryStrategy.swift b/Pods/Kingfisher/Sources/Networking/RetryStrategy.swift new file mode 100644 index 0000000..1ab5a2e --- /dev/null +++ b/Pods/Kingfisher/Sources/Networking/RetryStrategy.swift @@ -0,0 +1,153 @@ +// +// RetryStrategy.swift +// Kingfisher +// +// Created by onevcat on 2020/05/04. +// +// Copyright (c) 2020 Wei Wang +// +// Permission is hereby granted, free of charge, to any person obtaining a copy +// of this software and associated documentation files (the "Software"), to deal +// in the Software without restriction, including without limitation the rights +// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +// copies of the Software, and to permit persons to whom the Software is +// furnished to do so, subject to the following conditions: +// +// The above copyright notice and this permission notice shall be included in +// all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN +// THE SOFTWARE. + +import Foundation + +/// Represents a retry context which could be used to determine the current retry status. +public class RetryContext { + + /// The source from which the target image should be retrieved. + public let source: Source + + /// The last error which caused current retry behavior. + public let error: KingfisherError + + /// The retried count before current retry happens. This value is `0` if the current retry is for the first time. + public var retriedCount: Int + + /// A user set value for passing any other information during the retry. If you choose to use `RetryDecision.retry` + /// as the retry decision for `RetryStrategy.retry(context:retryHandler:)`, the associated value of + /// `RetryDecision.retry` will be delivered to you in the next retry. + public internal(set) var userInfo: Any? = nil + + init(source: Source, error: KingfisherError) { + self.source = source + self.error = error + self.retriedCount = 0 + } + + @discardableResult + func increaseRetryCount() -> RetryContext { + retriedCount += 1 + return self + } +} + +/// Represents decision of behavior on the current retry. +public enum RetryDecision { + /// A retry should happen. The associated `userInfo` will be pass to the next retry in the `RetryContext` parameter. + case retry(userInfo: Any?) + /// There should be no more retry attempt. The image retrieving process will fail with an error. + case stop +} + +/// Defines a retry strategy can be applied to a `.retryStrategy` option. +public protocol RetryStrategy { + + /// Kingfisher calls this method if an error happens during the image retrieving process from a `KingfisherManager`. + /// You implement this method to provide necessary logic based on the `context` parameter. Then you need to call + /// `retryHandler` to pass the retry decision back to Kingfisher. + /// + /// - Parameters: + /// - context: The retry context containing information of current retry attempt. + /// - retryHandler: A block you need to call with a decision of whether the retry should happen or not. + func retry(context: RetryContext, retryHandler: @escaping (RetryDecision) -> Void) +} + +/// A retry strategy that guides Kingfisher to retry when a `.responseError` happens, with a specified max retry count +/// and a certain interval mechanism. +public struct DelayRetryStrategy: RetryStrategy { + + /// Represents the interval mechanism which used in a `DelayRetryStrategy`. + public enum Interval { + /// The next retry attempt should happen in fixed seconds. For example, if the associated value is 3, the + /// attempts happens after 3 seconds after the previous decision is made. + case seconds(TimeInterval) + /// The next retry attempt should happen in an accumulated duration. For example, if the associated value is 3, + /// the attempts happens with interval of 3, 6, 9, 12, ... seconds. + case accumulated(TimeInterval) + /// Uses a block to determine the next interval. The current retry count is given as a parameter. + case custom(block: (_ retriedCount: Int) -> TimeInterval) + + func timeInterval(for retriedCount: Int) -> TimeInterval { + let retryAfter: TimeInterval + switch self { + case .seconds(let interval): + retryAfter = interval + case .accumulated(let interval): + retryAfter = Double(retriedCount + 1) * interval + case .custom(let block): + retryAfter = block(retriedCount) + } + return retryAfter + } + } + + /// The max retry count defined for the retry strategy + public let maxRetryCount: Int + + /// The retry interval mechanism defined for the retry strategy. + public let retryInterval: Interval + + /// Creates a delay retry strategy. + /// - Parameters: + /// - maxRetryCount: The max retry count. + /// - retryInterval: The retry interval mechanism. By default, `.seconds(3)` is used to provide a constant retry + /// interval. + public init(maxRetryCount: Int, retryInterval: Interval = .seconds(3)) { + self.maxRetryCount = maxRetryCount + self.retryInterval = retryInterval + } + + public func retry(context: RetryContext, retryHandler: @escaping (RetryDecision) -> Void) { + // Retry count exceeded. + guard context.retriedCount < maxRetryCount else { + retryHandler(.stop) + return + } + + // User cancel the task. No retry. + guard !context.error.isTaskCancelled else { + retryHandler(.stop) + return + } + + // Only retry for a response error. + guard case KingfisherError.responseError = context.error else { + retryHandler(.stop) + return + } + + let interval = retryInterval.timeInterval(for: context.retriedCount) + if interval == 0 { + retryHandler(.retry(userInfo: nil)) + } else { + DispatchQueue.main.asyncAfter(deadline: .now() + interval) { + retryHandler(.retry(userInfo: nil)) + } + } + } +} diff --git a/Pods/Kingfisher/Sources/Networking/SessionDataTask.swift b/Pods/Kingfisher/Sources/Networking/SessionDataTask.swift new file mode 100644 index 0000000..8932bd5 --- /dev/null +++ b/Pods/Kingfisher/Sources/Networking/SessionDataTask.swift @@ -0,0 +1,127 @@ +// +// SessionDataTask.swift +// Kingfisher +// +// Created by Wei Wang on 2018/11/1. +// +// Copyright (c) 2019 Wei Wang +// +// Permission is hereby granted, free of charge, to any person obtaining a copy +// of this software and associated documentation files (the "Software"), to deal +// in the Software without restriction, including without limitation the rights +// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +// copies of the Software, and to permit persons to whom the Software is +// furnished to do so, subject to the following conditions: +// +// The above copyright notice and this permission notice shall be included in +// all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN +// THE SOFTWARE. + +import Foundation + +/// Represents a session data task in `ImageDownloader`. It consists of an underlying `URLSessionDataTask` and +/// an array of `TaskCallback`. Multiple `TaskCallback`s could be added for a single downloading data task. +public class SessionDataTask { + + /// Represents the type of token which used for cancelling a task. + public typealias CancelToken = Int + + struct TaskCallback { + let onCompleted: Delegate, Void>? + let options: KingfisherParsedOptionsInfo + } + + /// Downloaded raw data of current task. + public private(set) var mutableData: Data + + // This is a copy of `task.originalRequest?.url`. It is for getting a race-safe behavior for a pitfall on iOS 13. + // Ref: https://github.com/onevcat/Kingfisher/issues/1511 + public let originalURL: URL? + + /// The underlying download task. It is only for debugging purpose when you encountered an error. You should not + /// modify the content of this task or start it yourself. + public let task: URLSessionDataTask + private var callbacksStore = [CancelToken: TaskCallback]() + + var callbacks: [SessionDataTask.TaskCallback] { + lock.lock() + defer { lock.unlock() } + return Array(callbacksStore.values) + } + + private var currentToken = 0 + private let lock = NSLock() + + let onTaskDone = Delegate<(Result<(Data, URLResponse?), KingfisherError>, [TaskCallback]), Void>() + let onCallbackCancelled = Delegate<(CancelToken, TaskCallback), Void>() + + var started = false + var containsCallbacks: Bool { + // We should be able to use `task.state != .running` to check it. + // However, in some rare cases, cancelling the task does not change + // task state to `.cancelling` immediately, but still in `.running`. + // So we need to check callbacks count to for sure that it is safe to remove the + // task in delegate. + return !callbacks.isEmpty + } + + init(task: URLSessionDataTask) { + self.task = task + self.originalURL = task.originalRequest?.url + mutableData = Data() + } + + func addCallback(_ callback: TaskCallback) -> CancelToken { + lock.lock() + defer { lock.unlock() } + callbacksStore[currentToken] = callback + defer { currentToken += 1 } + return currentToken + } + + func removeCallback(_ token: CancelToken) -> TaskCallback? { + lock.lock() + defer { lock.unlock() } + if let callback = callbacksStore[token] { + callbacksStore[token] = nil + return callback + } + return nil + } + + func removeAllCallbacks() -> Void { + lock.lock() + defer { lock.unlock() } + callbacksStore.removeAll() + } + + func resume() { + guard !started else { return } + started = true + task.resume() + } + + func cancel(token: CancelToken) { + guard let callback = removeCallback(token) else { + return + } + onCallbackCancelled.call((token, callback)) + } + + func forceCancel() { + for token in callbacksStore.keys { + cancel(token: token) + } + } + + func didReceiveData(_ data: Data) { + mutableData.append(data) + } +} diff --git a/Pods/Kingfisher/Sources/Networking/SessionDelegate.swift b/Pods/Kingfisher/Sources/Networking/SessionDelegate.swift new file mode 100644 index 0000000..a4f6bf4 --- /dev/null +++ b/Pods/Kingfisher/Sources/Networking/SessionDelegate.swift @@ -0,0 +1,271 @@ +// +// SessionDelegate.swift +// Kingfisher +// +// Created by Wei Wang on 2018/11/1. +// +// Copyright (c) 2019 Wei Wang +// +// Permission is hereby granted, free of charge, to any person obtaining a copy +// of this software and associated documentation files (the "Software"), to deal +// in the Software without restriction, including without limitation the rights +// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +// copies of the Software, and to permit persons to whom the Software is +// furnished to do so, subject to the following conditions: +// +// The above copyright notice and this permission notice shall be included in +// all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN +// THE SOFTWARE. + +import Foundation + +// Represents the delegate object of downloader session. It also behave like a task manager for downloading. +@objc(KFSessionDelegate) // Fix for ObjC header name conflicting. https://github.com/onevcat/Kingfisher/issues/1530 +open class SessionDelegate: NSObject { + + typealias SessionChallengeFunc = ( + URLSession, + URLAuthenticationChallenge, + (URLSession.AuthChallengeDisposition, URLCredential?) -> Void + ) + + typealias SessionTaskChallengeFunc = ( + URLSession, + URLSessionTask, + URLAuthenticationChallenge, + (URLSession.AuthChallengeDisposition, URLCredential?) -> Void + ) + + private var tasks: [URL: SessionDataTask] = [:] + private let lock = NSLock() + + let onValidStatusCode = Delegate() + let onResponseReceived = Delegate<(URLResponse, (URLSession.ResponseDisposition) -> Void), Void>() + let onDownloadingFinished = Delegate<(URL, Result), Void>() + let onDidDownloadData = Delegate() + + let onReceiveSessionChallenge = Delegate() + let onReceiveSessionTaskChallenge = Delegate() + + func add( + _ dataTask: URLSessionDataTask, + url: URL, + callback: SessionDataTask.TaskCallback) -> DownloadTask + { + lock.lock() + defer { lock.unlock() } + + // Create a new task if necessary. + let task = SessionDataTask(task: dataTask) + task.onCallbackCancelled.delegate(on: self) { [weak task] (self, value) in + guard let task = task else { return } + + let (token, callback) = value + + let error = KingfisherError.requestError(reason: .taskCancelled(task: task, token: token)) + task.onTaskDone.call((.failure(error), [callback])) + // No other callbacks waiting, we can clear the task now. + if !task.containsCallbacks { + let dataTask = task.task + + self.cancelTask(dataTask) + self.remove(task) + } + } + let token = task.addCallback(callback) + tasks[url] = task + return DownloadTask(sessionTask: task, cancelToken: token) + } + + private func cancelTask(_ dataTask: URLSessionDataTask) { + lock.lock() + defer { lock.unlock() } + dataTask.cancel() + } + + func append( + _ task: SessionDataTask, + callback: SessionDataTask.TaskCallback) -> DownloadTask + { + let token = task.addCallback(callback) + return DownloadTask(sessionTask: task, cancelToken: token) + } + + private func remove(_ task: SessionDataTask) { + lock.lock() + defer { lock.unlock() } + + guard let url = task.originalURL else { + return + } + task.removeAllCallbacks() + tasks[url] = nil + } + + private func task(for task: URLSessionTask) -> SessionDataTask? { + lock.lock() + defer { lock.unlock() } + + guard let url = task.originalRequest?.url else { + return nil + } + guard let sessionTask = tasks[url] else { + return nil + } + guard sessionTask.task.taskIdentifier == task.taskIdentifier else { + return nil + } + return sessionTask + } + + func task(for url: URL) -> SessionDataTask? { + lock.lock() + defer { lock.unlock() } + return tasks[url] + } + + func cancelAll() { + lock.lock() + let taskValues = tasks.values + lock.unlock() + for task in taskValues { + task.forceCancel() + } + } + + func cancel(url: URL) { + lock.lock() + let task = tasks[url] + lock.unlock() + task?.forceCancel() + } +} + +extension SessionDelegate: URLSessionDataDelegate { + + open func urlSession( + _ session: URLSession, + dataTask: URLSessionDataTask, + didReceive response: URLResponse, + completionHandler: @escaping (URLSession.ResponseDisposition) -> Void) + { + guard let httpResponse = response as? HTTPURLResponse else { + let error = KingfisherError.responseError(reason: .invalidURLResponse(response: response)) + onCompleted(task: dataTask, result: .failure(error)) + completionHandler(.cancel) + return + } + + let httpStatusCode = httpResponse.statusCode + guard onValidStatusCode.call(httpStatusCode) == true else { + let error = KingfisherError.responseError(reason: .invalidHTTPStatusCode(response: httpResponse)) + onCompleted(task: dataTask, result: .failure(error)) + completionHandler(.cancel) + return + } + + let inspectedHandler: (URLSession.ResponseDisposition) -> Void = { disposition in + if disposition == .cancel { + let error = KingfisherError.responseError(reason: .cancelledByDelegate(response: response)) + self.onCompleted(task: dataTask, result: .failure(error)) + } + completionHandler(disposition) + } + onResponseReceived.call((response, inspectedHandler)) + } + + open func urlSession(_ session: URLSession, dataTask: URLSessionDataTask, didReceive data: Data) { + guard let task = self.task(for: dataTask) else { + return + } + + task.didReceiveData(data) + + task.callbacks.forEach { callback in + callback.options.onDataReceived?.forEach { sideEffect in + sideEffect.onDataReceived(session, task: task, data: data) + } + } + } + + open func urlSession(_ session: URLSession, task: URLSessionTask, didCompleteWithError error: Error?) { + guard let sessionTask = self.task(for: task) else { return } + + if let url = sessionTask.originalURL { + let result: Result + if let error = error { + result = .failure(KingfisherError.responseError(reason: .URLSessionError(error: error))) + } else if let response = task.response { + result = .success(response) + } else { + result = .failure(KingfisherError.responseError(reason: .noURLResponse(task: sessionTask))) + } + onDownloadingFinished.call((url, result)) + } + + let result: Result<(Data, URLResponse?), KingfisherError> + if let error = error { + result = .failure(KingfisherError.responseError(reason: .URLSessionError(error: error))) + } else { + if let data = onDidDownloadData.call(sessionTask) { + result = .success((data, task.response)) + } else { + result = .failure(KingfisherError.responseError(reason: .dataModifyingFailed(task: sessionTask))) + } + } + onCompleted(task: task, result: result) + } + + open func urlSession( + _ session: URLSession, + didReceive challenge: URLAuthenticationChallenge, + completionHandler: @escaping (URLSession.AuthChallengeDisposition, URLCredential?) -> Void) + { + onReceiveSessionChallenge.call((session, challenge, completionHandler)) + } + + open func urlSession( + _ session: URLSession, + task: URLSessionTask, + didReceive challenge: URLAuthenticationChallenge, + completionHandler: @escaping (URLSession.AuthChallengeDisposition, URLCredential?) -> Void) + { + onReceiveSessionTaskChallenge.call((session, task, challenge, completionHandler)) + } + + open func urlSession( + _ session: URLSession, + task: URLSessionTask, + willPerformHTTPRedirection response: HTTPURLResponse, + newRequest request: URLRequest, + completionHandler: @escaping (URLRequest?) -> Void) + { + guard let sessionDataTask = self.task(for: task), + let redirectHandler = Array(sessionDataTask.callbacks).last?.options.redirectHandler else + { + completionHandler(request) + return + } + + redirectHandler.handleHTTPRedirection( + for: sessionDataTask, + response: response, + newRequest: request, + completionHandler: completionHandler) + } + + private func onCompleted(task: URLSessionTask, result: Result<(Data, URLResponse?), KingfisherError>) { + guard let sessionTask = self.task(for: task) else { + return + } + sessionTask.onTaskDone.call((result, sessionTask.callbacks)) + remove(sessionTask) + } +} diff --git a/Pods/Kingfisher/Sources/PrivacyInfo.xcprivacy b/Pods/Kingfisher/Sources/PrivacyInfo.xcprivacy new file mode 100644 index 0000000..993e1f6 --- /dev/null +++ b/Pods/Kingfisher/Sources/PrivacyInfo.xcprivacy @@ -0,0 +1,25 @@ + + + + + NSPrivacyAccessedAPITypes + + + NSPrivacyAccessedAPIType + NSPrivacyAccessedAPICategoryFileTimestamp + NSPrivacyAccessedAPITypeReasons + + C617.1 + + + + NSPrivacyTracking + + NSPrivacyTrackingDomains + + + NSPrivacyCollectedDataTypes + + + + diff --git a/Pods/Kingfisher/Sources/SwiftUI/ImageBinder.swift b/Pods/Kingfisher/Sources/SwiftUI/ImageBinder.swift new file mode 100644 index 0000000..7ad5f2c --- /dev/null +++ b/Pods/Kingfisher/Sources/SwiftUI/ImageBinder.swift @@ -0,0 +1,149 @@ +// +// ImageBinder.swift +// Kingfisher +// +// Created by onevcat on 2019/06/27. +// +// Copyright (c) 2019 Wei Wang +// +// Permission is hereby granted, free of charge, to any person obtaining a copy +// of this software and associated documentation files (the "Software"), to deal +// in the Software without restriction, including without limitation the rights +// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +// copies of the Software, and to permit persons to whom the Software is +// furnished to do so, subject to the following conditions: +// +// The above copyright notice and this permission notice shall be included in +// all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN +// THE SOFTWARE. + +#if canImport(SwiftUI) && canImport(Combine) +import SwiftUI +import Combine + +@available(iOS 14.0, macOS 11.0, tvOS 14.0, watchOS 7.0, *) +extension KFImage { + + /// Represents a binder for `KFImage`. It takes responsibility as an `ObjectBinding` and performs + /// image downloading and progress reporting based on `KingfisherManager`. + class ImageBinder: ObservableObject { + + init() {} + + var downloadTask: DownloadTask? + private var loading = false + + var loadingOrSucceeded: Bool { + return loading || loadedImage != nil + } + + // Do not use @Published due to https://github.com/onevcat/Kingfisher/issues/1717. Revert to @Published once + // we can drop iOS 12. + private(set) var loaded = false + + private(set) var animating = false + + var loadedImage: KFCrossPlatformImage? = nil { willSet { objectWillChange.send() } } + var progress: Progress = .init() + + func markLoading() { + loading = true + } + + func markLoaded(sendChangeEvent: Bool) { + loaded = true + if sendChangeEvent { + objectWillChange.send() + } + } + + func start(context: Context) { + guard let source = context.source else { + CallbackQueue.mainCurrentOrAsync.execute { + context.onFailureDelegate.call(KingfisherError.imageSettingError(reason: .emptySource)) + if let image = context.options.onFailureImage { + self.loadedImage = image + } + self.loading = false + self.markLoaded(sendChangeEvent: false) + } + return + } + + loading = true + + progress = .init() + downloadTask = KingfisherManager.shared + .retrieveImage( + with: source, + options: context.options, + progressBlock: { size, total in + self.updateProgress(downloaded: size, total: total) + context.onProgressDelegate.call((size, total)) + }, + completionHandler: { [weak self] result in + + guard let self = self else { return } + + CallbackQueue.mainCurrentOrAsync.execute { + self.downloadTask = nil + self.loading = false + } + + switch result { + case .success(let value): + CallbackQueue.mainCurrentOrAsync.execute { + if let fadeDuration = context.fadeTransitionDuration(cacheType: value.cacheType) { + self.animating = true + let animation = Animation.linear(duration: fadeDuration) + withAnimation(animation) { + // Trigger the view render to apply the animation. + self.markLoaded(sendChangeEvent: true) + } + } else { + self.markLoaded(sendChangeEvent: false) + } + self.loadedImage = value.image + self.animating = false + } + + CallbackQueue.mainAsync.execute { + context.onSuccessDelegate.call(value) + } + case .failure(let error): + CallbackQueue.mainCurrentOrAsync.execute { + if let image = context.options.onFailureImage { + self.loadedImage = image + } + self.markLoaded(sendChangeEvent: false) + } + + CallbackQueue.mainAsync.execute { + context.onFailureDelegate.call(error) + } + } + }) + } + + private func updateProgress(downloaded: Int64, total: Int64) { + progress.totalUnitCount = total + progress.completedUnitCount = downloaded + objectWillChange.send() + } + + /// Cancels the download task if it is in progress. + func cancel() { + downloadTask?.cancel() + downloadTask = nil + loading = false + } + } +} +#endif diff --git a/Pods/Kingfisher/Sources/SwiftUI/ImageContext.swift b/Pods/Kingfisher/Sources/SwiftUI/ImageContext.swift new file mode 100644 index 0000000..730477b --- /dev/null +++ b/Pods/Kingfisher/Sources/SwiftUI/ImageContext.swift @@ -0,0 +1,102 @@ +// +// ImageContext.swift +// Kingfisher +// +// Created by onevcat on 2021/05/08. +// +// Copyright (c) 2021 Wei Wang +// +// Permission is hereby granted, free of charge, to any person obtaining a copy +// of this software and associated documentation files (the "Software"), to deal +// in the Software without restriction, including without limitation the rights +// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +// copies of the Software, and to permit persons to whom the Software is +// furnished to do so, subject to the following conditions: +// +// The above copyright notice and this permission notice shall be included in +// all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN +// THE SOFTWARE. + +#if canImport(SwiftUI) && canImport(Combine) +import SwiftUI +import Combine + +@available(iOS 14.0, macOS 11.0, tvOS 14.0, watchOS 7.0, *) +extension KFImage { + public class Context { + let source: Source? + var options = KingfisherParsedOptionsInfo( + KingfisherManager.shared.defaultOptions + [.loadDiskFileSynchronously] + ) + + var configurations: [(HoldingView) -> HoldingView] = [] + var renderConfigurations: [(HoldingView.RenderingView) -> Void] = [] + var contentConfiguration: ((HoldingView) -> AnyView)? = nil + + var cancelOnDisappear: Bool = false + var placeholder: ((Progress) -> AnyView)? = nil + + let onFailureDelegate = Delegate() + let onSuccessDelegate = Delegate() + let onProgressDelegate = Delegate<(Int64, Int64), Void>() + + var startLoadingBeforeViewAppear: Bool = false + + init(source: Source?) { + self.source = source + } + + func shouldApplyFade(cacheType: CacheType) -> Bool { + options.forceTransition || cacheType == .none + } + + func fadeTransitionDuration(cacheType: CacheType) -> TimeInterval? { + shouldApplyFade(cacheType: cacheType) + ? options.transition.fadeDuration + : nil + } + } +} + +extension ImageTransition { + // Only for fade effect in SwiftUI. + fileprivate var fadeDuration: TimeInterval? { + switch self { + case .fade(let duration): + return duration + default: + return nil + } + } +} + + +@available(iOS 14.0, macOS 11.0, tvOS 14.0, watchOS 7.0, *) +extension KFImage.Context: Hashable { + public static func == (lhs: KFImage.Context, rhs: KFImage.Context) -> Bool { + lhs.source == rhs.source && + lhs.options.processor.identifier == rhs.options.processor.identifier + } + + public func hash(into hasher: inout Hasher) { + hasher.combine(source) + hasher.combine(options.processor.identifier) + } +} + +#if canImport(UIKit) && !os(watchOS) +@available(iOS 14.0, macOS 11.0, tvOS 14.0, watchOS 7.0, *) +extension KFAnimatedImage { + public typealias Context = KFImage.Context + typealias ImageBinder = KFImage.ImageBinder +} +#endif + +#endif diff --git a/Pods/Kingfisher/Sources/SwiftUI/KFAnimatedImage.swift b/Pods/Kingfisher/Sources/SwiftUI/KFAnimatedImage.swift new file mode 100644 index 0000000..ad25eb2 --- /dev/null +++ b/Pods/Kingfisher/Sources/SwiftUI/KFAnimatedImage.swift @@ -0,0 +1,96 @@ +// +// KFAnimatedImage.swift +// Kingfisher +// +// Created by wangxingbin on 2021/4/29. +// +// Copyright (c) 2021 Wei Wang +// +// Permission is hereby granted, free of charge, to any person obtaining a copy +// of this software and associated documentation files (the "Software"), to deal +// in the Software without restriction, including without limitation the rights +// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +// copies of the Software, and to permit persons to whom the Software is +// furnished to do so, subject to the following conditions: +// +// The above copyright notice and this permission notice shall be included in +// all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN +// THE SOFTWARE. + +#if canImport(SwiftUI) && canImport(Combine) && canImport(UIKit) && !os(watchOS) +import SwiftUI +import Combine + +@available(iOS 14.0, macOS 11.0, tvOS 14.0, watchOS 7.0, *) +public struct KFAnimatedImage: KFImageProtocol { + public typealias HoldingView = KFAnimatedImageViewRepresenter + public var context: Context + public init(context: KFImage.Context) { + self.context = context + } + + /// Configures current rendering view with a `block`. This block will be applied when the under-hood + /// `AnimatedImageView` is created in `UIViewRepresentable.makeUIView(context:)` + /// + /// - Parameter block: The block applies to the animated image view. + /// - Returns: A `KFAnimatedImage` view that being configured by the `block`. + public func configure(_ block: @escaping (HoldingView.RenderingView) -> Void) -> Self { + context.renderConfigurations.append(block) + return self + } +} + +/// A wrapped `UIViewRepresentable` of `AnimatedImageView` +@available(iOS 14.0, macOS 11.0, tvOS 14.0, watchOS 7.0, *) +public struct KFAnimatedImageViewRepresenter: UIViewRepresentable, KFImageHoldingView { + public typealias RenderingView = AnimatedImageView + public static func created(from image: KFCrossPlatformImage?, context: KFImage.Context) -> KFAnimatedImageViewRepresenter { + KFAnimatedImageViewRepresenter(image: image, context: context) + } + + var image: KFCrossPlatformImage? + let context: KFImage.Context + + public func makeUIView(context: Context) -> AnimatedImageView { + let view = AnimatedImageView() + + self.context.renderConfigurations.forEach { $0(view) } + + view.image = image + + // Allow SwiftUI scale (fit/fill) working fine. + view.setContentCompressionResistancePriority(.defaultLow, for: .horizontal) + view.setContentCompressionResistancePriority(.defaultLow, for: .vertical) + return view + } + + public func updateUIView(_ uiView: AnimatedImageView, context: Context) { + uiView.image = image + } +} + +#if DEBUG +@available(iOS 14.0, macOS 11.0, tvOS 14.0, watchOS 7.0, *) +struct KFAnimatedImage_Previews: PreviewProvider { + static var previews: some View { + Group { + KFAnimatedImage(source: .network(URL(string: "https://raw.githubusercontent.com/onevcat/Kingfisher-TestImages/master/DemoAppImage/GIF/1.gif")!)) + .onSuccess { r in + print(r) + } + .placeholder { + ProgressView() + } + .padding() + } + } +} +#endif +#endif diff --git a/Pods/Kingfisher/Sources/SwiftUI/KFImage.swift b/Pods/Kingfisher/Sources/SwiftUI/KFImage.swift new file mode 100644 index 0000000..67f1c19 --- /dev/null +++ b/Pods/Kingfisher/Sources/SwiftUI/KFImage.swift @@ -0,0 +1,106 @@ +// +// KFImage.swift +// Kingfisher +// +// Created by onevcat on 2019/06/26. +// +// Copyright (c) 2019 Wei Wang +// +// Permission is hereby granted, free of charge, to any person obtaining a copy +// of this software and associated documentation files (the "Software"), to deal +// in the Software without restriction, including without limitation the rights +// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +// copies of the Software, and to permit persons to whom the Software is +// furnished to do so, subject to the following conditions: +// +// The above copyright notice and this permission notice shall be included in +// all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN +// THE SOFTWARE. + +#if canImport(SwiftUI) && canImport(Combine) +import SwiftUI +import Combine + +@available(iOS 14.0, macOS 11.0, tvOS 14.0, watchOS 7.0, *) +public struct KFImage: KFImageProtocol { + public var context: Context + public init(context: Context) { + self.context = context + } +} + +@available(iOS 14.0, macOS 11.0, tvOS 14.0, watchOS 7.0, *) +extension Image: KFImageHoldingView { + public typealias RenderingView = Image + public static func created(from image: KFCrossPlatformImage?, context: KFImage.Context) -> Image { + Image(crossPlatformImage: image) + } +} + +// MARK: - Image compatibility. +@available(iOS 14.0, macOS 11.0, tvOS 14.0, watchOS 7.0, *) +extension KFImage { + + public func resizable( + capInsets: EdgeInsets = EdgeInsets(), + resizingMode: Image.ResizingMode = .stretch) -> KFImage + { + configure { $0.resizable(capInsets: capInsets, resizingMode: resizingMode) } + } + + public func renderingMode(_ renderingMode: Image.TemplateRenderingMode?) -> KFImage { + configure { $0.renderingMode(renderingMode) } + } + + public func interpolation(_ interpolation: Image.Interpolation) -> KFImage { + configure { $0.interpolation(interpolation) } + } + + public func antialiased(_ isAntialiased: Bool) -> KFImage { + configure { $0.antialiased(isAntialiased) } + } + + /// Starts the loading process of `self` immediately. + /// + /// By default, a `KFImage` will not load its source until the `onAppear` is called. This is a lazily loading + /// behavior and provides better performance. However, when you refresh the view, the lazy loading also causes a + /// flickering since the loading does not happen immediately. Call this method if you want to start the load at once + /// could help avoiding the flickering, with some performance trade-off. + /// + /// - Deprecated: This is not necessary anymore since `@StateObject` is used for holding the image data. + /// It does nothing now and please just remove it. + /// + /// - Returns: The `Self` value with changes applied. + @available(*, deprecated, message: "This is not necessary anymore since `@StateObject` is used. It does nothing now and please just remove it.") + public func loadImmediately(_ start: Bool = true) -> KFImage { + return self + } +} + +#if DEBUG +@available(iOS 14.0, macOS 11.0, tvOS 14.0, watchOS 7.0, *) +struct KFImage_Previews: PreviewProvider { + static var previews: some View { + Group { + KFImage.url(URL(string: "https://raw.githubusercontent.com/onevcat/Kingfisher/master/images/logo.png")!) + .onSuccess { r in + print(r) + } + .placeholder { p in + ProgressView(p) + } + .resizable() + .aspectRatio(contentMode: .fit) + .padding() + } + } +} +#endif +#endif diff --git a/Pods/Kingfisher/Sources/SwiftUI/KFImageOptions.swift b/Pods/Kingfisher/Sources/SwiftUI/KFImageOptions.swift new file mode 100644 index 0000000..a63d909 --- /dev/null +++ b/Pods/Kingfisher/Sources/SwiftUI/KFImageOptions.swift @@ -0,0 +1,158 @@ +// +// KFImageOptions.swift +// Kingfisher +// +// Created by onevcat on 2020/12/20. +// +// Copyright (c) 2020 Wei Wang +// +// Permission is hereby granted, free of charge, to any person obtaining a copy +// of this software and associated documentation files (the "Software"), to deal +// in the Software without restriction, including without limitation the rights +// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +// copies of the Software, and to permit persons to whom the Software is +// furnished to do so, subject to the following conditions: +// +// The above copyright notice and this permission notice shall be included in +// all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN +// THE SOFTWARE. + +#if canImport(SwiftUI) && canImport(Combine) +import SwiftUI +import Combine + +// MARK: - KFImage creating. +@available(iOS 14.0, macOS 11.0, tvOS 14.0, watchOS 7.0, *) +extension KFImageProtocol { + + /// Creates a `KFImage` for a given `Source`. + /// - Parameters: + /// - source: The `Source` object defines data information from network or a data provider. + /// - Returns: A `KFImage` for future configuration or embedding to a `SwiftUI.View`. + public static func source( + _ source: Source? + ) -> Self + { + Self.init(source: source) + } + + /// Creates a `KFImage` for a given `Resource`. + /// - Parameters: + /// - source: The `Resource` object defines data information like key or URL. + /// - Returns: A `KFImage` for future configuration or embedding to a `SwiftUI.View`. + public static func resource( + _ resource: Resource? + ) -> Self + { + source(resource?.convertToSource()) + } + + /// Creates a `KFImage` for a given `URL`. + /// - Parameters: + /// - url: The URL where the image should be downloaded. + /// - cacheKey: The key used to store the downloaded image in cache. + /// If `nil`, the `absoluteString` of `url` is used as the cache key. + /// - Returns: A `KFImage` for future configuration or embedding to a `SwiftUI.View`. + public static func url( + _ url: URL?, cacheKey: String? = nil + ) -> Self + { + source(url?.convertToSource(overrideCacheKey: cacheKey)) + } + + /// Creates a `KFImage` for a given `ImageDataProvider`. + /// - Parameters: + /// - provider: The `ImageDataProvider` object contains information about the data. + /// - Returns: A `KFImage` for future configuration or embedding to a `SwiftUI.View`. + public static func dataProvider( + _ provider: ImageDataProvider? + ) -> Self + { + source(provider?.convertToSource()) + } + + /// Creates a builder for some given raw data and a cache key. + /// - Parameters: + /// - data: The data object from which the image should be created. + /// - cacheKey: The key used to store the downloaded image in cache. + /// - Returns: A `KFImage` for future configuration or embedding to a `SwiftUI.View`. + public static func data( + _ data: Data?, cacheKey: String + ) -> Self + { + if let data = data { + return dataProvider(RawImageDataProvider(data: data, cacheKey: cacheKey)) + } else { + return dataProvider(nil) + } + } +} + +@available(iOS 14.0, macOS 11.0, tvOS 14.0, watchOS 7.0, *) +extension KFImageProtocol { + /// Sets a placeholder `View` which shows when loading the image, with a progress parameter as input. + /// - Parameter content: A view that describes the placeholder. + /// - Returns: A `KFImage` view that contains `content` as its placeholder. + public func placeholder(@ViewBuilder _ content: @escaping (Progress) -> P) -> Self { + context.placeholder = { progress in + return AnyView(content(progress)) + } + return self + } + + /// Sets a placeholder `View` which shows when loading the image. + /// - Parameter content: A view that describes the placeholder. + /// - Returns: A `KFImage` view that contains `content` as its placeholder. + public func placeholder(@ViewBuilder _ content: @escaping () -> P) -> Self { + placeholder { _ in content() } + } + + /// Sets cancelling the download task bound to `self` when the view disappearing. + /// - Parameter flag: Whether cancel the task or not. + /// - Returns: A `KFImage` view that cancels downloading task when disappears. + public func cancelOnDisappear(_ flag: Bool) -> Self { + context.cancelOnDisappear = flag + return self + } + + /// Sets a fade transition for the image task. + /// - Parameter duration: The duration of the fade transition. + /// - Returns: A `KFImage` with changes applied. + /// + /// Kingfisher will use the fade transition to animate the image in if it is downloaded from web. + /// The transition will not happen when the + /// image is retrieved from either memory or disk cache by default. If you need to do the transition even when + /// the image being retrieved from cache, also call `forceRefresh()` on the returned `KFImage`. + public func fade(duration: TimeInterval) -> Self { + context.options.transition = .fade(duration) + return self + } + + /// Sets whether to start the image loading before the view actually appears. + /// + /// By default, Kingfisher performs a lazy loading for `KFImage`. The image loading won't start until the view's + /// `onAppear` is called. However, sometimes you may want to trigger an aggressive loading for the view. By enabling + /// this, the `KFImage` will try to load the view when its `body` is evaluated when the image loading is not yet + /// started or a previous loading did fail. + /// + /// - Parameter flag: Whether the image loading should happen before view appear. Default is `true`. + /// - Returns: A `KFImage` with changes applied. + /// + /// - Note: This is a temporary workaround for an issue from iOS 16, where the SwiftUI view's `onAppear` is not + /// called when it is deeply embedded inside a `List` or `ForEach`. + /// See [#1988](https://github.com/onevcat/Kingfisher/issues/1988). It may cause performance regression, especially + /// if you have a lot of images to load in the view. Use it as your own risk. + /// + public func startLoadingBeforeViewAppear(_ flag: Bool = true) -> Self { + context.startLoadingBeforeViewAppear = flag + return self + } +} +#endif diff --git a/Pods/Kingfisher/Sources/SwiftUI/KFImageProtocol.swift b/Pods/Kingfisher/Sources/SwiftUI/KFImageProtocol.swift new file mode 100644 index 0000000..5a5ad4b --- /dev/null +++ b/Pods/Kingfisher/Sources/SwiftUI/KFImageProtocol.swift @@ -0,0 +1,112 @@ +// +// KFImageProtocol.swift +// Kingfisher +// +// Created by onevcat on 2021/05/08. +// +// Copyright (c) 2021 Wei Wang +// +// Permission is hereby granted, free of charge, to any person obtaining a copy +// of this software and associated documentation files (the "Software"), to deal +// in the Software without restriction, including without limitation the rights +// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +// copies of the Software, and to permit persons to whom the Software is +// furnished to do so, subject to the following conditions: +// +// The above copyright notice and this permission notice shall be included in +// all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN +// THE SOFTWARE. + +#if canImport(SwiftUI) && canImport(Combine) +import SwiftUI +import Combine + +@available(iOS 14.0, macOS 11.0, tvOS 14.0, watchOS 7.0, *) +public protocol KFImageProtocol: View, KFOptionSetter { + associatedtype HoldingView: KFImageHoldingView + var context: KFImage.Context { get set } + init(context: KFImage.Context) +} + +@available(iOS 14.0, macOS 11.0, tvOS 14.0, watchOS 7.0, *) +extension KFImageProtocol { + public var body: some View { + ZStack { + KFImageRenderer( + context: context + ).id(context) + } + } + + /// Creates a Kingfisher compatible image view to load image from the given `Source`. + /// - Parameters: + /// - source: The image `Source` defining where to load the target image. + public init(source: Source?) { + let context = KFImage.Context(source: source) + self.init(context: context) + } + + /// Creates a Kingfisher compatible image view to load image from the given `URL`. + /// - Parameters: + /// - source: The image `Source` defining where to load the target image. + public init(_ url: URL?) { + self.init(source: url?.convertToSource()) + } + + /// Configures current image with a `block` and return another `Image` to use as the final content. + /// + /// This block will be lazily applied when creating the final `Image`. + /// + /// If multiple `configure` modifiers are added to the image, they will be evaluated by order. If you want to + /// configure the input image (which is usually an `Image` value) to a non-`Image` value, use `contentConfigure`. + /// + /// - Parameter block: The block applies to loaded image. The block should return an `Image` that is configured. + /// - Returns: A `KFImage` view that configures internal `Image` with `block`. + public func configure(_ block: @escaping (HoldingView) -> HoldingView) -> Self { + context.configurations.append(block) + return self + } + + /// Configures current image with a `block` and return a `View` to use as the final content. + /// + /// This block will be lazily applied when creating the final `Image`. + /// + /// If multiple `contentConfigure` modifiers are added to the image, only the last one will be stored and used. + /// + /// - Parameter block: The block applies to the loaded image. The block should return a `View` that is configured. + /// - Returns: A `KFImage` view that configures internal `Image` with `block`. + public func contentConfigure(_ block: @escaping (HoldingView) -> V) -> Self { + context.contentConfiguration = { AnyView(block($0)) } + return self + } +} + +@available(iOS 14.0, macOS 11.0, tvOS 14.0, watchOS 7.0, *) +public protocol KFImageHoldingView: View { + associatedtype RenderingView + static func created(from image: KFCrossPlatformImage?, context: KFImage.Context) -> Self +} + +@available(iOS 14.0, macOS 11.0, tvOS 14.0, watchOS 7.0, *) +extension KFImageProtocol { + public var options: KingfisherParsedOptionsInfo { + get { context.options } + nonmutating set { context.options = newValue } + } + + public var onFailureDelegate: Delegate { context.onFailureDelegate } + public var onSuccessDelegate: Delegate { context.onSuccessDelegate } + public var onProgressDelegate: Delegate<(Int64, Int64), Void> { context.onProgressDelegate } + + public var delegateObserver: AnyObject { context } +} + + +#endif diff --git a/Pods/Kingfisher/Sources/SwiftUI/KFImageRenderer.swift b/Pods/Kingfisher/Sources/SwiftUI/KFImageRenderer.swift new file mode 100644 index 0000000..5203b4e --- /dev/null +++ b/Pods/Kingfisher/Sources/SwiftUI/KFImageRenderer.swift @@ -0,0 +1,129 @@ +// +// KFImageRenderer.swift +// Kingfisher +// +// Created by onevcat on 2021/05/08. +// +// Copyright (c) 2021 Wei Wang +// +// Permission is hereby granted, free of charge, to any person obtaining a copy +// of this software and associated documentation files (the "Software"), to deal +// in the Software without restriction, including without limitation the rights +// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +// copies of the Software, and to permit persons to whom the Software is +// furnished to do so, subject to the following conditions: +// +// The above copyright notice and this permission notice shall be included in +// all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN +// THE SOFTWARE. + +#if canImport(SwiftUI) && canImport(Combine) +import SwiftUI +import Combine + +/// A Kingfisher compatible SwiftUI `View` to load an image from a `Source`. +/// Declaring a `KFImage` in a `View`'s body to trigger loading from the given `Source`. +@available(iOS 14.0, macOS 11.0, tvOS 14.0, watchOS 7.0, *) +struct KFImageRenderer : View where HoldingView: KFImageHoldingView { + + @StateObject var binder: KFImage.ImageBinder = .init() + let context: KFImage.Context + + var body: some View { + if context.startLoadingBeforeViewAppear && !binder.loadingOrSucceeded && !binder.animating { + binder.markLoading() + DispatchQueue.main.async { binder.start(context: context) } + } + + return ZStack { + renderedImage().opacity(binder.loaded ? 1.0 : 0.0) + if binder.loadedImage == nil { + ZStack { + if let placeholder = context.placeholder { + placeholder(binder.progress) + } else { + Color.clear + } + } + .onAppear { [weak binder = self.binder] in + guard let binder = binder else { + return + } + if !binder.loadingOrSucceeded { + binder.start(context: context) + } + } + .onDisappear { [weak binder = self.binder] in + guard let binder = binder else { + return + } + if context.cancelOnDisappear { + binder.cancel() + } + } + } + } + // Workaround for https://github.com/onevcat/Kingfisher/issues/1988 + // on iOS 16 there seems to be a bug that when in a List, the `onAppear` of the `ZStack` above in the + // `binder.loadedImage == nil` not get called. Adding this empty `onAppear` fixes it and the life cycle can + // work again. + // + // There is another "fix": adding an `else` clause and put a `Color.clear` there. But I believe this `onAppear` + // should work better. + // + // It should be a bug in iOS 16, I guess it is some kinds of over-optimization in list cell loading caused it. + .onAppear() + } + + @ViewBuilder + private func renderedImage() -> some View { + let configuredImage = context.configurations + .reduce(HoldingView.created(from: binder.loadedImage, context: context)) { + current, config in config(current) + } + if let contentConfiguration = context.contentConfiguration { + contentConfiguration(configuredImage) + } else { + configuredImage + } + } +} + +@available(iOS 14.0, macOS 11.0, tvOS 14.0, watchOS 7.0, *) +extension Image { + // Creates an Image with either UIImage or NSImage. + init(crossPlatformImage: KFCrossPlatformImage?) { + #if canImport(UIKit) + self.init(uiImage: crossPlatformImage ?? KFCrossPlatformImage()) + #elseif canImport(AppKit) + self.init(nsImage: crossPlatformImage ?? KFCrossPlatformImage()) + #endif + } +} + +#if canImport(UIKit) +@available(iOS 14.0, macOS 11.0, tvOS 14.0, watchOS 7.0, *) +extension UIImage.Orientation { + func toSwiftUI() -> Image.Orientation { + switch self { + case .down: return .down + case .up: return .up + case .left: return .left + case .right: return .right + case .upMirrored: return .upMirrored + case .downMirrored: return .downMirrored + case .leftMirrored: return .leftMirrored + case .rightMirrored: return .rightMirrored + @unknown default: return .up + } + } +} +#endif +#endif diff --git a/Pods/Kingfisher/Sources/Utility/Box.swift b/Pods/Kingfisher/Sources/Utility/Box.swift new file mode 100644 index 0000000..0303a6e --- /dev/null +++ b/Pods/Kingfisher/Sources/Utility/Box.swift @@ -0,0 +1,34 @@ +// +// Box.swift +// Kingfisher +// +// Created by Wei Wang on 2018/3/17. +// Copyright (c) 2019 Wei Wang +// +// Permission is hereby granted, free of charge, to any person obtaining a copy +// of this software and associated documentation files (the "Software"), to deal +// in the Software without restriction, including without limitation the rights +// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +// copies of the Software, and to permit persons to whom the Software is +// furnished to do so, subject to the following conditions: +// +// The above copyright notice and this permission notice shall be included in +// all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN +// THE SOFTWARE. + +import Foundation + +class Box { + var value: T + + init(_ value: T) { + self.value = value + } +} diff --git a/Pods/Kingfisher/Sources/Utility/CallbackQueue.swift b/Pods/Kingfisher/Sources/Utility/CallbackQueue.swift new file mode 100644 index 0000000..822af28 --- /dev/null +++ b/Pods/Kingfisher/Sources/Utility/CallbackQueue.swift @@ -0,0 +1,83 @@ +// +// CallbackQueue.swift +// Kingfisher +// +// Created by onevcat on 2018/10/15. +// +// Copyright (c) 2019 Wei Wang +// +// Permission is hereby granted, free of charge, to any person obtaining a copy +// of this software and associated documentation files (the "Software"), to deal +// in the Software without restriction, including without limitation the rights +// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +// copies of the Software, and to permit persons to whom the Software is +// furnished to do so, subject to the following conditions: +// +// The above copyright notice and this permission notice shall be included in +// all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN +// THE SOFTWARE. + +import Foundation + +public typealias ExecutionQueue = CallbackQueue + +/// Represents callback queue behaviors when an calling of closure be dispatched. +/// +/// - asyncMain: Dispatch the calling to `DispatchQueue.main` with an `async` behavior. +/// - currentMainOrAsync: Dispatch the calling to `DispatchQueue.main` with an `async` behavior if current queue is not +/// `.main`. Otherwise, call the closure immediately in current main queue. +/// - untouch: Do not change the calling queue for closure. +/// - dispatch: Dispatches to a specified `DispatchQueue`. +public enum CallbackQueue { + /// Dispatch the calling to `DispatchQueue.main` with an `async` behavior. + case mainAsync + /// Dispatch the calling to `DispatchQueue.main` with an `async` behavior if current queue is not + /// `.main`. Otherwise, call the closure immediately in current main queue. + case mainCurrentOrAsync + /// Do not change the calling queue for closure. + case untouch + /// Dispatches to a specified `DispatchQueue`. + case dispatch(DispatchQueue) + + public func execute(_ block: @escaping () -> Void) { + switch self { + case .mainAsync: + DispatchQueue.main.async { block() } + case .mainCurrentOrAsync: + DispatchQueue.main.safeAsync { block() } + case .untouch: + block() + case .dispatch(let queue): + queue.async { block() } + } + } + + var queue: DispatchQueue { + switch self { + case .mainAsync: return .main + case .mainCurrentOrAsync: return .main + case .untouch: return OperationQueue.current?.underlyingQueue ?? .main + case .dispatch(let queue): return queue + } + } +} + +extension DispatchQueue { + // This method will dispatch the `block` to self. + // If `self` is the main queue, and current thread is main thread, the block + // will be invoked immediately instead of being dispatched. + func safeAsync(_ block: @escaping () -> Void) { + if self === DispatchQueue.main && Thread.isMainThread { + block() + } else { + async { block() } + } + } +} diff --git a/Pods/Kingfisher/Sources/Utility/Delegate.swift b/Pods/Kingfisher/Sources/Utility/Delegate.swift new file mode 100644 index 0000000..9caa1a6 --- /dev/null +++ b/Pods/Kingfisher/Sources/Utility/Delegate.swift @@ -0,0 +1,132 @@ +// +// Delegate.swift +// Kingfisher +// +// Created by onevcat on 2018/10/10. +// +// Copyright (c) 2019 Wei Wang +// +// Permission is hereby granted, free of charge, to any person obtaining a copy +// of this software and associated documentation files (the "Software"), to deal +// in the Software without restriction, including without limitation the rights +// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +// copies of the Software, and to permit persons to whom the Software is +// furnished to do so, subject to the following conditions: +// +// The above copyright notice and this permission notice shall be included in +// all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN +// THE SOFTWARE. + +import Foundation +/// A class that keeps a weakly reference for `self` when implementing `onXXX` behaviors. +/// Instead of remembering to keep `self` as weak in a stored closure: +/// +/// ```swift +/// // MyClass.swift +/// var onDone: (() -> Void)? +/// func done() { +/// onDone?() +/// } +/// +/// // ViewController.swift +/// var obj: MyClass? +/// +/// func doSomething() { +/// obj = MyClass() +/// obj!.onDone = { [weak self] in +/// self?.reportDone() +/// } +/// } +/// ``` +/// +/// You can create a `Delegate` and observe on `self`. Now, there is no retain cycle inside: +/// +/// ```swift +/// // MyClass.swift +/// let onDone = Delegate<(), Void>() +/// func done() { +/// onDone.call() +/// } +/// +/// // ViewController.swift +/// var obj: MyClass? +/// +/// func doSomething() { +/// obj = MyClass() +/// obj!.onDone.delegate(on: self) { (self, _) +/// // `self` here is shadowed and does not keep a strong ref. +/// // So you can release both `MyClass` instance and `ViewController` instance. +/// self.reportDone() +/// } +/// } +/// ``` +/// +public class Delegate { + public init() {} + + private var block: ((Input) -> Output?)? + public func delegate(on target: T, block: ((T, Input) -> Output)?) { + self.block = { [weak target] input in + guard let target = target else { return nil } + return block?(target, input) + } + } + + public func call(_ input: Input) -> Output? { + return block?(input) + } + + public func callAsFunction(_ input: Input) -> Output? { + return call(input) + } +} + +extension Delegate where Input == Void { + public func call() -> Output? { + return call(()) + } + + public func callAsFunction() -> Output? { + return call() + } +} + +extension Delegate where Input == Void, Output: OptionalProtocol { + public func call() -> Output { + return call(()) + } + + public func callAsFunction() -> Output { + return call() + } +} + +extension Delegate where Output: OptionalProtocol { + public func call(_ input: Input) -> Output { + if let result = block?(input) { + return result + } else { + return Output._createNil + } + } + + public func callAsFunction(_ input: Input) -> Output { + return call(input) + } +} + +public protocol OptionalProtocol { + static var _createNil: Self { get } +} +extension Optional : OptionalProtocol { + public static var _createNil: Optional { + return nil + } +} diff --git a/Pods/Kingfisher/Sources/Utility/ExtensionHelpers.swift b/Pods/Kingfisher/Sources/Utility/ExtensionHelpers.swift new file mode 100644 index 0000000..22b2063 --- /dev/null +++ b/Pods/Kingfisher/Sources/Utility/ExtensionHelpers.swift @@ -0,0 +1,117 @@ +// +// ExtensionHelpers.swift +// Kingfisher +// +// Created by onevcat on 2018/09/28. +// +// Copyright (c) 2019 Wei Wang +// +// Permission is hereby granted, free of charge, to any person obtaining a copy +// of this software and associated documentation files (the "Software"), to deal +// in the Software without restriction, including without limitation the rights +// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +// copies of the Software, and to permit persons to whom the Software is +// furnished to do so, subject to the following conditions: +// +// The above copyright notice and this permission notice shall be included in +// all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN +// THE SOFTWARE. + +import Foundation + +extension CGFloat { + var isEven: Bool { + return truncatingRemainder(dividingBy: 2.0) == 0 + } +} + +#if canImport(AppKit) && !targetEnvironment(macCatalyst) +import AppKit +extension NSBezierPath { + convenience init(roundedRect rect: NSRect, topLeftRadius: CGFloat, topRightRadius: CGFloat, + bottomLeftRadius: CGFloat, bottomRightRadius: CGFloat) + { + self.init() + + let maxCorner = min(rect.width, rect.height) / 2 + + let radiusTopLeft = min(maxCorner, max(0, topLeftRadius)) + let radiusTopRight = min(maxCorner, max(0, topRightRadius)) + let radiusBottomLeft = min(maxCorner, max(0, bottomLeftRadius)) + let radiusBottomRight = min(maxCorner, max(0, bottomRightRadius)) + + guard !rect.isEmpty else { + return + } + + let topLeft = NSPoint(x: rect.minX, y: rect.maxY) + let topRight = NSPoint(x: rect.maxX, y: rect.maxY) + let bottomRight = NSPoint(x: rect.maxX, y: rect.minY) + + move(to: NSPoint(x: rect.midX, y: rect.maxY)) + appendArc(from: topLeft, to: rect.origin, radius: radiusTopLeft) + appendArc(from: rect.origin, to: bottomRight, radius: radiusBottomLeft) + appendArc(from: bottomRight, to: topRight, radius: radiusBottomRight) + appendArc(from: topRight, to: topLeft, radius: radiusTopRight) + close() + } + + convenience init(roundedRect rect: NSRect, byRoundingCorners corners: RectCorner, radius: CGFloat) { + let radiusTopLeft = corners.contains(.topLeft) ? radius : 0 + let radiusTopRight = corners.contains(.topRight) ? radius : 0 + let radiusBottomLeft = corners.contains(.bottomLeft) ? radius : 0 + let radiusBottomRight = corners.contains(.bottomRight) ? radius : 0 + + self.init(roundedRect: rect, topLeftRadius: radiusTopLeft, topRightRadius: radiusTopRight, + bottomLeftRadius: radiusBottomLeft, bottomRightRadius: radiusBottomRight) + } +} + +extension KFCrossPlatformImage { + // macOS does not support scale. This is just for code compatibility across platforms. + convenience init?(data: Data, scale: CGFloat) { + self.init(data: data) + } +} +#endif + +#if canImport(UIKit) +import UIKit +extension RectCorner { + var uiRectCorner: UIRectCorner { + + var result: UIRectCorner = [] + + if contains(.topLeft) { result.insert(.topLeft) } + if contains(.topRight) { result.insert(.topRight) } + if contains(.bottomLeft) { result.insert(.bottomLeft) } + if contains(.bottomRight) { result.insert(.bottomRight) } + + return result + } +} +#endif + +extension Date { + var isPast: Bool { + return isPast(referenceDate: Date()) + } + + func isPast(referenceDate: Date) -> Bool { + return timeIntervalSince(referenceDate) <= 0 + } + + // `Date` in memory is a wrap for `TimeInterval`. But in file attribute it can only accept `Int` number. + // By default the system will `round` it. But it is not friendly for testing purpose. + // So we always `ceil` the value when used for file attributes. + var fileAttributeDate: Date { + return Date(timeIntervalSince1970: ceil(timeIntervalSince1970)) + } +} diff --git a/Pods/Kingfisher/Sources/Utility/Result.swift b/Pods/Kingfisher/Sources/Utility/Result.swift new file mode 100644 index 0000000..dcdb08b --- /dev/null +++ b/Pods/Kingfisher/Sources/Utility/Result.swift @@ -0,0 +1,50 @@ +// +// Result.swift +// Kingfisher +// +// Created by onevcat on 2018/09/22. +// +// Copyright (c) 2019 Wei Wang +// +// Permission is hereby granted, free of charge, to any person obtaining a copy +// of this software and associated documentation files (the "Software"), to deal +// in the Software without restriction, including without limitation the rights +// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +// copies of the Software, and to permit persons to whom the Software is +// furnished to do so, subject to the following conditions: +// +// The above copyright notice and this permission notice shall be included in +// all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN +// THE SOFTWARE. + +import Foundation + +// These helper methods are not public since we do not want them to be exposed or cause any conflicting. +// However, they are just wrapper of `ResultUtil` static methods. +extension Result where Failure: Error { + + /// Evaluates the given transform closures to create a single output value. + /// + /// - Parameters: + /// - onSuccess: A closure that transforms the success value. + /// - onFailure: A closure that transforms the error value. + /// - Returns: A single `Output` value. + func match( + onSuccess: (Success) -> Output, + onFailure: (Failure) -> Output) -> Output + { + switch self { + case let .success(value): + return onSuccess(value) + case let .failure(error): + return onFailure(error) + } + } +} diff --git a/Pods/Kingfisher/Sources/Utility/Runtime.swift b/Pods/Kingfisher/Sources/Utility/Runtime.swift new file mode 100644 index 0000000..c8039cb --- /dev/null +++ b/Pods/Kingfisher/Sources/Utility/Runtime.swift @@ -0,0 +1,39 @@ +// +// Runtime.swift +// Kingfisher +// +// Created by Wei Wang on 2018/10/12. +// +// Copyright (c) 2019 Wei Wang +// +// Permission is hereby granted, free of charge, to any person obtaining a copy +// of this software and associated documentation files (the "Software"), to deal +// in the Software without restriction, including without limitation the rights +// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +// copies of the Software, and to permit persons to whom the Software is +// furnished to do so, subject to the following conditions: +// +// The above copyright notice and this permission notice shall be included in +// all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN +// THE SOFTWARE. + +import Foundation + +func getAssociatedObject(_ object: Any, _ key: UnsafeRawPointer) -> T? { + if #available(iOS 14, macOS 11, watchOS 7, tvOS 14, *) { // swift 5.3 fixed this issue (https://github.com/apple/swift/issues/46456) + return objc_getAssociatedObject(object, key) as? T + } else { + return objc_getAssociatedObject(object, key) as AnyObject as? T + } +} + +func setRetainedAssociatedObject(_ object: Any, _ key: UnsafeRawPointer, _ value: T) { + objc_setAssociatedObject(object, key, value, .OBJC_ASSOCIATION_RETAIN_NONATOMIC) +} diff --git a/Pods/Kingfisher/Sources/Utility/SizeExtensions.swift b/Pods/Kingfisher/Sources/Utility/SizeExtensions.swift new file mode 100644 index 0000000..19d05d6 --- /dev/null +++ b/Pods/Kingfisher/Sources/Utility/SizeExtensions.swift @@ -0,0 +1,110 @@ +// +// SizeExtensions.swift +// Kingfisher +// +// Created by onevcat on 2018/09/28. +// +// Copyright (c) 2019 Wei Wang +// +// Permission is hereby granted, free of charge, to any person obtaining a copy +// of this software and associated documentation files (the "Software"), to deal +// in the Software without restriction, including without limitation the rights +// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +// copies of the Software, and to permit persons to whom the Software is +// furnished to do so, subject to the following conditions: +// +// The above copyright notice and this permission notice shall be included in +// all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN +// THE SOFTWARE. + +import CoreGraphics + +extension CGSize: KingfisherCompatibleValue {} +extension KingfisherWrapper where Base == CGSize { + + /// Returns a size by resizing the `base` size to a target size under a given content mode. + /// + /// - Parameters: + /// - size: The target size to resize to. + /// - contentMode: Content mode of the target size should be when resizing. + /// - Returns: The resized size under the given `ContentMode`. + public func resize(to size: CGSize, for contentMode: ContentMode) -> CGSize { + switch contentMode { + case .aspectFit: + return constrained(size) + case .aspectFill: + return filling(size) + case .none: + return size + } + } + + /// Returns a size by resizing the `base` size by making it aspect fitting the given `size`. + /// + /// - Parameter size: The size in which the `base` should fit in. + /// - Returns: The size fitted in by the input `size`, while keeps `base` aspect. + public func constrained(_ size: CGSize) -> CGSize { + let aspectWidth = round(aspectRatio * size.height) + let aspectHeight = round(size.width / aspectRatio) + + return aspectWidth > size.width ? + CGSize(width: size.width, height: aspectHeight) : + CGSize(width: aspectWidth, height: size.height) + } + + /// Returns a size by resizing the `base` size by making it aspect filling the given `size`. + /// + /// - Parameter size: The size in which the `base` should fill. + /// - Returns: The size be filled by the input `size`, while keeps `base` aspect. + public func filling(_ size: CGSize) -> CGSize { + let aspectWidth = round(aspectRatio * size.height) + let aspectHeight = round(size.width / aspectRatio) + + return aspectWidth < size.width ? + CGSize(width: size.width, height: aspectHeight) : + CGSize(width: aspectWidth, height: size.height) + } + + /// Returns a `CGRect` for which the `base` size is constrained to an input `size` at a given `anchor` point. + /// + /// - Parameters: + /// - size: The size in which the `base` should be constrained to. + /// - anchor: An anchor point in which the size constraint should happen. + /// - Returns: The result `CGRect` for the constraint operation. + public func constrainedRect(for size: CGSize, anchor: CGPoint) -> CGRect { + + let unifiedAnchor = CGPoint(x: anchor.x.clamped(to: 0.0...1.0), + y: anchor.y.clamped(to: 0.0...1.0)) + + let x = unifiedAnchor.x * base.width - unifiedAnchor.x * size.width + let y = unifiedAnchor.y * base.height - unifiedAnchor.y * size.height + let r = CGRect(x: x, y: y, width: size.width, height: size.height) + + let ori = CGRect(origin: .zero, size: base) + return ori.intersection(r) + } + + private var aspectRatio: CGFloat { + return base.height == 0.0 ? 1.0 : base.width / base.height + } +} + +extension CGRect { + func scaled(_ scale: CGFloat) -> CGRect { + return CGRect(x: origin.x * scale, y: origin.y * scale, + width: size.width * scale, height: size.height * scale) + } +} + +extension Comparable { + func clamped(to limits: ClosedRange) -> Self { + return min(max(self, limits.lowerBound), limits.upperBound) + } +} diff --git a/Pods/Kingfisher/Sources/Utility/String+MD5.swift b/Pods/Kingfisher/Sources/Utility/String+MD5.swift new file mode 100644 index 0000000..59586b5 --- /dev/null +++ b/Pods/Kingfisher/Sources/Utility/String+MD5.swift @@ -0,0 +1,278 @@ +// +// String+MD5.swift +// Kingfisher +// +// Created by Wei Wang on 18/09/25. +// +// Copyright (c) 2019 Wei Wang +// +// Permission is hereby granted, free of charge, to any person obtaining a copy +// of this software and associated documentation files (the "Software"), to deal +// in the Software without restriction, including without limitation the rights +// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +// copies of the Software, and to permit persons to whom the Software is +// furnished to do so, subject to the following conditions: +// +// The above copyright notice and this permission notice shall be included in +// all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN +// THE SOFTWARE. + +import Foundation +import CommonCrypto + +extension String: KingfisherCompatibleValue { } +extension KingfisherWrapper where Base == String { + var md5: String { + guard let data = base.data(using: .utf8) else { + return base + } + + let message = data.withUnsafeBytes { (bytes: UnsafeRawBufferPointer) in + return [UInt8](bytes) + } + + let MD5Calculator = MD5(message) + let MD5Data = MD5Calculator.calculate() + + var MD5String = String() + for c in MD5Data { + MD5String += String(format: "%02x", c) + } + return MD5String + } + + var ext: String? { + var ext = "" + if let index = base.lastIndex(of: ".") { + let extRange = base.index(index, offsetBy: 1).. 0 ? String(firstSeg) : nil + } +} + +// array of bytes, little-endian representation +func arrayOfBytes(_ value: T, length: Int? = nil) -> [UInt8] { + let totalBytes = length ?? (MemoryLayout.size * 8) + + let valuePointer = UnsafeMutablePointer.allocate(capacity: 1) + valuePointer.pointee = value + + let bytes = valuePointer.withMemoryRebound(to: UInt8.self, capacity: totalBytes) { (bytesPointer) -> [UInt8] in + var bytes = [UInt8](repeating: 0, count: totalBytes) + for j in 0...size, totalBytes) { + bytes[totalBytes - 1 - j] = (bytesPointer + j).pointee + } + return bytes + } + + valuePointer.deinitialize(count: 1) + valuePointer.deallocate() + + return bytes +} + +extension Int { + // Array of bytes with optional padding (little-endian) + func bytes(_ totalBytes: Int = MemoryLayout.size) -> [UInt8] { + return arrayOfBytes(self, length: totalBytes) + } + +} + +protocol HashProtocol { + var message: [UInt8] { get } + // Common part for hash calculation. Prepare header data. + func prepare(_ len: Int) -> [UInt8] +} + +extension HashProtocol { + + func prepare(_ len: Int) -> [UInt8] { + var tmpMessage = message + + // Step 1. Append Padding Bits + tmpMessage.append(0x80) // append one bit (UInt8 with one bit) to message + + // append "0" bit until message length in bits ≡ 448 (mod 512) + var msgLength = tmpMessage.count + var counter = 0 + + while msgLength % len != (len - 8) { + counter += 1 + msgLength += 1 + } + + tmpMessage += [UInt8](repeating: 0, count: counter) + return tmpMessage + } +} + +func toUInt32Array(_ slice: ArraySlice) -> [UInt32] { + var result = [UInt32]() + result.reserveCapacity(16) + + for idx in stride(from: slice.startIndex, to: slice.endIndex, by: MemoryLayout.size) { + let d0 = UInt32(slice[idx.advanced(by: 3)]) << 24 + let d1 = UInt32(slice[idx.advanced(by: 2)]) << 16 + let d2 = UInt32(slice[idx.advanced(by: 1)]) << 8 + let d3 = UInt32(slice[idx]) + let val: UInt32 = d0 | d1 | d2 | d3 + + result.append(val) + } + return result +} + +struct BytesIterator: IteratorProtocol { + + let chunkSize: Int + let data: [UInt8] + + init(chunkSize: Int, data: [UInt8]) { + self.chunkSize = chunkSize + self.data = data + } + + var offset = 0 + + mutating func next() -> ArraySlice? { + let end = min(chunkSize, data.count - offset) + let result = data[offset.. 0 ? result : nil + } +} + +struct BytesSequence: Sequence { + let chunkSize: Int + let data: [UInt8] + + func makeIterator() -> BytesIterator { + return BytesIterator(chunkSize: chunkSize, data: data) + } +} + +func rotateLeft(_ value: UInt32, bits: UInt32) -> UInt32 { + return ((value << bits) & 0xFFFFFFFF) | (value >> (32 - bits)) +} + +class MD5: HashProtocol { + + let message: [UInt8] + + init (_ message: [UInt8]) { + self.message = message + } + + // specifies the per-round shift amounts + private let shifts: [UInt32] = [7, 12, 17, 22, 7, 12, 17, 22, 7, 12, 17, 22, 7, 12, 17, 22, + 5, 9, 14, 20, 5, 9, 14, 20, 5, 9, 14, 20, 5, 9, 14, 20, + 4, 11, 16, 23, 4, 11, 16, 23, 4, 11, 16, 23, 4, 11, 16, 23, + 6, 10, 15, 21, 6, 10, 15, 21, 6, 10, 15, 21, 6, 10, 15, 21] + + // binary integer part of the sines of integers (Radians) + private let sines: [UInt32] = [0xd76aa478, 0xe8c7b756, 0x242070db, 0xc1bdceee, + 0xf57c0faf, 0x4787c62a, 0xa8304613, 0xfd469501, + 0x698098d8, 0x8b44f7af, 0xffff5bb1, 0x895cd7be, + 0x6b901122, 0xfd987193, 0xa679438e, 0x49b40821, + 0xf61e2562, 0xc040b340, 0x265e5a51, 0xe9b6c7aa, + 0xd62f105d, 0x02441453, 0xd8a1e681, 0xe7d3fbc8, + 0x21e1cde6, 0xc33707d6, 0xf4d50d87, 0x455a14ed, + 0xa9e3e905, 0xfcefa3f8, 0x676f02d9, 0x8d2a4c8a, + 0xfffa3942, 0x8771f681, 0x6d9d6122, 0xfde5380c, + 0xa4beea44, 0x4bdecfa9, 0xf6bb4b60, 0xbebfbc70, + 0x289b7ec6, 0xeaa127fa, 0xd4ef3085, 0x4881d05, + 0xd9d4d039, 0xe6db99e5, 0x1fa27cf8, 0xc4ac5665, + 0xf4292244, 0x432aff97, 0xab9423a7, 0xfc93a039, + 0x655b59c3, 0x8f0ccc92, 0xffeff47d, 0x85845dd1, + 0x6fa87e4f, 0xfe2ce6e0, 0xa3014314, 0x4e0811a1, + 0xf7537e82, 0xbd3af235, 0x2ad7d2bb, 0xeb86d391] + + private let hashes: [UInt32] = [0x67452301, 0xefcdab89, 0x98badcfe, 0x10325476] + + func calculate() -> [UInt8] { + var tmpMessage = prepare(64) + tmpMessage.reserveCapacity(tmpMessage.count + 4) + + // hash values + var hh = hashes + + // Step 2. Append Length a 64-bit representation of lengthInBits + let lengthInBits = (message.count * 8) + let lengthBytes = lengthInBits.bytes(64 / 8) + tmpMessage += lengthBytes.reversed() + + // Process the message in successive 512-bit chunks: + let chunkSizeBytes = 512 / 8 // 64 + + for chunk in BytesSequence(chunkSize: chunkSizeBytes, data: tmpMessage) { + // break chunk into sixteen 32-bit words M[j], 0 ≤ j ≤ 15 + let M = toUInt32Array(chunk) + assert(M.count == 16, "Invalid array") + + // Initialize hash value for this chunk: + var A: UInt32 = hh[0] + var B: UInt32 = hh[1] + var C: UInt32 = hh[2] + var D: UInt32 = hh[3] + + var dTemp: UInt32 = 0 + + // Main loop + for j in 0 ..< sines.count { + var g = 0 + var F: UInt32 = 0 + + switch j { + case 0...15: + F = (B & C) | ((~B) & D) + g = j + case 16...31: + F = (D & B) | (~D & C) + g = (5 * j + 1) % 16 + case 32...47: + F = B ^ C ^ D + g = (3 * j + 5) % 16 + case 48...63: + F = C ^ (B | (~D)) + g = (7 * j) % 16 + default: + break + } + dTemp = D + D = C + C = B + B = B &+ rotateLeft((A &+ F &+ sines[j] &+ M[g]), bits: shifts[j]) + A = dTemp + } + + hh[0] = hh[0] &+ A + hh[1] = hh[1] &+ B + hh[2] = hh[2] &+ C + hh[3] = hh[3] &+ D + } + var result = [UInt8]() + result.reserveCapacity(hh.count / 4) + + hh.forEach { + let itemLE = $0.littleEndian + let r1 = UInt8(itemLE & 0xff) + let r2 = UInt8((itemLE >> 8) & 0xff) + let r3 = UInt8((itemLE >> 16) & 0xff) + let r4 = UInt8((itemLE >> 24) & 0xff) + result += [r1, r2, r3, r4] + } + return result + } +} diff --git a/Pods/Kingfisher/Sources/Views/AnimatedImageView.swift b/Pods/Kingfisher/Sources/Views/AnimatedImageView.swift new file mode 100644 index 0000000..c4f57df --- /dev/null +++ b/Pods/Kingfisher/Sources/Views/AnimatedImageView.swift @@ -0,0 +1,730 @@ +// +// AnimatableImageView.swift +// Kingfisher +// +// Created by bl4ckra1sond3tre on 4/22/16. +// +// The AnimatableImageView, AnimatedFrame and Animator is a modified version of +// some classes from kaishin's Gifu project (https://github.com/kaishin/Gifu) +// +// The MIT License (MIT) +// +// Copyright (c) 2019 Reda Lemeden. +// +// Permission is hereby granted, free of charge, to any person obtaining a copy of +// this software and associated documentation files (the "Software"), to deal in +// the Software without restriction, including without limitation the rights to +// use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of +// the Software, and to permit persons to whom the Software is furnished to do so, +// subject to the following conditions: +// +// The above copyright notice and this permission notice shall be included in all +// copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS +// FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR +// COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER +// IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN +// CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. +// +// The name and characters used in the demo of this software are property of their +// respective owners. + +#if !os(watchOS) +#if canImport(UIKit) +import UIKit +import ImageIO + +/// Protocol of `AnimatedImageView`. +public protocol AnimatedImageViewDelegate: AnyObject { + + /// Called after the animatedImageView has finished each animation loop. + /// + /// - Parameters: + /// - imageView: The `AnimatedImageView` that is being animated. + /// - count: The looped count. + func animatedImageView(_ imageView: AnimatedImageView, didPlayAnimationLoops count: UInt) + + /// Called after the `AnimatedImageView` has reached the max repeat count. + /// + /// - Parameter imageView: The `AnimatedImageView` that is being animated. + func animatedImageViewDidFinishAnimating(_ imageView: AnimatedImageView) +} + +extension AnimatedImageViewDelegate { + public func animatedImageView(_ imageView: AnimatedImageView, didPlayAnimationLoops count: UInt) {} + public func animatedImageViewDidFinishAnimating(_ imageView: AnimatedImageView) {} +} + +let KFRunLoopModeCommon = RunLoop.Mode.common + +/// Represents a subclass of `UIImageView` for displaying animated image. +/// Different from showing animated image in a normal `UIImageView` (which load all frames at one time), +/// `AnimatedImageView` only tries to load several frames (defined by `framePreloadCount`) to reduce memory usage. +/// It provides a tradeoff between memory usage and CPU time. If you have a memory issue when using a normal image +/// view to load GIF data, you could give this class a try. +/// +/// Kingfisher supports setting GIF animated data to either `UIImageView` and `AnimatedImageView` out of box. So +/// it would be fairly easy to switch between them. +open class AnimatedImageView: UIImageView { + /// Proxy object for preventing a reference cycle between the `CADDisplayLink` and `AnimatedImageView`. + class TargetProxy { + private weak var target: AnimatedImageView? + + init(target: AnimatedImageView) { + self.target = target + } + + @objc func onScreenUpdate() { + target?.updateFrameIfNeeded() + } + } + + /// Enumeration that specifies repeat count of GIF + public enum RepeatCount: Equatable { + case once + case finite(count: UInt) + case infinite + + public static func ==(lhs: RepeatCount, rhs: RepeatCount) -> Bool { + switch (lhs, rhs) { + case let (.finite(l), .finite(r)): + return l == r + case (.once, .once), + (.infinite, .infinite): + return true + case (.once, .finite(let count)), + (.finite(let count), .once): + return count == 1 + case (.once, _), + (.infinite, _), + (.finite, _): + return false + } + } + } + + // MARK: - Public property + /// Whether automatically play the animation when the view become visible. Default is `true`. + public var autoPlayAnimatedImage = true + + /// The count of the frames should be preloaded before shown. + public var framePreloadCount = 10 + + /// Specifies whether the GIF frames should be pre-scaled to the image view's size or not. + /// If the downloaded image is larger than the image view's size, it will help to reduce some memory use. + /// Default is `true`. + public var needsPrescaling = true + + /// Decode the GIF frames in background thread before using. It will decode frames data and do a off-screen + /// rendering to extract pixel information in background. This can reduce the main thread CPU usage. + public var backgroundDecode = true + + /// The animation timer's run loop mode. Default is `RunLoop.Mode.common`. + /// Set this property to `RunLoop.Mode.default` will make the animation pause during UIScrollView scrolling. + public var runLoopMode = KFRunLoopModeCommon { + willSet { + guard runLoopMode != newValue else { return } + stopAnimating() + displayLink.remove(from: .main, forMode: runLoopMode) + displayLink.add(to: .main, forMode: newValue) + startAnimating() + } + } + + /// The repeat count. The animated image will keep animate until it the loop count reaches this value. + /// Setting this value to another one will reset current animation. + /// + /// Default is `.infinite`, which means the animation will last forever. + public var repeatCount = RepeatCount.infinite { + didSet { + if oldValue != repeatCount { + reset() + setNeedsDisplay() + layer.setNeedsDisplay() + } + } + } + + /// Delegate of this `AnimatedImageView` object. See `AnimatedImageViewDelegate` protocol for more. + public weak var delegate: AnimatedImageViewDelegate? + + /// The `Animator` instance that holds the frames of a specific image in memory. + public private(set) var animator: Animator? + + // MARK: - Private property + // Dispatch queue used for preloading images. + private lazy var preloadQueue: DispatchQueue = { + return DispatchQueue(label: "com.onevcat.Kingfisher.Animator.preloadQueue") + }() + + // A flag to avoid invalidating the displayLink on deinit if it was never created, because displayLink is so lazy. + private var isDisplayLinkInitialized: Bool = false + + // A display link that keeps calling the `updateFrame` method on every screen refresh. + private lazy var displayLink: CADisplayLink = { + isDisplayLinkInitialized = true + let displayLink = CADisplayLink(target: TargetProxy(target: self), selector: #selector(TargetProxy.onScreenUpdate)) + displayLink.add(to: .main, forMode: runLoopMode) + displayLink.isPaused = true + return displayLink + }() + + // MARK: - Override + override open var image: KFCrossPlatformImage? { + didSet { + if image != oldValue { + reset() + } + setNeedsDisplay() + layer.setNeedsDisplay() + } + } + + open override var isHighlighted: Bool { + get { + super.isHighlighted + } + set { + // Highlighted image is unsupported for animated images. + // See https://github.com/onevcat/Kingfisher/issues/1679 + if displayLink.isPaused { + super.isHighlighted = newValue + } + } + } + +// Workaround for Apple xcframework creating issue on Apple TV in Swift 5.8. +// https://github.com/apple/swift/issues/66015 +#if os(tvOS) + public override init(image: UIImage?, highlightedImage: UIImage?) { + super.init(image: image, highlightedImage: highlightedImage) + } + + required public init?(coder: NSCoder) { + super.init(coder: coder) + } + + init() { + super.init(frame: .zero) + } +#endif + + deinit { + if isDisplayLinkInitialized { + displayLink.invalidate() + } + } + + override open var isAnimating: Bool { + if isDisplayLinkInitialized { + return !displayLink.isPaused + } else { + return super.isAnimating + } + } + + /// Starts the animation. + override open func startAnimating() { + guard !isAnimating else { return } + guard let animator = animator else { return } + guard !animator.isReachMaxRepeatCount else { return } + + displayLink.isPaused = false + } + + /// Stops the animation. + override open func stopAnimating() { + super.stopAnimating() + if isDisplayLinkInitialized { + displayLink.isPaused = true + } + } + + override open func display(_ layer: CALayer) { + layer.contents = animator?.currentFrameImage?.cgImage ?? image?.cgImage + } + + override open func didMoveToWindow() { + super.didMoveToWindow() + didMove() + } + + override open func didMoveToSuperview() { + super.didMoveToSuperview() + didMove() + } + + // This is for back compatibility that using regular `UIImageView` to show animated image. + override func shouldPreloadAllAnimation() -> Bool { + return false + } + + // Reset the animator. + private func reset() { + animator = nil + if let image = image, let frameSource = image.kf.frameSource { + #if os(visionOS) + let targetSize = bounds.scaled(UITraitCollection.current.displayScale).size + #else + var scale: CGFloat = 0 + + if #available(iOS 13.0, tvOS 13.0, *) { + scale = UITraitCollection.current.displayScale + } else { + scale = UIScreen.main.scale + } + let targetSize = bounds.scaled(scale).size + #endif + let animator = Animator( + frameSource: frameSource, + contentMode: contentMode, + size: targetSize, + imageSize: image.kf.size, + imageScale: image.kf.scale, + framePreloadCount: framePreloadCount, + repeatCount: repeatCount, + preloadQueue: preloadQueue) + animator.delegate = self + animator.needsPrescaling = needsPrescaling + animator.backgroundDecode = backgroundDecode + animator.prepareFramesAsynchronously() + self.animator = animator + } + didMove() + } + + private func didMove() { + if autoPlayAnimatedImage && animator != nil { + if let _ = superview, let _ = window { + startAnimating() + } else { + stopAnimating() + } + } + } + + /// Update the current frame with the displayLink duration. + private func updateFrameIfNeeded() { + guard let animator = animator else { + return + } + + guard !animator.isFinished else { + stopAnimating() + delegate?.animatedImageViewDidFinishAnimating(self) + return + } + + let duration: CFTimeInterval + + // CA based display link is opt-out from ProMotion by default. + // So the duration and its FPS might not match. + // See [#718](https://github.com/onevcat/Kingfisher/issues/718) + // By setting CADisableMinimumFrameDuration to YES in Info.plist may + // cause the preferredFramesPerSecond being 0 + let preferredFramesPerSecond = displayLink.preferredFramesPerSecond + if preferredFramesPerSecond == 0 { + duration = displayLink.duration + } else { + // Some devices (like iPad Pro 10.5) will have a different FPS. + duration = 1.0 / TimeInterval(preferredFramesPerSecond) + } + + animator.shouldChangeFrame(with: duration) { [weak self] hasNewFrame in + if hasNewFrame { + self?.layer.setNeedsDisplay() + } + } + } +} + +protocol AnimatorDelegate: AnyObject { + func animator(_ animator: AnimatedImageView.Animator, didPlayAnimationLoops count: UInt) +} + +extension AnimatedImageView: AnimatorDelegate { + func animator(_ animator: Animator, didPlayAnimationLoops count: UInt) { + delegate?.animatedImageView(self, didPlayAnimationLoops: count) + } +} + +extension AnimatedImageView { + + // Represents a single frame in a GIF. + struct AnimatedFrame { + + // The image to display for this frame. Its value is nil when the frame is removed from the buffer. + let image: UIImage? + + // The duration that this frame should remain active. + let duration: TimeInterval + + // A placeholder frame with no image assigned. + // Used to replace frames that are no longer needed in the animation. + var placeholderFrame: AnimatedFrame { + return AnimatedFrame(image: nil, duration: duration) + } + + // Whether this frame instance contains an image or not. + var isPlaceholder: Bool { + return image == nil + } + + // Returns a new instance from an optional image. + // + // - parameter image: An optional `UIImage` instance to be assigned to the new frame. + // - returns: An `AnimatedFrame` instance. + func makeAnimatedFrame(image: UIImage?) -> AnimatedFrame { + return AnimatedFrame(image: image, duration: duration) + } + } +} + +extension AnimatedImageView { + + // MARK: - Animator + + /// An animator which used to drive the data behind `AnimatedImageView`. + public class Animator { + private let size: CGSize + + private let imageSize: CGSize + private let imageScale: CGFloat + + /// The maximum count of image frames that needs preload. + public let maxFrameCount: Int + + private let frameSource: ImageFrameSource + private let maxRepeatCount: RepeatCount + + private let maxTimeStep: TimeInterval = 1.0 + private let animatedFrames = SafeArray() + private var frameCount = 0 + private var timeSinceLastFrameChange: TimeInterval = 0.0 + private var currentRepeatCount: UInt = 0 + + var isFinished: Bool = false + + var needsPrescaling = true + + var backgroundDecode = true + + weak var delegate: AnimatorDelegate? + + // Total duration of one animation loop + var loopDuration: TimeInterval = 0 + + /// The image of the current frame. + public var currentFrameImage: UIImage? { + return frame(at: currentFrameIndex) + } + + /// The duration of the current active frame duration. + public var currentFrameDuration: TimeInterval { + return duration(at: currentFrameIndex) + } + + /// The index of the current animation frame. + public internal(set) var currentFrameIndex = 0 { + didSet { + previousFrameIndex = oldValue + } + } + + var previousFrameIndex = 0 { + didSet { + preloadQueue.async { + self.updatePreloadedFrames() + } + } + } + + var isReachMaxRepeatCount: Bool { + switch maxRepeatCount { + case .once: + return currentRepeatCount >= 1 + case .finite(let maxCount): + return currentRepeatCount >= maxCount + case .infinite: + return false + } + } + + /// Whether the current frame is the last frame or not in the animation sequence. + public var isLastFrame: Bool { + return currentFrameIndex == frameCount - 1 + } + + var preloadingIsNeeded: Bool { + return maxFrameCount < frameCount - 1 + } + + var contentMode = UIView.ContentMode.scaleToFill + + private lazy var preloadQueue: DispatchQueue = { + return DispatchQueue(label: "com.onevcat.Kingfisher.Animator.preloadQueue") + }() + + /// Creates an animator with image source reference. + /// + /// - Parameters: + /// - source: The reference of animated image. + /// - mode: Content mode of the `AnimatedImageView`. + /// - size: Size of the `AnimatedImageView`. + /// - imageSize: Size of the `KingfisherWrapper`. + /// - imageScale: Scale of the `KingfisherWrapper`. + /// - count: Count of frames needed to be preloaded. + /// - repeatCount: The repeat count should this animator uses. + /// - preloadQueue: Dispatch queue used for preloading images. + convenience init(imageSource source: CGImageSource, + contentMode mode: UIView.ContentMode, + size: CGSize, + imageSize: CGSize, + imageScale: CGFloat, + framePreloadCount count: Int, + repeatCount: RepeatCount, + preloadQueue: DispatchQueue) { + let frameSource = CGImageFrameSource(data: nil, imageSource: source, options: nil) + self.init(frameSource: frameSource, + contentMode: mode, + size: size, + imageSize: imageSize, + imageScale: imageScale, + framePreloadCount: count, + repeatCount: repeatCount, + preloadQueue: preloadQueue) + } + + /// Creates an animator with a custom image frame source. + /// + /// - Parameters: + /// - frameSource: The reference of animated image. + /// - mode: Content mode of the `AnimatedImageView`. + /// - size: Size of the `AnimatedImageView`. + /// - imageSize: Size of the `KingfisherWrapper`. + /// - imageScale: Scale of the `KingfisherWrapper`. + /// - count: Count of frames needed to be preloaded. + /// - repeatCount: The repeat count should this animator uses. + /// - preloadQueue: Dispatch queue used for preloading images. + init(frameSource source: ImageFrameSource, + contentMode mode: UIView.ContentMode, + size: CGSize, + imageSize: CGSize, + imageScale: CGFloat, + framePreloadCount count: Int, + repeatCount: RepeatCount, + preloadQueue: DispatchQueue) { + self.frameSource = source + self.contentMode = mode + self.size = size + self.imageSize = imageSize + self.imageScale = imageScale + self.maxFrameCount = count + self.maxRepeatCount = repeatCount + self.preloadQueue = preloadQueue + } + + deinit { + resetAnimatedFrames() + } + + /// Gets the image frame of a given index. + /// - Parameter index: The index of desired image. + /// - Returns: The decoded image at the frame. `nil` if the index is out of bound or the image is not yet loaded. + public func frame(at index: Int) -> KFCrossPlatformImage? { + return animatedFrames[index]?.image + } + + public func duration(at index: Int) -> TimeInterval { + return animatedFrames[index]?.duration ?? .infinity + } + + func prepareFramesAsynchronously() { + frameCount = frameSource.frameCount + animatedFrames.reserveCapacity(frameCount) + preloadQueue.async { [weak self] in + self?.setupAnimatedFrames() + } + } + + func shouldChangeFrame(with duration: CFTimeInterval, handler: (Bool) -> Void) { + incrementTimeSinceLastFrameChange(with: duration) + + if currentFrameDuration > timeSinceLastFrameChange { + handler(false) + } else { + resetTimeSinceLastFrameChange() + incrementCurrentFrameIndex() + handler(true) + } + } + + private func setupAnimatedFrames() { + resetAnimatedFrames() + + var duration: TimeInterval = 0 + + (0.. maxFrameCount { return } + animatedFrames[index] = animatedFrames[index]?.makeAnimatedFrame(image: loadFrame(at: index)) + } + + self.loopDuration = duration + } + + private func resetAnimatedFrames() { + animatedFrames.removeAll() + } + + private func loadFrame(at index: Int) -> UIImage? { + let resize = needsPrescaling && size != .zero + let maxSize = resize ? size : nil + guard let cgImage = frameSource.frame(at: index, maxSize: maxSize) else { + return nil + } + + if #available(iOS 15, tvOS 15, *) { + // From iOS 15, a plain image loading causes iOS calling `-[_UIImageCGImageContent initWithCGImage:scale:]` + // in ImageIO, which holds the image ref on the creating thread. + // To get a workaround, create another image ref and use that to create the final image. This leads to + // some performance loss, but there is little we can do. + // https://github.com/onevcat/Kingfisher/issues/1844 + // https://github.com/onevcat/Kingfisher/pulls/2194 + guard let unretainedImage = CGImage.create(ref: cgImage) else { + return KFCrossPlatformImage(cgImage: cgImage) + } + + return KFCrossPlatformImage(cgImage: unretainedImage) + } else { + let image = KFCrossPlatformImage(cgImage: cgImage) + if backgroundDecode { + guard let context = GraphicsContext.current(size: imageSize, scale: imageScale, inverting: true, cgImage: cgImage) else { + return image + } + return image.kf.decoded(on: context) + } else { + return image + } + } + } + + private func updatePreloadedFrames() { + guard preloadingIsNeeded else { + return + } + + let previousFrame = animatedFrames[previousFrameIndex] + animatedFrames[previousFrameIndex] = previousFrame?.placeholderFrame + // ensure the image dealloc in main thread + defer { + if let image = previousFrame?.image { + DispatchQueue.main.async { + _ = image + } + } + } + + preloadIndexes(start: currentFrameIndex).forEach { index in + guard let currentAnimatedFrame = animatedFrames[index] else { return } + if !currentAnimatedFrame.isPlaceholder { return } + animatedFrames[index] = currentAnimatedFrame.makeAnimatedFrame(image: loadFrame(at: index)) + } + } + + private func incrementCurrentFrameIndex() { + let wasLastFrame = isLastFrame + currentFrameIndex = increment(frameIndex: currentFrameIndex) + if isLastFrame { + currentRepeatCount += 1 + if isReachMaxRepeatCount { + isFinished = true + + // Notify the delegate here because the animation is stopping. + delegate?.animator(self, didPlayAnimationLoops: currentRepeatCount) + } + } else if wasLastFrame { + + // Notify the delegate that the loop completed + delegate?.animator(self, didPlayAnimationLoops: currentRepeatCount) + } + } + + private func incrementTimeSinceLastFrameChange(with duration: TimeInterval) { + timeSinceLastFrameChange += min(maxTimeStep, duration) + } + + private func resetTimeSinceLastFrameChange() { + timeSinceLastFrameChange -= currentFrameDuration + } + + private func increment(frameIndex: Int, by value: Int = 1) -> Int { + return (frameIndex + value) % frameCount + } + + private func preloadIndexes(start index: Int) -> [Int] { + let nextIndex = increment(frameIndex: index) + let lastIndex = increment(frameIndex: index, by: maxFrameCount) + + if lastIndex >= nextIndex { + return [Int](nextIndex...lastIndex) + } else { + return [Int](nextIndex.. { + private var array: Array = [] + private let lock = NSLock() + + subscript(index: Int) -> Element? { + get { + lock.lock() + defer { lock.unlock() } + return array.indices ~= index ? array[index] : nil + } + + set { + lock.lock() + defer { lock.unlock() } + if let newValue = newValue, array.indices ~= index { + array[index] = newValue + } + } + } + + var count : Int { + lock.lock() + defer { lock.unlock() } + return array.count + } + + func reserveCapacity(_ count: Int) { + lock.lock() + defer { lock.unlock() } + array.reserveCapacity(count) + } + + func append(_ element: Element) { + lock.lock() + defer { lock.unlock() } + array += [element] + } + + func removeAll() { + lock.lock() + defer { lock.unlock() } + array = [] + } +} +#endif +#endif + + diff --git a/Pods/Kingfisher/Sources/Views/Indicator.swift b/Pods/Kingfisher/Sources/Views/Indicator.swift new file mode 100644 index 0000000..f44721e --- /dev/null +++ b/Pods/Kingfisher/Sources/Views/Indicator.swift @@ -0,0 +1,233 @@ +// +// Indicator.swift +// Kingfisher +// +// Created by João D. Moreira on 30/08/16. +// +// Copyright (c) 2019 Wei Wang +// +// Permission is hereby granted, free of charge, to any person obtaining a copy +// of this software and associated documentation files (the "Software"), to deal +// in the Software without restriction, including without limitation the rights +// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +// copies of the Software, and to permit persons to whom the Software is +// furnished to do so, subject to the following conditions: +// +// The above copyright notice and this permission notice shall be included in +// all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN +// THE SOFTWARE. + +#if !os(watchOS) + +#if canImport(AppKit) && !targetEnvironment(macCatalyst) +import AppKit +public typealias IndicatorView = NSView +#else +import UIKit +public typealias IndicatorView = UIView +#endif + +/// Represents the activity indicator type which should be added to +/// an image view when an image is being downloaded. +/// +/// - none: No indicator. +/// - activity: Uses the system activity indicator. +/// - image: Uses an image as indicator. GIF is supported. +/// - custom: Uses a custom indicator. The type of associated value should conform to the `Indicator` protocol. +public enum IndicatorType { + /// No indicator. + case none + /// Uses the system activity indicator. + case activity + /// Uses an image as indicator. GIF is supported. + case image(imageData: Data) + /// Uses a custom indicator. The type of associated value should conform to the `Indicator` protocol. + case custom(indicator: Indicator) +} + +/// An indicator type which can be used to show the download task is in progress. +public protocol Indicator { + + /// Called when the indicator should start animating. + func startAnimatingView() + + /// Called when the indicator should stop animating. + func stopAnimatingView() + + /// Center offset of the indicator. Kingfisher will use this value to determine the position of + /// indicator in the super view. + var centerOffset: CGPoint { get } + + /// The indicator view which would be added to the super view. + var view: IndicatorView { get } + + /// The size strategy used when adding the indicator to image view. + /// - Parameter imageView: The super view of indicator. + func sizeStrategy(in imageView: KFCrossPlatformImageView) -> IndicatorSizeStrategy +} + +public enum IndicatorSizeStrategy { + case intrinsicSize + case full + case size(CGSize) +} + +extension Indicator { + + /// Default implementation of `centerOffset` of `Indicator`. The default value is `.zero`, means that there is + /// no offset for the indicator view. + public var centerOffset: CGPoint { return .zero } + + /// Default implementation of `centerOffset` of `Indicator`. The default value is `.full`, means that the indicator + /// will pin to the same height and width as the image view. + public func sizeStrategy(in imageView: KFCrossPlatformImageView) -> IndicatorSizeStrategy { + return .full + } +} + +// Displays a NSProgressIndicator / UIActivityIndicatorView +final class ActivityIndicator: Indicator { + + #if os(macOS) + private let activityIndicatorView: NSProgressIndicator + #else + private let activityIndicatorView: UIActivityIndicatorView + #endif + private var animatingCount = 0 + + var view: IndicatorView { + return activityIndicatorView + } + + func startAnimatingView() { + if animatingCount == 0 { + #if os(macOS) + activityIndicatorView.startAnimation(nil) + #else + activityIndicatorView.startAnimating() + #endif + activityIndicatorView.isHidden = false + } + animatingCount += 1 + } + + func stopAnimatingView() { + animatingCount = max(animatingCount - 1, 0) + if animatingCount == 0 { + #if os(macOS) + activityIndicatorView.stopAnimation(nil) + #else + activityIndicatorView.stopAnimating() + #endif + activityIndicatorView.isHidden = true + } + } + + func sizeStrategy(in imageView: KFCrossPlatformImageView) -> IndicatorSizeStrategy { + return .intrinsicSize + } + + init() { + #if os(macOS) + activityIndicatorView = NSProgressIndicator(frame: CGRect(x: 0, y: 0, width: 16, height: 16)) + activityIndicatorView.controlSize = .small + activityIndicatorView.style = .spinning + #else + let indicatorStyle: UIActivityIndicatorView.Style + + #if os(tvOS) + if #available(tvOS 13.0, *) { + indicatorStyle = UIActivityIndicatorView.Style.large + } else { + indicatorStyle = UIActivityIndicatorView.Style.white + } + #elseif os(visionOS) + indicatorStyle = UIActivityIndicatorView.Style.medium + #else + if #available(iOS 13.0, * ) { + indicatorStyle = UIActivityIndicatorView.Style.medium + } else { + indicatorStyle = UIActivityIndicatorView.Style.gray + } + #endif + + activityIndicatorView = UIActivityIndicatorView(style: indicatorStyle) + #endif + } +} + +#if canImport(UIKit) +extension UIActivityIndicatorView.Style { + #if compiler(>=5.1) + #else + static let large = UIActivityIndicatorView.Style.white + #if !os(tvOS) + static let medium = UIActivityIndicatorView.Style.gray + #endif + #endif +} +#endif + +// MARK: - ImageIndicator +// Displays an ImageView. Supports gif +final class ImageIndicator: Indicator { + private let animatedImageIndicatorView: KFCrossPlatformImageView + + var view: IndicatorView { + return animatedImageIndicatorView + } + + init?( + imageData data: Data, + processor: ImageProcessor = DefaultImageProcessor.default, + options: KingfisherParsedOptionsInfo? = nil) + { + var options = options ?? KingfisherParsedOptionsInfo(nil) + // Use normal image view to show animations, so we need to preload all animation data. + if !options.preloadAllAnimationData { + options.preloadAllAnimationData = true + } + + guard let image = processor.process(item: .data(data), options: options) else { + return nil + } + + animatedImageIndicatorView = KFCrossPlatformImageView() + animatedImageIndicatorView.image = image + + #if os(macOS) + // Need for gif to animate on macOS + animatedImageIndicatorView.imageScaling = .scaleNone + animatedImageIndicatorView.canDrawSubviewsIntoLayer = true + #else + animatedImageIndicatorView.contentMode = .center + #endif + } + + func startAnimatingView() { + #if os(macOS) + animatedImageIndicatorView.animates = true + #else + animatedImageIndicatorView.startAnimating() + #endif + animatedImageIndicatorView.isHidden = false + } + + func stopAnimatingView() { + #if os(macOS) + animatedImageIndicatorView.animates = false + #else + animatedImageIndicatorView.stopAnimating() + #endif + animatedImageIndicatorView.isHidden = true + } +} + +#endif diff --git a/Pods/MBProgressHUD/LICENSE b/Pods/MBProgressHUD/LICENSE new file mode 100644 index 0000000..d7f0647 --- /dev/null +++ b/Pods/MBProgressHUD/LICENSE @@ -0,0 +1,19 @@ +Copyright © 2009-2020 Matej Bukovinski + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in +all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN +THE SOFTWARE. \ No newline at end of file diff --git a/Pods/MBProgressHUD/MBProgressHUD.h b/Pods/MBProgressHUD/MBProgressHUD.h new file mode 100644 index 0000000..38b5004 --- /dev/null +++ b/Pods/MBProgressHUD/MBProgressHUD.h @@ -0,0 +1,411 @@ +// +// MBProgressHUD.h +// Version 1.2.0 +// Created by Matej Bukovinski on 2.4.09. +// + +// This code is distributed under the terms and conditions of the MIT license. + +// Copyright © 2009-2016 Matej Bukovinski +// +// 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 +#import +#import + +@class MBBackgroundView; +@protocol MBProgressHUDDelegate; + + +extern CGFloat const MBProgressMaxOffset; + +typedef NS_ENUM(NSInteger, MBProgressHUDMode) { + /// UIActivityIndicatorView. + MBProgressHUDModeIndeterminate, + /// A round, pie-chart like, progress view. + MBProgressHUDModeDeterminate, + /// Horizontal progress bar. + MBProgressHUDModeDeterminateHorizontalBar, + /// Ring-shaped progress view. + MBProgressHUDModeAnnularDeterminate, + /// Shows a custom view. + MBProgressHUDModeCustomView, + /// Shows only labels. + MBProgressHUDModeText +}; + +typedef NS_ENUM(NSInteger, MBProgressHUDAnimation) { + /// Opacity animation + MBProgressHUDAnimationFade, + /// Opacity + scale animation (zoom in when appearing zoom out when disappearing) + MBProgressHUDAnimationZoom, + /// Opacity + scale animation (zoom out style) + MBProgressHUDAnimationZoomOut, + /// Opacity + scale animation (zoom in style) + MBProgressHUDAnimationZoomIn +}; + +typedef NS_ENUM(NSInteger, MBProgressHUDBackgroundStyle) { + /// Solid color background + MBProgressHUDBackgroundStyleSolidColor, + /// UIVisualEffectView or UIToolbar.layer background view + MBProgressHUDBackgroundStyleBlur +}; + +typedef void (^MBProgressHUDCompletionBlock)(void); + + +NS_ASSUME_NONNULL_BEGIN + + +/** + * Displays a simple HUD window containing a progress indicator and two optional labels for short messages. + * + * This is a simple drop-in class for displaying a progress HUD view similar to Apple's private UIProgressHUD class. + * The MBProgressHUD window spans over the entire space given to it by the initWithFrame: constructor and catches all + * user input on this region, thereby preventing the user operations on components below the view. + * + * @note To still allow touches to pass through the HUD, you can set hud.userInteractionEnabled = NO. + * @attention MBProgressHUD is a UI class and should therefore only be accessed on the main thread. + */ +@interface MBProgressHUD : UIView + +/** + * Creates a new HUD, adds it to provided view and shows it. The counterpart to this method is hideHUDForView:animated:. + * + * @note This method sets removeFromSuperViewOnHide. The HUD will automatically be removed from the view hierarchy when hidden. + * + * @param view The view that the HUD will be added to + * @param animated If set to YES the HUD will appear using the current animationType. If set to NO the HUD will not use + * animations while appearing. + * @return A reference to the created HUD. + * + * @see hideHUDForView:animated: + * @see animationType + */ ++ (instancetype)showHUDAddedTo:(UIView *)view animated:(BOOL)animated; + +/// @name Showing and hiding + +/** + * Finds the top-most HUD subview that hasn't finished and hides it. The counterpart to this method is showHUDAddedTo:animated:. + * + * @note This method sets removeFromSuperViewOnHide. The HUD will automatically be removed from the view hierarchy when hidden. + * + * @param view The view that is going to be searched for a HUD subview. + * @param animated If set to YES the HUD will disappear using the current animationType. If set to NO the HUD will not use + * animations while disappearing. + * @return YES if a HUD was found and removed, NO otherwise. + * + * @see showHUDAddedTo:animated: + * @see animationType + */ ++ (BOOL)hideHUDForView:(UIView *)view animated:(BOOL)animated; + +/** + * Finds the top-most HUD subview that hasn't finished and returns it. + * + * @param view The view that is going to be searched. + * @return A reference to the last HUD subview discovered. + */ ++ (nullable MBProgressHUD *)HUDForView:(UIView *)view NS_SWIFT_NAME(forView(_:)); + +/** + * A convenience constructor that initializes the HUD with the view's bounds. Calls the designated constructor with + * view.bounds as the parameter. + * + * @param view The view instance that will provide the bounds for the HUD. Should be the same instance as + * the HUD's superview (i.e., the view that the HUD will be added to). + */ +- (instancetype)initWithView:(UIView *)view; + +/** + * Displays the HUD. + * + * @note You need to make sure that the main thread completes its run loop soon after this method call so that + * the user interface can be updated. Call this method when your task is already set up to be executed in a new thread + * (e.g., when using something like NSOperation or making an asynchronous call like NSURLRequest). + * + * @param animated If set to YES the HUD will appear using the current animationType. If set to NO the HUD will not use + * animations while appearing. + * + * @see animationType + */ +- (void)showAnimated:(BOOL)animated; + +/** + * Hides the HUD. This still calls the hudWasHidden: delegate. This is the counterpart of the show: method. Use it to + * hide the HUD when your task completes. + * + * @param animated If set to YES the HUD will disappear using the current animationType. If set to NO the HUD will not use + * animations while disappearing. + * + * @see animationType + */ +- (void)hideAnimated:(BOOL)animated; + +/** + * Hides the HUD after a delay. This still calls the hudWasHidden: delegate. This is the counterpart of the show: method. Use it to + * hide the HUD when your task completes. + * + * @param animated If set to YES the HUD will disappear using the current animationType. If set to NO the HUD will not use + * animations while disappearing. + * @param delay Delay in seconds until the HUD is hidden. + * + * @see animationType + */ +- (void)hideAnimated:(BOOL)animated afterDelay:(NSTimeInterval)delay; + +/** + * The HUD delegate object. Receives HUD state notifications. + */ +@property (weak, nonatomic) id delegate; + +/** + * Called after the HUD is hidden. + */ +@property (copy, nullable) MBProgressHUDCompletionBlock completionBlock; + +/** + * Grace period is the time (in seconds) that the invoked method may be run without + * showing the HUD. If the task finishes before the grace time runs out, the HUD will + * not be shown at all. + * This may be used to prevent HUD display for very short tasks. + * Defaults to 0 (no grace time). + * @note The graceTime needs to be set before the hud is shown. You thus can't use `showHUDAddedTo:animated:`, + * but instead need to alloc / init the HUD, configure the grace time and than show it manually. + */ +@property (assign, nonatomic) NSTimeInterval graceTime; + +/** + * The minimum time (in seconds) that the HUD is shown. + * This avoids the problem of the HUD being shown and than instantly hidden. + * Defaults to 0 (no minimum show time). + */ +@property (assign, nonatomic) NSTimeInterval minShowTime; + +/** + * Removes the HUD from its parent view when hidden. + * Defaults to NO. + */ +@property (assign, nonatomic) BOOL removeFromSuperViewOnHide; + +/// @name Appearance + +/** + * MBProgressHUD operation mode. The default is MBProgressHUDModeIndeterminate. + */ +@property (assign, nonatomic) MBProgressHUDMode mode; + +/** + * A color that gets forwarded to all labels and supported indicators. Also sets the tintColor + * for custom views on iOS 7+. Set to nil to manage color individually. + * Defaults to semi-translucent black on iOS 7 and later and white on earlier iOS versions. + */ +@property (strong, nonatomic, nullable) UIColor *contentColor UI_APPEARANCE_SELECTOR; + +/** + * The animation type that should be used when the HUD is shown and hidden. + */ +@property (assign, nonatomic) MBProgressHUDAnimation animationType UI_APPEARANCE_SELECTOR; + +/** + * The bezel offset relative to the center of the view. You can use MBProgressMaxOffset + * and -MBProgressMaxOffset to move the HUD all the way to the screen edge in each direction. + * E.g., CGPointMake(0.f, MBProgressMaxOffset) would position the HUD centered on the bottom edge. + */ +@property (assign, nonatomic) CGPoint offset UI_APPEARANCE_SELECTOR; + +/** + * The amount of space between the HUD edge and the HUD elements (labels, indicators or custom views). + * This also represents the minimum bezel distance to the edge of the HUD view. + * Defaults to 20.f + */ +@property (assign, nonatomic) CGFloat margin UI_APPEARANCE_SELECTOR; + +/** + * The minimum size of the HUD bezel. Defaults to CGSizeZero (no minimum size). + */ +@property (assign, nonatomic) CGSize minSize UI_APPEARANCE_SELECTOR; + +/** + * Force the HUD dimensions to be equal if possible. + */ +@property (assign, nonatomic, getter = isSquare) BOOL square UI_APPEARANCE_SELECTOR; + +/** + * When enabled, the bezel center gets slightly affected by the device accelerometer data. + * Defaults to NO. + * + * @note This can cause main thread checker assertions on certain devices. https://github.com/jdg/MBProgressHUD/issues/552 + */ +@property (assign, nonatomic, getter=areDefaultMotionEffectsEnabled) BOOL defaultMotionEffectsEnabled UI_APPEARANCE_SELECTOR; + +/// @name Progress + +/** + * The progress of the progress indicator, from 0.0 to 1.0. Defaults to 0.0. + */ +@property (assign, nonatomic) float progress; + +/// @name ProgressObject + +/** + * The NSProgress object feeding the progress information to the progress indicator. + */ +@property (strong, nonatomic, nullable) NSProgress *progressObject; + +/// @name Views + +/** + * The view containing the labels and indicator (or customView). + */ +@property (strong, nonatomic, readonly) MBBackgroundView *bezelView; + +/** + * View covering the entire HUD area, placed behind bezelView. + */ +@property (strong, nonatomic, readonly) MBBackgroundView *backgroundView; + +/** + * The UIView (e.g., a UIImageView) to be shown when the HUD is in MBProgressHUDModeCustomView. + * The view should implement intrinsicContentSize for proper sizing. For best results use approximately 37 by 37 pixels. + */ +@property (strong, nonatomic, nullable) UIView *customView; + +/** + * A label that holds an optional short message to be displayed below the activity indicator. The HUD is automatically resized to fit + * the entire text. + */ +@property (strong, nonatomic, readonly) UILabel *label; + +/** + * A label that holds an optional details message displayed below the labelText message. The details text can span multiple lines. + */ +@property (strong, nonatomic, readonly) UILabel *detailsLabel; + +/** + * A button that is placed below the labels. Visible only if a target / action is added and a title is assigned.. + */ +@property (strong, nonatomic, readonly) UIButton *button; + +@end + + +@protocol MBProgressHUDDelegate + +@optional + +/** + * Called after the HUD was fully hidden from the screen. + */ +- (void)hudWasHidden:(MBProgressHUD *)hud; + +@end + + +/** + * A progress view for showing definite progress by filling up a circle (pie chart). + */ +@interface MBRoundProgressView : UIView + +/** + * Progress (0.0 to 1.0) + */ +@property (nonatomic, assign) float progress; + +/** + * Indicator progress color. + * Defaults to white [UIColor whiteColor]. + */ +@property (nonatomic, strong) UIColor *progressTintColor; + +/** + * Indicator background (non-progress) color. + * Only applicable on iOS versions older than iOS 7. + * Defaults to translucent white (alpha 0.1). + */ +@property (nonatomic, strong) UIColor *backgroundTintColor; + +/* + * Display mode - NO = round or YES = annular. Defaults to round. + */ +@property (nonatomic, assign, getter = isAnnular) BOOL annular; + +@end + + +/** + * A flat bar progress view. + */ +@interface MBBarProgressView : UIView + +/** + * Progress (0.0 to 1.0) + */ +@property (nonatomic, assign) float progress; + +/** + * Bar border line color. + * Defaults to white [UIColor whiteColor]. + */ +@property (nonatomic, strong) UIColor *lineColor; + +/** + * Bar background color. + * Defaults to clear [UIColor clearColor]; + */ +@property (nonatomic, strong) UIColor *progressRemainingColor; + +/** + * Bar progress color. + * Defaults to white [UIColor whiteColor]. + */ +@property (nonatomic, strong) UIColor *progressColor; + +@end + + +@interface MBBackgroundView : UIView + +/** + * The background style. + * Defaults to MBProgressHUDBackgroundStyleBlur. + */ +@property (nonatomic) MBProgressHUDBackgroundStyle style; + +/** + * The blur effect style, when using MBProgressHUDBackgroundStyleBlur. + * Defaults to UIBlurEffectStyleLight. + */ +@property (nonatomic) UIBlurEffectStyle blurEffectStyle; + +/** + * The background color or the blur tint color. + * + * Defaults to nil on iOS 13 and later and + * `[UIColor colorWithWhite:0.8f alpha:0.6f]` + * on older systems. + */ +@property (nonatomic, strong, nullable) UIColor *color; + +@end + +NS_ASSUME_NONNULL_END diff --git a/Pods/MBProgressHUD/MBProgressHUD.m b/Pods/MBProgressHUD/MBProgressHUD.m new file mode 100644 index 0000000..a2829a3 --- /dev/null +++ b/Pods/MBProgressHUD/MBProgressHUD.m @@ -0,0 +1,1194 @@ +// +// MBProgressHUD.m +// Version 1.2.0 +// Created by Matej Bukovinski on 2.4.09. +// + +#import "MBProgressHUD.h" +#import + +#define MBMainThreadAssert() NSAssert([NSThread isMainThread], @"MBProgressHUD needs to be accessed on the main thread."); + +CGFloat const MBProgressMaxOffset = 1000000.f; + +static const CGFloat MBDefaultPadding = 4.f; +static const CGFloat MBDefaultLabelFontSize = 16.f; +static const CGFloat MBDefaultDetailsLabelFontSize = 12.f; + + +@interface MBProgressHUD () + +@property (nonatomic, assign) BOOL useAnimation; +@property (nonatomic, assign, getter=hasFinished) BOOL finished; +@property (nonatomic, strong) UIView *indicator; +@property (nonatomic, strong) NSDate *showStarted; +@property (nonatomic, strong) NSArray *paddingConstraints; +@property (nonatomic, strong) NSArray *bezelConstraints; +@property (nonatomic, strong) UIView *topSpacer; +@property (nonatomic, strong) UIView *bottomSpacer; +@property (nonatomic, strong) UIMotionEffectGroup *bezelMotionEffects; +@property (nonatomic, weak) NSTimer *graceTimer; +@property (nonatomic, weak) NSTimer *minShowTimer; +@property (nonatomic, weak) NSTimer *hideDelayTimer; +@property (nonatomic, weak) CADisplayLink *progressObjectDisplayLink; + +@end + + +@interface MBProgressHUDRoundedButton : UIButton +@end + + +@implementation MBProgressHUD + +#pragma mark - Class methods + ++ (instancetype)showHUDAddedTo:(UIView *)view animated:(BOOL)animated { + MBProgressHUD *hud = [[self alloc] initWithView:view]; + hud.removeFromSuperViewOnHide = YES; + [view addSubview:hud]; + [hud showAnimated:animated]; + return hud; +} + ++ (BOOL)hideHUDForView:(UIView *)view animated:(BOOL)animated { + MBProgressHUD *hud = [self HUDForView:view]; + if (hud != nil) { + hud.removeFromSuperViewOnHide = YES; + [hud hideAnimated:animated]; + return YES; + } + return NO; +} + ++ (MBProgressHUD *)HUDForView:(UIView *)view { + NSEnumerator *subviewsEnum = [view.subviews reverseObjectEnumerator]; + for (UIView *subview in subviewsEnum) { + if ([subview isKindOfClass:self]) { + MBProgressHUD *hud = (MBProgressHUD *)subview; + if (hud.hasFinished == NO) { + return hud; + } + } + } + return nil; +} + +#pragma mark - Lifecycle + +- (void)commonInit { + // Set default values for properties + _animationType = MBProgressHUDAnimationFade; + _mode = MBProgressHUDModeIndeterminate; + _margin = 20.0f; + _defaultMotionEffectsEnabled = NO; + + if (@available(iOS 13.0, tvOS 13, *)) { + _contentColor = [[UIColor labelColor] colorWithAlphaComponent:0.7f]; + } else { + _contentColor = [UIColor colorWithWhite:0.f alpha:0.7f]; + } + + // Transparent background + self.opaque = NO; + self.backgroundColor = [UIColor clearColor]; + // Make it invisible for now + self.alpha = 0.0f; + self.autoresizingMask = UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleHeight; + self.layer.allowsGroupOpacity = NO; + + [self setupViews]; + [self updateIndicators]; + [self registerForNotifications]; +} + +- (instancetype)initWithFrame:(CGRect)frame { + if ((self = [super initWithFrame:frame])) { + [self commonInit]; + } + return self; +} + +- (instancetype)initWithCoder:(NSCoder *)aDecoder { + if ((self = [super initWithCoder:aDecoder])) { + [self commonInit]; + } + return self; +} + +- (id)initWithView:(UIView *)view { + NSAssert(view, @"View must not be nil."); + return [self initWithFrame:view.bounds]; +} + +- (void)dealloc { + [self unregisterFromNotifications]; +} + +#pragma mark - Show & hide + +- (void)showAnimated:(BOOL)animated { + MBMainThreadAssert(); + [self.minShowTimer invalidate]; + self.useAnimation = animated; + self.finished = NO; + // If the grace time is set, postpone the HUD display + if (self.graceTime > 0.0) { + NSTimer *timer = [NSTimer timerWithTimeInterval:self.graceTime target:self selector:@selector(handleGraceTimer:) userInfo:nil repeats:NO]; + [[NSRunLoop currentRunLoop] addTimer:timer forMode:NSRunLoopCommonModes]; + self.graceTimer = timer; + } + // ... otherwise show the HUD immediately + else { + [self showUsingAnimation:self.useAnimation]; + } +} + +- (void)hideAnimated:(BOOL)animated { + MBMainThreadAssert(); + [self.graceTimer invalidate]; + self.useAnimation = animated; + self.finished = YES; + // If the minShow time is set, calculate how long the HUD was shown, + // and postpone the hiding operation if necessary + if (self.minShowTime > 0.0 && self.showStarted) { + NSTimeInterval interv = [[NSDate date] timeIntervalSinceDate:self.showStarted]; + if (interv < self.minShowTime) { + NSTimer *timer = [NSTimer timerWithTimeInterval:(self.minShowTime - interv) target:self selector:@selector(handleMinShowTimer:) userInfo:nil repeats:NO]; + [[NSRunLoop currentRunLoop] addTimer:timer forMode:NSRunLoopCommonModes]; + self.minShowTimer = timer; + return; + } + } + // ... otherwise hide the HUD immediately + [self hideUsingAnimation:self.useAnimation]; +} + +- (void)hideAnimated:(BOOL)animated afterDelay:(NSTimeInterval)delay { + // Cancel any scheduled hideAnimated:afterDelay: calls + [self.hideDelayTimer invalidate]; + + NSTimer *timer = [NSTimer timerWithTimeInterval:delay target:self selector:@selector(handleHideTimer:) userInfo:@(animated) repeats:NO]; + [[NSRunLoop currentRunLoop] addTimer:timer forMode:NSRunLoopCommonModes]; + self.hideDelayTimer = timer; +} + +#pragma mark - Timer callbacks + +- (void)handleGraceTimer:(NSTimer *)theTimer { + // Show the HUD only if the task is still running + if (!self.hasFinished) { + [self showUsingAnimation:self.useAnimation]; + } +} + +- (void)handleMinShowTimer:(NSTimer *)theTimer { + [self hideUsingAnimation:self.useAnimation]; +} + +- (void)handleHideTimer:(NSTimer *)timer { + [self hideAnimated:[timer.userInfo boolValue]]; +} + +#pragma mark - View Hierrarchy + +- (void)didMoveToSuperview { + [self updateForCurrentOrientationAnimated:NO]; +} + +#pragma mark - Internal show & hide operations + +- (void)showUsingAnimation:(BOOL)animated { + // Cancel any previous animations + [self.bezelView.layer removeAllAnimations]; + [self.backgroundView.layer removeAllAnimations]; + + // Cancel any scheduled hideAnimated:afterDelay: calls + [self.hideDelayTimer invalidate]; + + self.showStarted = [NSDate date]; + self.alpha = 1.f; + + // Needed in case we hide and re-show with the same NSProgress object attached. + [self setNSProgressDisplayLinkEnabled:YES]; + + // Set up motion effects only at this point to avoid needlessly + // creating the effect if it was disabled after initialization. + [self updateBezelMotionEffects]; + + if (animated) { + [self animateIn:YES withType:self.animationType completion:NULL]; + } else { + self.bezelView.alpha = 1.f; + self.backgroundView.alpha = 1.f; + } +} + +- (void)hideUsingAnimation:(BOOL)animated { + // Cancel any scheduled hideAnimated:afterDelay: calls. + // This needs to happen here instead of in done, + // to avoid races if another hideAnimated:afterDelay: + // call comes in while the HUD is animating out. + [self.hideDelayTimer invalidate]; + + if (animated && self.showStarted) { + self.showStarted = nil; + [self animateIn:NO withType:self.animationType completion:^(BOOL finished) { + [self done]; + }]; + } else { + self.showStarted = nil; + self.bezelView.alpha = 0.f; + self.backgroundView.alpha = 1.f; + [self done]; + } +} + +- (void)animateIn:(BOOL)animatingIn withType:(MBProgressHUDAnimation)type completion:(void(^)(BOOL finished))completion { + // Automatically determine the correct zoom animation type + if (type == MBProgressHUDAnimationZoom) { + type = animatingIn ? MBProgressHUDAnimationZoomIn : MBProgressHUDAnimationZoomOut; + } + + CGAffineTransform small = CGAffineTransformMakeScale(0.5f, 0.5f); + CGAffineTransform large = CGAffineTransformMakeScale(1.5f, 1.5f); + + // Set starting state + UIView *bezelView = self.bezelView; + if (animatingIn && bezelView.alpha == 0.f && type == MBProgressHUDAnimationZoomIn) { + bezelView.transform = small; + } else if (animatingIn && bezelView.alpha == 0.f && type == MBProgressHUDAnimationZoomOut) { + bezelView.transform = large; + } + + // Perform animations + dispatch_block_t animations = ^{ + if (animatingIn) { + bezelView.transform = CGAffineTransformIdentity; + } else if (!animatingIn && type == MBProgressHUDAnimationZoomIn) { + bezelView.transform = large; + } else if (!animatingIn && type == MBProgressHUDAnimationZoomOut) { + bezelView.transform = small; + } + CGFloat alpha = animatingIn ? 1.f : 0.f; + bezelView.alpha = alpha; + self.backgroundView.alpha = alpha; + }; + [UIView animateWithDuration:0.3 delay:0. usingSpringWithDamping:1.f initialSpringVelocity:0.f options:UIViewAnimationOptionBeginFromCurrentState animations:animations completion:completion]; +} + +- (void)done { + [self setNSProgressDisplayLinkEnabled:NO]; + + if (self.hasFinished) { + self.alpha = 0.0f; + if (self.removeFromSuperViewOnHide) { + [self removeFromSuperview]; + } + } + MBProgressHUDCompletionBlock completionBlock = self.completionBlock; + if (completionBlock) { + completionBlock(); + } + id delegate = self.delegate; + if ([delegate respondsToSelector:@selector(hudWasHidden:)]) { + [delegate performSelector:@selector(hudWasHidden:) withObject:self]; + } +} + +#pragma mark - UI + +- (void)setupViews { + UIColor *defaultColor = self.contentColor; + + MBBackgroundView *backgroundView = [[MBBackgroundView alloc] initWithFrame:self.bounds]; + backgroundView.style = MBProgressHUDBackgroundStyleSolidColor; + backgroundView.backgroundColor = [UIColor clearColor]; + backgroundView.autoresizingMask = UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleHeight; + backgroundView.alpha = 0.f; + [self addSubview:backgroundView]; + _backgroundView = backgroundView; + + MBBackgroundView *bezelView = [MBBackgroundView new]; + bezelView.translatesAutoresizingMaskIntoConstraints = NO; + bezelView.layer.cornerRadius = 5.f; + bezelView.alpha = 0.f; + [self addSubview:bezelView]; + _bezelView = bezelView; + + UILabel *label = [UILabel new]; + label.adjustsFontSizeToFitWidth = NO; + label.textAlignment = NSTextAlignmentCenter; + label.textColor = defaultColor; + label.font = [UIFont boldSystemFontOfSize:MBDefaultLabelFontSize]; + label.opaque = NO; + label.backgroundColor = [UIColor clearColor]; + _label = label; + + UILabel *detailsLabel = [UILabel new]; + detailsLabel.adjustsFontSizeToFitWidth = NO; + detailsLabel.textAlignment = NSTextAlignmentCenter; + detailsLabel.textColor = defaultColor; + detailsLabel.numberOfLines = 0; + detailsLabel.font = [UIFont boldSystemFontOfSize:MBDefaultDetailsLabelFontSize]; + detailsLabel.opaque = NO; + detailsLabel.backgroundColor = [UIColor clearColor]; + _detailsLabel = detailsLabel; + + UIButton *button = [MBProgressHUDRoundedButton buttonWithType:UIButtonTypeCustom]; + button.titleLabel.textAlignment = NSTextAlignmentCenter; + button.titleLabel.font = [UIFont boldSystemFontOfSize:MBDefaultDetailsLabelFontSize]; + [button setTitleColor:defaultColor forState:UIControlStateNormal]; + _button = button; + + for (UIView *view in @[label, detailsLabel, button]) { + view.translatesAutoresizingMaskIntoConstraints = NO; + [view setContentCompressionResistancePriority:998.f forAxis:UILayoutConstraintAxisHorizontal]; + [view setContentCompressionResistancePriority:998.f forAxis:UILayoutConstraintAxisVertical]; + [bezelView addSubview:view]; + } + + UIView *topSpacer = [UIView new]; + topSpacer.translatesAutoresizingMaskIntoConstraints = NO; + topSpacer.hidden = YES; + [bezelView addSubview:topSpacer]; + _topSpacer = topSpacer; + + UIView *bottomSpacer = [UIView new]; + bottomSpacer.translatesAutoresizingMaskIntoConstraints = NO; + bottomSpacer.hidden = YES; + [bezelView addSubview:bottomSpacer]; + _bottomSpacer = bottomSpacer; +} + +- (void)updateIndicators { + UIView *indicator = self.indicator; + BOOL isActivityIndicator = [indicator isKindOfClass:[UIActivityIndicatorView class]]; + BOOL isRoundIndicator = [indicator isKindOfClass:[MBRoundProgressView class]]; + + MBProgressHUDMode mode = self.mode; + if (mode == MBProgressHUDModeIndeterminate) { + if (!isActivityIndicator) { + // Update to indeterminate indicator + UIActivityIndicatorView *activityIndicator; + [indicator removeFromSuperview]; +#if !TARGET_OS_MACCATALYST + if (@available(iOS 13.0, tvOS 13.0, *)) { +#endif + activityIndicator = [[UIActivityIndicatorView alloc] initWithActivityIndicatorStyle:UIActivityIndicatorViewStyleLarge]; + activityIndicator.color = [UIColor whiteColor]; +#if !TARGET_OS_MACCATALYST + } else { + activityIndicator = [[UIActivityIndicatorView alloc] initWithActivityIndicatorStyle:UIActivityIndicatorViewStyleWhiteLarge]; + } +#endif + [activityIndicator startAnimating]; + indicator = activityIndicator; + [self.bezelView addSubview:indicator]; + } + } + else if (mode == MBProgressHUDModeDeterminateHorizontalBar) { + // Update to bar determinate indicator + [indicator removeFromSuperview]; + indicator = [[MBBarProgressView alloc] init]; + [self.bezelView addSubview:indicator]; + } + else if (mode == MBProgressHUDModeDeterminate || mode == MBProgressHUDModeAnnularDeterminate) { + if (!isRoundIndicator) { + // Update to determinante indicator + [indicator removeFromSuperview]; + indicator = [[MBRoundProgressView alloc] init]; + [self.bezelView addSubview:indicator]; + } + if (mode == MBProgressHUDModeAnnularDeterminate) { + [(MBRoundProgressView *)indicator setAnnular:YES]; + } + } + else if (mode == MBProgressHUDModeCustomView && self.customView != indicator) { + // Update custom view indicator + [indicator removeFromSuperview]; + indicator = self.customView; + [self.bezelView addSubview:indicator]; + } + else if (mode == MBProgressHUDModeText) { + [indicator removeFromSuperview]; + indicator = nil; + } + indicator.translatesAutoresizingMaskIntoConstraints = NO; + self.indicator = indicator; + + if ([indicator respondsToSelector:@selector(setProgress:)]) { + [(id)indicator setValue:@(self.progress) forKey:@"progress"]; + } + + [indicator setContentCompressionResistancePriority:998.f forAxis:UILayoutConstraintAxisHorizontal]; + [indicator setContentCompressionResistancePriority:998.f forAxis:UILayoutConstraintAxisVertical]; + + [self updateViewsForColor:self.contentColor]; + [self setNeedsUpdateConstraints]; +} + +- (void)updateViewsForColor:(UIColor *)color { + if (!color) return; + + self.label.textColor = color; + self.detailsLabel.textColor = color; + [self.button setTitleColor:color forState:UIControlStateNormal]; + + // UIAppearance settings are prioritized. If they are preset the set color is ignored. + + UIView *indicator = self.indicator; + if ([indicator isKindOfClass:[UIActivityIndicatorView class]]) { + UIActivityIndicatorView *appearance = nil; +#if __IPHONE_OS_VERSION_MIN_REQUIRED < 90000 + appearance = [UIActivityIndicatorView appearanceWhenContainedIn:[MBProgressHUD class], nil]; +#else + // For iOS 9+ + appearance = [UIActivityIndicatorView appearanceWhenContainedInInstancesOfClasses:@[[MBProgressHUD class]]]; +#endif + + if (appearance.color == nil) { + ((UIActivityIndicatorView *)indicator).color = color; + } + } else if ([indicator isKindOfClass:[MBRoundProgressView class]]) { + MBRoundProgressView *appearance = nil; +#if __IPHONE_OS_VERSION_MIN_REQUIRED < 90000 + appearance = [MBRoundProgressView appearanceWhenContainedIn:[MBProgressHUD class], nil]; +#else + appearance = [MBRoundProgressView appearanceWhenContainedInInstancesOfClasses:@[[MBProgressHUD class]]]; +#endif + if (appearance.progressTintColor == nil) { + ((MBRoundProgressView *)indicator).progressTintColor = color; + } + if (appearance.backgroundTintColor == nil) { + ((MBRoundProgressView *)indicator).backgroundTintColor = [color colorWithAlphaComponent:0.1]; + } + } else if ([indicator isKindOfClass:[MBBarProgressView class]]) { + MBBarProgressView *appearance = nil; +#if __IPHONE_OS_VERSION_MIN_REQUIRED < 90000 + appearance = [MBBarProgressView appearanceWhenContainedIn:[MBProgressHUD class], nil]; +#else + appearance = [MBBarProgressView appearanceWhenContainedInInstancesOfClasses:@[[MBProgressHUD class]]]; +#endif + if (appearance.progressColor == nil) { + ((MBBarProgressView *)indicator).progressColor = color; + } + if (appearance.lineColor == nil) { + ((MBBarProgressView *)indicator).lineColor = color; + } + } else { + [indicator setTintColor:color]; + } +} + +- (void)updateBezelMotionEffects { + MBBackgroundView *bezelView = self.bezelView; + UIMotionEffectGroup *bezelMotionEffects = self.bezelMotionEffects; + + if (self.defaultMotionEffectsEnabled && !bezelMotionEffects) { + CGFloat effectOffset = 10.f; + UIInterpolatingMotionEffect *effectX = [[UIInterpolatingMotionEffect alloc] initWithKeyPath:@"center.x" type:UIInterpolatingMotionEffectTypeTiltAlongHorizontalAxis]; + effectX.maximumRelativeValue = @(effectOffset); + effectX.minimumRelativeValue = @(-effectOffset); + + UIInterpolatingMotionEffect *effectY = [[UIInterpolatingMotionEffect alloc] initWithKeyPath:@"center.y" type:UIInterpolatingMotionEffectTypeTiltAlongVerticalAxis]; + effectY.maximumRelativeValue = @(effectOffset); + effectY.minimumRelativeValue = @(-effectOffset); + + UIMotionEffectGroup *group = [[UIMotionEffectGroup alloc] init]; + group.motionEffects = @[effectX, effectY]; + + self.bezelMotionEffects = group; + [bezelView addMotionEffect:group]; + } else if (bezelMotionEffects) { + self.bezelMotionEffects = nil; + [bezelView removeMotionEffect:bezelMotionEffects]; + } +} + +#pragma mark - Layout + +- (void)updateConstraints { + UIView *bezel = self.bezelView; + UIView *topSpacer = self.topSpacer; + UIView *bottomSpacer = self.bottomSpacer; + CGFloat margin = self.margin; + NSMutableArray *bezelConstraints = [NSMutableArray array]; + NSDictionary *metrics = @{@"margin": @(margin)}; + + NSMutableArray *subviews = [NSMutableArray arrayWithObjects:self.topSpacer, self.label, self.detailsLabel, self.button, self.bottomSpacer, nil]; + if (self.indicator) [subviews insertObject:self.indicator atIndex:1]; + + // Remove existing constraints + [self removeConstraints:self.constraints]; + [topSpacer removeConstraints:topSpacer.constraints]; + [bottomSpacer removeConstraints:bottomSpacer.constraints]; + if (self.bezelConstraints) { + [bezel removeConstraints:self.bezelConstraints]; + self.bezelConstraints = nil; + } + + // Center bezel in container (self), applying the offset if set + CGPoint offset = self.offset; + NSMutableArray *centeringConstraints = [NSMutableArray array]; + [centeringConstraints addObject:[NSLayoutConstraint constraintWithItem:bezel attribute:NSLayoutAttributeCenterX relatedBy:NSLayoutRelationEqual toItem:self attribute:NSLayoutAttributeCenterX multiplier:1.f constant:offset.x]]; + [centeringConstraints addObject:[NSLayoutConstraint constraintWithItem:bezel attribute:NSLayoutAttributeCenterY relatedBy:NSLayoutRelationEqual toItem:self attribute:NSLayoutAttributeCenterY multiplier:1.f constant:offset.y]]; + [self applyPriority:998.f toConstraints:centeringConstraints]; + [self addConstraints:centeringConstraints]; + + // Ensure minimum side margin is kept + NSMutableArray *sideConstraints = [NSMutableArray array]; + [sideConstraints addObjectsFromArray:[NSLayoutConstraint constraintsWithVisualFormat:@"|-(>=margin)-[bezel]-(>=margin)-|" options:0 metrics:metrics views:NSDictionaryOfVariableBindings(bezel)]]; + [sideConstraints addObjectsFromArray:[NSLayoutConstraint constraintsWithVisualFormat:@"V:|-(>=margin)-[bezel]-(>=margin)-|" options:0 metrics:metrics views:NSDictionaryOfVariableBindings(bezel)]]; + [self applyPriority:999.f toConstraints:sideConstraints]; + [self addConstraints:sideConstraints]; + + // Minimum bezel size, if set + CGSize minimumSize = self.minSize; + if (!CGSizeEqualToSize(minimumSize, CGSizeZero)) { + NSMutableArray *minSizeConstraints = [NSMutableArray array]; + [minSizeConstraints addObject:[NSLayoutConstraint constraintWithItem:bezel attribute:NSLayoutAttributeWidth relatedBy:NSLayoutRelationGreaterThanOrEqual toItem:nil attribute:NSLayoutAttributeNotAnAttribute multiplier:1.f constant:minimumSize.width]]; + [minSizeConstraints addObject:[NSLayoutConstraint constraintWithItem:bezel attribute:NSLayoutAttributeHeight relatedBy:NSLayoutRelationGreaterThanOrEqual toItem:nil attribute:NSLayoutAttributeNotAnAttribute multiplier:1.f constant:minimumSize.height]]; + [self applyPriority:997.f toConstraints:minSizeConstraints]; + [bezelConstraints addObjectsFromArray:minSizeConstraints]; + } + + // Square aspect ratio, if set + if (self.square) { + NSLayoutConstraint *square = [NSLayoutConstraint constraintWithItem:bezel attribute:NSLayoutAttributeHeight relatedBy:NSLayoutRelationEqual toItem:bezel attribute:NSLayoutAttributeWidth multiplier:1.f constant:0]; + square.priority = 997.f; + [bezelConstraints addObject:square]; + } + + // Top and bottom spacing + [topSpacer addConstraint:[NSLayoutConstraint constraintWithItem:topSpacer attribute:NSLayoutAttributeHeight relatedBy:NSLayoutRelationGreaterThanOrEqual toItem:nil attribute:NSLayoutAttributeNotAnAttribute multiplier:1.f constant:margin]]; + [bottomSpacer addConstraint:[NSLayoutConstraint constraintWithItem:bottomSpacer attribute:NSLayoutAttributeHeight relatedBy:NSLayoutRelationGreaterThanOrEqual toItem:nil attribute:NSLayoutAttributeNotAnAttribute multiplier:1.f constant:margin]]; + // Top and bottom spaces should be equal + [bezelConstraints addObject:[NSLayoutConstraint constraintWithItem:topSpacer attribute:NSLayoutAttributeHeight relatedBy:NSLayoutRelationEqual toItem:bottomSpacer attribute:NSLayoutAttributeHeight multiplier:1.f constant:0.f]]; + + // Layout subviews in bezel + NSMutableArray *paddingConstraints = [NSMutableArray new]; + [subviews enumerateObjectsUsingBlock:^(UIView *view, NSUInteger idx, BOOL *stop) { + // Center in bezel + [bezelConstraints addObject:[NSLayoutConstraint constraintWithItem:view attribute:NSLayoutAttributeCenterX relatedBy:NSLayoutRelationEqual toItem:bezel attribute:NSLayoutAttributeCenterX multiplier:1.f constant:0.f]]; + // Ensure the minimum edge margin is kept + [bezelConstraints addObjectsFromArray:[NSLayoutConstraint constraintsWithVisualFormat:@"|-(>=margin)-[view]-(>=margin)-|" options:0 metrics:metrics views:NSDictionaryOfVariableBindings(view)]]; + // Element spacing + if (idx == 0) { + // First, ensure spacing to bezel edge + [bezelConstraints addObject:[NSLayoutConstraint constraintWithItem:view attribute:NSLayoutAttributeTop relatedBy:NSLayoutRelationEqual toItem:bezel attribute:NSLayoutAttributeTop multiplier:1.f constant:0.f]]; + } else if (idx == subviews.count - 1) { + // Last, ensure spacing to bezel edge + [bezelConstraints addObject:[NSLayoutConstraint constraintWithItem:view attribute:NSLayoutAttributeBottom relatedBy:NSLayoutRelationEqual toItem:bezel attribute:NSLayoutAttributeBottom multiplier:1.f constant:0.f]]; + } + if (idx > 0) { + // Has previous + NSLayoutConstraint *padding = [NSLayoutConstraint constraintWithItem:view attribute:NSLayoutAttributeTop relatedBy:NSLayoutRelationEqual toItem:subviews[idx - 1] attribute:NSLayoutAttributeBottom multiplier:1.f constant:0.f]; + [bezelConstraints addObject:padding]; + [paddingConstraints addObject:padding]; + } + }]; + + [bezel addConstraints:bezelConstraints]; + self.bezelConstraints = bezelConstraints; + + self.paddingConstraints = [paddingConstraints copy]; + [self updatePaddingConstraints]; + + [super updateConstraints]; +} + +- (void)layoutSubviews { + // There is no need to update constraints if they are going to + // be recreated in [super layoutSubviews] due to needsUpdateConstraints being set. + // This also avoids an issue on iOS 8, where updatePaddingConstraints + // would trigger a zombie object access. + if (!self.needsUpdateConstraints) { + [self updatePaddingConstraints]; + } + [super layoutSubviews]; +} + +- (void)updatePaddingConstraints { + // Set padding dynamically, depending on whether the view is visible or not + __block BOOL hasVisibleAncestors = NO; + [self.paddingConstraints enumerateObjectsUsingBlock:^(NSLayoutConstraint *padding, NSUInteger idx, BOOL *stop) { + UIView *firstView = (UIView *)padding.firstItem; + UIView *secondView = (UIView *)padding.secondItem; + BOOL firstVisible = !firstView.hidden && !CGSizeEqualToSize(firstView.intrinsicContentSize, CGSizeZero); + BOOL secondVisible = !secondView.hidden && !CGSizeEqualToSize(secondView.intrinsicContentSize, CGSizeZero); + // Set if both views are visible or if there's a visible view on top that doesn't have padding + // added relative to the current view yet + padding.constant = (firstVisible && (secondVisible || hasVisibleAncestors)) ? MBDefaultPadding : 0.f; + hasVisibleAncestors |= secondVisible; + }]; +} + +- (void)applyPriority:(UILayoutPriority)priority toConstraints:(NSArray *)constraints { + for (NSLayoutConstraint *constraint in constraints) { + constraint.priority = priority; + } +} + +#pragma mark - Properties + +- (void)setMode:(MBProgressHUDMode)mode { + if (mode != _mode) { + _mode = mode; + [self updateIndicators]; + } +} + +- (void)setCustomView:(UIView *)customView { + if (customView != _customView) { + _customView = customView; + if (self.mode == MBProgressHUDModeCustomView) { + [self updateIndicators]; + } + } +} + +- (void)setOffset:(CGPoint)offset { + if (!CGPointEqualToPoint(offset, _offset)) { + _offset = offset; + [self setNeedsUpdateConstraints]; + } +} + +- (void)setMargin:(CGFloat)margin { + if (margin != _margin) { + _margin = margin; + [self setNeedsUpdateConstraints]; + } +} + +- (void)setMinSize:(CGSize)minSize { + if (!CGSizeEqualToSize(minSize, _minSize)) { + _minSize = minSize; + [self setNeedsUpdateConstraints]; + } +} + +- (void)setSquare:(BOOL)square { + if (square != _square) { + _square = square; + [self setNeedsUpdateConstraints]; + } +} + +- (void)setProgressObjectDisplayLink:(CADisplayLink *)progressObjectDisplayLink { + if (progressObjectDisplayLink != _progressObjectDisplayLink) { + [_progressObjectDisplayLink invalidate]; + + _progressObjectDisplayLink = progressObjectDisplayLink; + + [_progressObjectDisplayLink addToRunLoop:[NSRunLoop mainRunLoop] forMode:NSDefaultRunLoopMode]; + } +} + +- (void)setProgressObject:(NSProgress *)progressObject { + if (progressObject != _progressObject) { + _progressObject = progressObject; + [self setNSProgressDisplayLinkEnabled:YES]; + } +} + +- (void)setProgress:(float)progress { + if (progress != _progress) { + _progress = progress; + UIView *indicator = self.indicator; + if ([indicator respondsToSelector:@selector(setProgress:)]) { + [(id)indicator setValue:@(self.progress) forKey:@"progress"]; + } + } +} + +- (void)setContentColor:(UIColor *)contentColor { + if (contentColor != _contentColor && ![contentColor isEqual:_contentColor]) { + _contentColor = contentColor; + [self updateViewsForColor:contentColor]; + } +} + +- (void)setDefaultMotionEffectsEnabled:(BOOL)defaultMotionEffectsEnabled { + if (defaultMotionEffectsEnabled != _defaultMotionEffectsEnabled) { + _defaultMotionEffectsEnabled = defaultMotionEffectsEnabled; + [self updateBezelMotionEffects]; + } +} + +#pragma mark - NSProgress + +- (void)setNSProgressDisplayLinkEnabled:(BOOL)enabled { + // We're using CADisplayLink, because NSProgress can change very quickly and observing it may starve the main thread, + // so we're refreshing the progress only every frame draw + if (enabled && self.progressObject) { + // Only create if not already active. + if (!self.progressObjectDisplayLink) { + self.progressObjectDisplayLink = [CADisplayLink displayLinkWithTarget:self selector:@selector(updateProgressFromProgressObject)]; + } + } else { + self.progressObjectDisplayLink = nil; + } +} + +- (void)updateProgressFromProgressObject { + self.progress = self.progressObject.fractionCompleted; +} + +#pragma mark - Notifications + +- (void)registerForNotifications { +#if !TARGET_OS_TV && !TARGET_OS_MACCATALYST + NSNotificationCenter *nc = [NSNotificationCenter defaultCenter]; + + [nc addObserver:self selector:@selector(statusBarOrientationDidChange:) + name:UIApplicationDidChangeStatusBarOrientationNotification object:nil]; +#endif +} + +- (void)unregisterFromNotifications { +#if !TARGET_OS_TV && !TARGET_OS_MACCATALYST + NSNotificationCenter *nc = [NSNotificationCenter defaultCenter]; + [nc removeObserver:self name:UIApplicationDidChangeStatusBarOrientationNotification object:nil]; +#endif +} + +#if !TARGET_OS_TV && !TARGET_OS_MACCATALYST +- (void)statusBarOrientationDidChange:(NSNotification *)notification { + UIView *superview = self.superview; + if (!superview) { + return; + } else { + [self updateForCurrentOrientationAnimated:YES]; + } +} +#endif + +- (void)updateForCurrentOrientationAnimated:(BOOL)animated { + // Stay in sync with the superview in any case + if (self.superview) { + self.frame = self.superview.bounds; + } + + // Not needed on iOS 8+, compile out when the deployment target allows, + // to avoid sharedApplication problems on extension targets +#if __IPHONE_OS_VERSION_MIN_REQUIRED < 80000 + // Only needed pre iOS 8 when added to a window + BOOL iOS8OrLater = kCFCoreFoundationVersionNumber >= kCFCoreFoundationVersionNumber_iOS_8_0; + if (iOS8OrLater || ![self.superview isKindOfClass:[UIWindow class]]) return; + + // Make extension friendly. Will not get called on extensions (iOS 8+) due to the above check. + // This just ensures we don't get a warning about extension-unsafe API. + Class UIApplicationClass = NSClassFromString(@"UIApplication"); + if (!UIApplicationClass || ![UIApplicationClass respondsToSelector:@selector(sharedApplication)]) return; + + UIApplication *application = [UIApplication performSelector:@selector(sharedApplication)]; + UIInterfaceOrientation orientation = application.statusBarOrientation; + CGFloat radians = 0; + + if (UIInterfaceOrientationIsLandscape(orientation)) { + radians = orientation == UIInterfaceOrientationLandscapeLeft ? -(CGFloat)M_PI_2 : (CGFloat)M_PI_2; + // Window coordinates differ! + self.bounds = CGRectMake(0, 0, self.bounds.size.height, self.bounds.size.width); + } else { + radians = orientation == UIInterfaceOrientationPortraitUpsideDown ? (CGFloat)M_PI : 0.f; + } + + if (animated) { + [UIView animateWithDuration:0.3 animations:^{ + self.transform = CGAffineTransformMakeRotation(radians); + }]; + } else { + self.transform = CGAffineTransformMakeRotation(radians); + } +#endif +} + +@end + + +@implementation MBRoundProgressView + +#pragma mark - Lifecycle + +- (id)init { + return [self initWithFrame:CGRectMake(0.f, 0.f, 37.f, 37.f)]; +} + +- (id)initWithFrame:(CGRect)frame { + self = [super initWithFrame:frame]; + if (self) { + self.backgroundColor = [UIColor clearColor]; + self.opaque = NO; + _progress = 0.f; + _annular = NO; + _progressTintColor = [[UIColor alloc] initWithWhite:1.f alpha:1.f]; + _backgroundTintColor = [[UIColor alloc] initWithWhite:1.f alpha:.1f]; + } + return self; +} + +#pragma mark - Layout + +- (CGSize)intrinsicContentSize { + return CGSizeMake(37.f, 37.f); +} + +#pragma mark - Properties + +- (void)setProgress:(float)progress { + if (progress != _progress) { + _progress = progress; + [self setNeedsDisplay]; + } +} + +- (void)setProgressTintColor:(UIColor *)progressTintColor { + NSAssert(progressTintColor, @"The color should not be nil."); + if (progressTintColor != _progressTintColor && ![progressTintColor isEqual:_progressTintColor]) { + _progressTintColor = progressTintColor; + [self setNeedsDisplay]; + } +} + +- (void)setBackgroundTintColor:(UIColor *)backgroundTintColor { + NSAssert(backgroundTintColor, @"The color should not be nil."); + if (backgroundTintColor != _backgroundTintColor && ![backgroundTintColor isEqual:_backgroundTintColor]) { + _backgroundTintColor = backgroundTintColor; + [self setNeedsDisplay]; + } +} + +#pragma mark - Drawing + +- (void)drawRect:(CGRect)rect { + CGContextRef context = UIGraphicsGetCurrentContext(); + + if (_annular) { + // Draw background + CGFloat lineWidth = 2.f; + UIBezierPath *processBackgroundPath = [UIBezierPath bezierPath]; + processBackgroundPath.lineWidth = lineWidth; + processBackgroundPath.lineCapStyle = kCGLineCapButt; + CGPoint center = CGPointMake(CGRectGetMidX(self.bounds), CGRectGetMidY(self.bounds)); + CGFloat radius = (self.bounds.size.width - lineWidth)/2; + CGFloat startAngle = - ((float)M_PI / 2); // 90 degrees + CGFloat endAngle = (2 * (float)M_PI) + startAngle; + [processBackgroundPath addArcWithCenter:center radius:radius startAngle:startAngle endAngle:endAngle clockwise:YES]; + [_backgroundTintColor set]; + [processBackgroundPath stroke]; + // Draw progress + UIBezierPath *processPath = [UIBezierPath bezierPath]; + processPath.lineCapStyle = kCGLineCapSquare; + processPath.lineWidth = lineWidth; + endAngle = (self.progress * 2 * (float)M_PI) + startAngle; + [processPath addArcWithCenter:center radius:radius startAngle:startAngle endAngle:endAngle clockwise:YES]; + [_progressTintColor set]; + [processPath stroke]; + } else { + // Draw background + CGFloat lineWidth = 2.f; + CGRect allRect = self.bounds; + CGRect circleRect = CGRectInset(allRect, lineWidth/2.f, lineWidth/2.f); + CGPoint center = CGPointMake(CGRectGetMidX(self.bounds), CGRectGetMidY(self.bounds)); + [_progressTintColor setStroke]; + [_backgroundTintColor setFill]; + CGContextSetLineWidth(context, lineWidth); + CGContextStrokeEllipseInRect(context, circleRect); + // 90 degrees + CGFloat startAngle = - ((float)M_PI / 2.f); + // Draw progress + UIBezierPath *processPath = [UIBezierPath bezierPath]; + processPath.lineCapStyle = kCGLineCapButt; + processPath.lineWidth = lineWidth * 2.f; + CGFloat radius = (CGRectGetWidth(self.bounds) / 2.f) - (processPath.lineWidth / 2.f); + CGFloat endAngle = (self.progress * 2.f * (float)M_PI) + startAngle; + [processPath addArcWithCenter:center radius:radius startAngle:startAngle endAngle:endAngle clockwise:YES]; + // Ensure that we don't get color overlapping when _progressTintColor alpha < 1.f. + CGContextSetBlendMode(context, kCGBlendModeCopy); + [_progressTintColor set]; + [processPath stroke]; + } +} + +@end + + +@implementation MBBarProgressView + +#pragma mark - Lifecycle + +- (id)init { + return [self initWithFrame:CGRectMake(.0f, .0f, 120.0f, 20.0f)]; +} + +- (id)initWithFrame:(CGRect)frame { + self = [super initWithFrame:frame]; + if (self) { + _progress = 0.f; + _lineColor = [UIColor whiteColor]; + _progressColor = [UIColor whiteColor]; + _progressRemainingColor = [UIColor clearColor]; + self.backgroundColor = [UIColor clearColor]; + self.opaque = NO; + } + return self; +} + +#pragma mark - Layout + +- (CGSize)intrinsicContentSize { + return CGSizeMake(120.f, 10.f); +} + +#pragma mark - Properties + +- (void)setProgress:(float)progress { + if (progress != _progress) { + _progress = progress; + [self setNeedsDisplay]; + } +} + +- (void)setProgressColor:(UIColor *)progressColor { + NSAssert(progressColor, @"The color should not be nil."); + if (progressColor != _progressColor && ![progressColor isEqual:_progressColor]) { + _progressColor = progressColor; + [self setNeedsDisplay]; + } +} + +- (void)setProgressRemainingColor:(UIColor *)progressRemainingColor { + NSAssert(progressRemainingColor, @"The color should not be nil."); + if (progressRemainingColor != _progressRemainingColor && ![progressRemainingColor isEqual:_progressRemainingColor]) { + _progressRemainingColor = progressRemainingColor; + [self setNeedsDisplay]; + } +} + +#pragma mark - Drawing + +- (void)drawRect:(CGRect)rect { + CGContextRef context = UIGraphicsGetCurrentContext(); + + CGContextSetLineWidth(context, 2); + CGContextSetStrokeColorWithColor(context,[_lineColor CGColor]); + CGContextSetFillColorWithColor(context, [_progressRemainingColor CGColor]); + + // Draw background and Border + CGFloat radius = (rect.size.height / 2) - 2; + CGContextMoveToPoint(context, 2, rect.size.height/2); + CGContextAddArcToPoint(context, 2, 2, radius + 2, 2, radius); + CGContextAddArcToPoint(context, rect.size.width - 2, 2, rect.size.width - 2, rect.size.height / 2, radius); + CGContextAddArcToPoint(context, rect.size.width - 2, rect.size.height - 2, rect.size.width - radius - 2, rect.size.height - 2, radius); + CGContextAddArcToPoint(context, 2, rect.size.height - 2, 2, rect.size.height/2, radius); + CGContextDrawPath(context, kCGPathFillStroke); + + CGContextSetFillColorWithColor(context, [_progressColor CGColor]); + radius = radius - 2; + CGFloat amount = self.progress * rect.size.width; + + // Progress in the middle area + if (amount >= radius + 4 && amount <= (rect.size.width - radius - 4)) { + CGContextMoveToPoint(context, 4, rect.size.height/2); + CGContextAddArcToPoint(context, 4, 4, radius + 4, 4, radius); + CGContextAddLineToPoint(context, amount, 4); + CGContextAddLineToPoint(context, amount, radius + 4); + + CGContextMoveToPoint(context, 4, rect.size.height/2); + CGContextAddArcToPoint(context, 4, rect.size.height - 4, radius + 4, rect.size.height - 4, radius); + CGContextAddLineToPoint(context, amount, rect.size.height - 4); + CGContextAddLineToPoint(context, amount, radius + 4); + + CGContextFillPath(context); + } + + // Progress in the right arc + else if (amount > radius + 4) { + CGFloat x = amount - (rect.size.width - radius - 4); + + CGContextMoveToPoint(context, 4, rect.size.height/2); + CGContextAddArcToPoint(context, 4, 4, radius + 4, 4, radius); + CGContextAddLineToPoint(context, rect.size.width - radius - 4, 4); + CGFloat angle = -acos(x/radius); + if (isnan(angle)) angle = 0; + CGContextAddArc(context, rect.size.width - radius - 4, rect.size.height/2, radius, M_PI, angle, 0); + CGContextAddLineToPoint(context, amount, rect.size.height/2); + + CGContextMoveToPoint(context, 4, rect.size.height/2); + CGContextAddArcToPoint(context, 4, rect.size.height - 4, radius + 4, rect.size.height - 4, radius); + CGContextAddLineToPoint(context, rect.size.width - radius - 4, rect.size.height - 4); + angle = acos(x/radius); + if (isnan(angle)) angle = 0; + CGContextAddArc(context, rect.size.width - radius - 4, rect.size.height/2, radius, -M_PI, angle, 1); + CGContextAddLineToPoint(context, amount, rect.size.height/2); + + CGContextFillPath(context); + } + + // Progress is in the left arc + else if (amount < radius + 4 && amount > 0) { + CGContextMoveToPoint(context, 4, rect.size.height/2); + CGContextAddArcToPoint(context, 4, 4, radius + 4, 4, radius); + CGContextAddLineToPoint(context, radius + 4, rect.size.height/2); + + CGContextMoveToPoint(context, 4, rect.size.height/2); + CGContextAddArcToPoint(context, 4, rect.size.height - 4, radius + 4, rect.size.height - 4, radius); + CGContextAddLineToPoint(context, radius + 4, rect.size.height/2); + + CGContextFillPath(context); + } +} + +@end + + +@interface MBBackgroundView () + +@property UIVisualEffectView *effectView; + +@end + + +@implementation MBBackgroundView + +#pragma mark - Lifecycle + +- (instancetype)initWithFrame:(CGRect)frame { + if ((self = [super initWithFrame:frame])) { + _style = MBProgressHUDBackgroundStyleBlur; + if (@available(iOS 13.0, *)) { + #if TARGET_OS_TV + _blurEffectStyle = UIBlurEffectStyleRegular; + #else + _blurEffectStyle = UIBlurEffectStyleSystemThickMaterial; + #endif + // Leaving the color unassigned yields best results. + } else { + _blurEffectStyle = UIBlurEffectStyleLight; + _color = [UIColor colorWithWhite:0.8f alpha:0.6f]; + } + + self.clipsToBounds = YES; + + [self updateForBackgroundStyle]; + } + return self; +} + +#pragma mark - Layout + +- (CGSize)intrinsicContentSize { + // Smallest size possible. Content pushes against this. + return CGSizeZero; +} + +#pragma mark - Appearance + +- (void)setStyle:(MBProgressHUDBackgroundStyle)style { + if (_style != style) { + _style = style; + [self updateForBackgroundStyle]; + } +} + +- (void)setColor:(UIColor *)color { + NSAssert(color, @"The color should not be nil."); + if (color != _color && ![color isEqual:_color]) { + _color = color; + [self updateViewsForColor:color]; + } +} + +- (void)setBlurEffectStyle:(UIBlurEffectStyle)blurEffectStyle { + if (_blurEffectStyle == blurEffectStyle) { + return; + } + + _blurEffectStyle = blurEffectStyle; + + [self updateForBackgroundStyle]; +} + +/////////////////////////////////////////////////////////////////////////////////////////// +#pragma mark - Views + +- (void)updateForBackgroundStyle { + [self.effectView removeFromSuperview]; + self.effectView = nil; + + MBProgressHUDBackgroundStyle style = self.style; + if (style == MBProgressHUDBackgroundStyleBlur) { + UIBlurEffect *effect = [UIBlurEffect effectWithStyle:self.blurEffectStyle]; + UIVisualEffectView *effectView = [[UIVisualEffectView alloc] initWithEffect:effect]; + [self insertSubview:effectView atIndex:0]; + effectView.frame = self.bounds; + effectView.autoresizingMask = UIViewAutoresizingFlexibleHeight | UIViewAutoresizingFlexibleWidth; + self.backgroundColor = self.color; + self.layer.allowsGroupOpacity = NO; + self.effectView = effectView; + } else { + self.backgroundColor = self.color; + } +} + +- (void)updateViewsForColor:(UIColor *)color { + if (self.style == MBProgressHUDBackgroundStyleBlur) { + self.backgroundColor = self.color; + } else { + self.backgroundColor = self.color; + } +} + +@end + + +@implementation MBProgressHUDRoundedButton + +#pragma mark - Lifecycle + +- (instancetype)initWithFrame:(CGRect)frame { + self = [super initWithFrame:frame]; + if (self) { + CALayer *layer = self.layer; + layer.borderWidth = 1.f; + } + return self; +} + +#pragma mark - Layout + +- (void)layoutSubviews { + [super layoutSubviews]; + // Fully rounded corners + CGFloat height = CGRectGetHeight(self.bounds); + self.layer.cornerRadius = ceil(height / 2.f); +} + +- (CGSize)intrinsicContentSize { + // Only show if we have associated control events and a title + if ((self.allControlEvents == 0) || ([self titleForState:UIControlStateNormal].length == 0)) + return CGSizeZero; + CGSize size = [super intrinsicContentSize]; + // Add some side padding + size.width += 20.f; + return size; +} + +#pragma mark - Color + +- (void)setTitleColor:(UIColor *)color forState:(UIControlState)state { + [super setTitleColor:color forState:state]; + // Update related colors + [self setHighlighted:self.highlighted]; + self.layer.borderColor = color.CGColor; +} + +- (void)setHighlighted:(BOOL)highlighted { + [super setHighlighted:highlighted]; + UIColor *baseColor = [self titleColorForState:UIControlStateSelected]; + self.backgroundColor = highlighted ? [baseColor colorWithAlphaComponent:0.1f] : [UIColor clearColor]; +} + +@end diff --git a/Pods/MBProgressHUD/README.mdown b/Pods/MBProgressHUD/README.mdown new file mode 100644 index 0000000..c90f5c6 --- /dev/null +++ b/Pods/MBProgressHUD/README.mdown @@ -0,0 +1,138 @@ +# MBProgressHUD + +[![Build Status](https://travis-ci.org/matej/MBProgressHUD.svg?branch=master)](https://travis-ci.org/matej/MBProgressHUD) [![codecov.io](https://codecov.io/github/matej/MBProgressHUD/coverage.svg?branch=master)](https://codecov.io/github/matej/MBProgressHUD?branch=master) + [![SwiftPM compatible](https://img.shields.io/badge/SwiftPM-compatible-brightgreen.svg)](https://github.com/apple/swift-package-manager) [![Carthage compatible](https://img.shields.io/badge/Carthage-compatible-4BC51D.svg?style=flat)](https://github.com/Carthage/Carthage#adding-frameworks-to-an-application) [![Accio supported](https://img.shields.io/badge/Accio-supported-0A7CF5.svg?style=flat)](https://github.com/JamitLabs/Accio) [![CocoaPods compatible](https://img.shields.io/cocoapods/v/MBProgressHUD.svg?style=flat)](https://cocoapods.org/pods/MBProgressHUD) [![License: MIT](https://img.shields.io/cocoapods/l/MBProgressHUD.svg?style=flat)](http://opensource.org/licenses/MIT) + +`MBProgressHUD` is an iOS drop-in class that displays a translucent HUD with an indicator and/or labels while work is being done in a background thread. The HUD is meant as a replacement for the undocumented, private `UIKit` `UIProgressHUD` with some additional features. + +[![](https://raw.githubusercontent.com/wiki/matej/MBProgressHUD/Screenshots/1-small.png)](https://raw.githubusercontent.com/wiki/matej/MBProgressHUD/Screenshots/1.png) +[![](https://raw.githubusercontent.com/wiki/matej/MBProgressHUD/Screenshots/2-small.png)](https://raw.githubusercontent.com/wiki/matej/MBProgressHUD/Screenshots/2.png) +[![](https://raw.githubusercontent.com/wiki/matej/MBProgressHUD/Screenshots/3-small.png)](https://raw.githubusercontent.com/wiki/matej/MBProgressHUD/Screenshots/3.png) +[![](https://raw.githubusercontent.com/wiki/matej/MBProgressHUD/Screenshots/4-small.png)](https://raw.githubusercontent.com/wiki/matej/MBProgressHUD/Screenshots/4.png) +[![](https://raw.githubusercontent.com/wiki/matej/MBProgressHUD/Screenshots/5-small.png)](https://raw.githubusercontent.com/wiki/matej/MBProgressHUD/Screenshots/5.png) +[![](https://raw.githubusercontent.com/wiki/matej/MBProgressHUD/Screenshots/6-small.png)](https://raw.githubusercontent.com/wiki/matej/MBProgressHUD/Screenshots/6.png) +[![](https://raw.githubusercontent.com/wiki/matej/MBProgressHUD/Screenshots/7-small.png)](https://raw.githubusercontent.com/wiki/matej/MBProgressHUD/Screenshots/7.png) + +**NOTE:** The class has recently undergone a major rewrite. The old version is available in the [legacy](https://github.com/jdg/MBProgressHUD/tree/legacy) branch, should you need it. + +## Requirements + +`MBProgressHUD` works on iOS 9.0+. It depends on the following Apple frameworks, which should already be included with most Xcode templates: + +* Foundation.framework +* UIKit.framework +* CoreGraphics.framework + +You will need the latest developer tools in order to build `MBProgressHUD`. Old Xcode versions might work, but compatibility will not be explicitly maintained. + +## Adding MBProgressHUD to your project + +### CocoaPods + +[CocoaPods](http://cocoapods.org) is the recommended way to add MBProgressHUD to your project. + +1. Add a pod entry for MBProgressHUD to your Podfile `pod 'MBProgressHUD', '~> 1.2.0'` +2. Install the pod(s) by running `pod install`. +3. Include MBProgressHUD wherever you need it with `#import "MBProgressHUD.h"`. + +### Carthage + +1. Add MBProgressHUD to your Cartfile. e.g., `github "jdg/MBProgressHUD" ~> 1.2.0` +2. Run `carthage update` +3. Follow the rest of the [standard Carthage installation instructions](https://github.com/Carthage/Carthage#adding-frameworks-to-an-application) to add MBProgressHUD to your project. + +### SwiftPM / Accio + +1. Add the following to your `Package.swift`: + ```swift + .package(url: "https://github.com/jdg/MBProgressHUD.git", .upToNextMajor(from: "1.2.0")), + ``` +2. Next, add `MBProgressHUD` to your App targets dependencies like so: + ```swift + .target(name: "App", dependencies: ["MBProgressHUD"]), + ``` +3. Then open your project in Xcode 11+ (SwiftPM) or run `accio update` (Accio). + +### Source files + +Alternatively you can directly add the `MBProgressHUD.h` and `MBProgressHUD.m` source files to your project. + +1. Download the [latest code version](https://github.com/matej/MBProgressHUD/archive/master.zip) or add the repository as a git submodule to your git-tracked project. +2. Open your project in Xcode, then drag and drop `MBProgressHUD.h` and `MBProgressHUD.m` onto your project (use the "Product Navigator view"). Make sure to select Copy items when asked if you extracted the code archive outside of your project. +3. Include MBProgressHUD wherever you need it with `#import "MBProgressHUD.h"`. + +### Static library + +You can also add MBProgressHUD as a static library to your project or workspace. + +1. Download the [latest code version](https://github.com/matej/MBProgressHUD/downloads) or add the repository as a git submodule to your git-tracked project. +2. Open your project in Xcode, then drag and drop `MBProgressHUD.xcodeproj` onto your project or workspace (use the "Product Navigator view"). +3. Select your target and go to the Build phases tab. In the Link Binary With Libraries section select the add button. On the sheet find and add `libMBProgressHUD.a`. You might also need to add `MBProgressHUD` to the Target Dependencies list. +4. Include MBProgressHUD wherever you need it with `#import `. + +## Usage + +The main guideline you need to follow when dealing with MBProgressHUD while running long-running tasks is keeping the main thread work-free, so the UI can be updated promptly. The recommended way of using MBProgressHUD is therefore to set it up on the main thread and then spinning the task, that you want to perform, off onto a new thread. + +```objective-c +[MBProgressHUD showHUDAddedTo:self.view animated:YES]; +dispatch_async(dispatch_get_global_queue( DISPATCH_QUEUE_PRIORITY_LOW, 0), ^{ + // Do something... + dispatch_async(dispatch_get_main_queue(), ^{ + [MBProgressHUD hideHUDForView:self.view animated:YES]; + }); +}); +``` + +You can add the HUD on any view or window. It is however a good idea to avoid adding the HUD to certain `UIKit` views with complex view hierarchies - like `UITableView` or `UICollectionView`. Those can mutate their subviews in unexpected ways and thereby break HUD display. + +If you need to configure the HUD you can do this by using the MBProgressHUD reference that showHUDAddedTo:animated: returns. + +```objective-c +MBProgressHUD *hud = [MBProgressHUD showHUDAddedTo:self.view animated:YES]; +hud.mode = MBProgressHUDModeAnnularDeterminate; +hud.label.text = @"Loading"; +[self doSomethingInBackgroundWithProgressCallback:^(float progress) { + hud.progress = progress; +} completionCallback:^{ + [hud hideAnimated:YES]; +}]; +``` + +You can also use a `NSProgress` object and MBProgressHUD will update itself when there is progress reported through that object. + +```objective-c +MBProgressHUD *hud = [MBProgressHUD showHUDAddedTo:self.view animated:YES]; +hud.mode = MBProgressHUDModeAnnularDeterminate; +hud.label.text = @"Loading"; +NSProgress *progress = [self doSomethingInBackgroundCompletion:^{ + [hud hideAnimated:YES]; +}]; +hud.progressObject = progress; +``` + +Keep in mind that UI updates, inclining calls to MBProgressHUD should always be done on the main thread. + +If you need to run your long-running task in the main thread, you should perform it with a slight delay, so UIKit will have enough time to update the UI (i.e., draw the HUD) before you block the main thread with your task. + +```objective-c +[MBProgressHUD showHUDAddedTo:self.view animated:YES]; +dispatch_time_t popTime = dispatch_time(DISPATCH_TIME_NOW, 0.01 * NSEC_PER_SEC); +dispatch_after(popTime, dispatch_get_main_queue(), ^(void){ + // Do something... + [MBProgressHUD hideHUDForView:self.view animated:YES]; +}); +``` + +You should be aware that any HUD updates issued inside the above block won't be displayed until the block completes. + +For more examples, including how to use MBProgressHUD with asynchronous operations such as NSURLConnection, take a look at the bundled demo project. Extensive API documentation is provided in the header file (MBProgressHUD.h). + + +## License + +This code is distributed under the terms and conditions of the [MIT license](LICENSE). + +## Change-log + +A brief summary of each MBProgressHUD release can be found in the [CHANGELOG](CHANGELOG.mdown). diff --git a/Pods/Manifest.lock b/Pods/Manifest.lock new file mode 100644 index 0000000..ce84de4 --- /dev/null +++ b/Pods/Manifest.lock @@ -0,0 +1,60 @@ +PODS: + - Alamofire (5.7.1) + - HandyJSON (5.0.2) + - Kingfisher (7.10.2) + - MBProgressHUD (1.2.0) + - Moya (15.0.0): + - Moya/Core (= 15.0.0) + - Moya/Core (15.0.0): + - Alamofire (~> 5.0) + - Reusable (4.1.2): + - Reusable/Storyboard (= 4.1.2) + - Reusable/View (= 4.1.2) + - Reusable/Storyboard (4.1.2) + - Reusable/View (4.1.2) + - RxCocoa (6.5.0): + - RxRelay (= 6.5.0) + - RxSwift (= 6.5.0) + - RxRelay (6.5.0): + - RxSwift (= 6.5.0) + - RxSwift (6.5.0) + - SnapKit (5.6.0) + +DEPENDENCIES: + - HandyJSON + - Kingfisher + - MBProgressHUD + - Moya + - Reusable + - RxCocoa + - RxSwift + - SnapKit (~> 5.6.0) + +SPEC REPOS: + https://mirrors.tuna.tsinghua.edu.cn/git/CocoaPods/Specs.git: + - Alamofire + - HandyJSON + - Kingfisher + - MBProgressHUD + - Moya + - Reusable + - RxCocoa + - RxRelay + - RxSwift + - SnapKit + +SPEC CHECKSUMS: + Alamofire: 0123a34370cb170936ae79a8df46cc62b2edeb88 + HandyJSON: 9e4e236f5d2dbefad5155a77417bbea438201c03 + Kingfisher: 99edc495d3b7607e6425f0d6f6847b2abd6d716d + MBProgressHUD: 3ee5efcc380f6a79a7cc9b363dd669c5e1ae7406 + Moya: 138f0573e53411fb3dc17016add0b748dfbd78ee + Reusable: 6bae6a5e8aa793c9c441db0213c863a64bce9136 + RxCocoa: 94f817b71c07517321eb4f9ad299112ca8af743b + RxRelay: 1de1523e604c72b6c68feadedd1af3b1b4d0ecbd + RxSwift: 5710a9e6b17f3c3d6e40d6e559b9fa1e813b2ef8 + SnapKit: e01d52ebb8ddbc333eefe2132acf85c8227d9c25 + +PODFILE CHECKSUM: e291658151a1fcada5c9dd297587942ae9475225 + +COCOAPODS: 1.12.1 diff --git a/Pods/Moya/License.md b/Pods/Moya/License.md new file mode 100644 index 0000000..58ef14f --- /dev/null +++ b/Pods/Moya/License.md @@ -0,0 +1,21 @@ +The MIT License (MIT) + +Copyright (c) 2014-present Artsy, Ash Furrow + +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/Moya/Readme.md b/Pods/Moya/Readme.md new file mode 100644 index 0000000..7fe7a31 --- /dev/null +++ b/Pods/Moya/Readme.md @@ -0,0 +1,360 @@ +

+ +

+ +# Moya 15.0.0 + +[![CircleCI](https://img.shields.io/circleci/project/github/Moya/Moya/master.svg)](https://circleci.com/gh/Moya/Moya/tree/master) +[![codecov.io](https://codecov.io/github/Moya/Moya/coverage.svg?branch=master)](https://codecov.io/github/Moya/Moya?branch=master) +[![Carthage compatible](https://img.shields.io/badge/Carthage-compatible-4BC51D.svg?style=flat)](https://github.com/Carthage/Carthage) +[![Accio supported](https://img.shields.io/badge/Accio-supported-0A7CF5.svg?style=flat)](https://github.com/JamitLabs/Accio) +[![CocoaPods compatible](https://img.shields.io/cocoapods/v/Moya.svg)](https://cocoapods.org/pods/Moya) +[![Swift Package Manager compatible](https://img.shields.io/badge/Swift%20Package%20Manager-compatible-brightgreen.svg)](https://github.com/apple/swift-package-manager) + +*A Chinese version of this document can be found [here](https://github.com/Moya/Moya/blob/master/Readme_CN.md).* + +You're a smart developer. You probably use [Alamofire](https://github.com/Alamofire/Alamofire) to abstract away access to +`URLSession` and all those nasty details you don't really care about. But then, +like lots of smart developers, you write ad hoc network abstraction layers. They +are probably called "APIManager" or "NetworkModel", and they always end in tears. + +![Moya Overview](web/diagram.png) + +Ad hoc network layers are common in iOS apps. They're bad for a few reasons: + +- Makes it hard to write new apps ("where do I begin?") +- Makes it hard to maintain existing apps ("oh my god, this mess...") +- Makes it hard to write unit tests ("how do I do this again?") + +So the basic idea of Moya is that we want some network abstraction layer that +sufficiently encapsulates actually calling Alamofire directly. It should be simple +enough that common things are easy, but comprehensive enough that complicated things +are also easy. + +> If you use Alamofire to abstract away `URLSession`, why not use something +to abstract away the nitty gritty of URLs, parameters, etc? + +Some awesome features of Moya: + +- Compile-time checking for correct API endpoint accesses. +- Lets you define a clear usage of different endpoints with associated enum values. +- Treats test stubs as first-class citizens so unit testing is super-easy. + +You can check out more about the project direction in the [vision document](https://github.com/Moya/Moya/blob/master/Vision.md). + +## Sample Projects + +We have provided two sample projects in the repository. To use it download the repo, run `carthage update` to download the required libraries and open [Moya.xcodeproj](https://github.com/Moya/Moya/tree/master/Moya.xcodeproj). You'll see two schemes: `Basic` and `Multi-Target` - select one and then build & run! Source files for these are in the `Examples` directory in project navigator. Have fun! + +## Project Status + +This project is actively under development, and is being used in [Artsy's +new auction app](https://github.com/Artsy/eidolon). We consider it +ready for production use. + +## Installation + +### Moya version vs Swift version. + +Below is a table that shows which version of Moya you should use for +your Swift version. + +| Swift | Moya | RxMoya | ReactiveMoya | +| ----- | -------------- |---------------- |--------------- | +| 5.X | >= 13.0.0 | >= 13.0.0 | >= 13.0.0 | +| 4.X | 9.0.0 - 12.0.1 | 10.0.0 - 12.0.1 | 9.0.0 - 12.0.1 | +| 3.X | 8.0.0 - 8.0.5 | 8.0.0 - 8.0.5 | 8.0.0 - 8.0.5 | +| 2.3 | 7.0.2 - 7.0.4 | 7.0.2 - 7.0.4 | 7.0.2 - 7.0.4 | +| 2.2 | <= 7.0.1 | <= 7.0.1 | <= 7.0.1 | + +_Note: If you are using Swift 4.2 in your project, but you are using Xcode 10.2, Moya 13 should work correctly even though we use Swift 5.0._ + +**Upgrading to a new major version of Moya? Check out our [migration guides](https://github.com/Moya/Moya/blob/master/docs/MigrationGuides).** + +### Swift Package Manager + +_Note: Instructions below are for using **SwiftPM** without the Xcode UI. It's the easiest to go to your Project Settings -> Swift Packages and add Moya from there._ + +To integrate using Apple's Swift package manager, without Xcode integration, add the following as a dependency to your `Package.swift`: + +```swift +.package(url: "https://github.com/Moya/Moya.git", .upToNextMajor(from: "15.0.0")) +``` + +and then specify `"Moya"` as a dependency of the Target in which you wish to use Moya. +If you want to use reactive extensions, add also `"ReactiveMoya"`, `"RxMoya"` or +`"CombineMoya"` as your target dependency respectively. +Here's an example `PackageDescription`: + +```swift +// swift-tools-version:5.3 +import PackageDescription + +let package = Package( + name: "MyPackage", + products: [ + .library( + name: "MyPackage", + targets: ["MyPackage"]), + ], + dependencies: [ + .package(url: "https://github.com/Moya/Moya.git", .upToNextMajor(from: "15.0.0")) + ], + targets: [ + .target( + name: "MyPackage", + dependencies: ["ReactiveMoya"]) + ] +) +``` + +Note: If you are using **ReactiveMoya**, we are using [our own fork of ReactiveSwift](https://github.com/Moya/ReactiveSwift). This fork adds 2 commits to remove testing dependencies on releases (starting 6.1.0). This is to prevent Xcode Previews on Xcode 11/11.1 to build testing dependencies (FB7316430). If you don't want to use our fork, you can just add another dependency to your SPM package list: `git@github.com:ReactiveCocoa/ReactiveSwift.git` and it should fetch the original repository. + +Combine note: if you're using **CombineMoya**, make sure that you use Xcode 11.5.0 +or later. With earlier versions of Xcode you will have to manually add Combine as +a weakly linked framework to your application target. + +### Accio + +[Accio](https://github.com/JamitLabs/Accio) is a dependency manager based on SwiftPM which can build frameworks for iOS/macOS/tvOS/watchOS. Therefore the integration steps of Moya are exactly the same as described above. Once your `Package.swift` file is configured, run `accio update` instead of `swift package update`. + +### CocoaPods + +For Moya, use the following entry in your Podfile: + +```rb +pod 'Moya', '~> 15.0' + +# or + +pod 'Moya/RxSwift', '~> 15.0' + +# or + +pod 'Moya/ReactiveSwift', '~> 15.0' + +#or + +pod 'Moya/Combine', '~> 15.0' +``` + +Then run `pod install`. + +In any file you'd like to use Moya in, don't forget to +import the framework with `import Moya`. + +### Carthage + +Carthage users can point to this repository and use whichever +generated framework they'd like, `Moya`, `RxMoya`, `ReactiveMoya`, or +`CombineMoya`. + +Make the following entry in your Cartfile: + +``` +github "Moya/Moya" ~> 15.0 +``` + +Then run `carthage update --use-xcframeworks`. + +If this is your first time using Carthage in the project, you'll need to go through some additional steps as explained [over at Carthage](https://github.com/Carthage/Carthage#adding-frameworks-to-an-application). + +> NOTE: At this time, Carthage does not provide a way to build only specific repository submodules. All submodules and their dependencies will be built with the above command. However, you don't need to copy frameworks you aren't using into your project. For instance, if you aren't using `ReactiveSwift`, feel free to delete that framework along with `ReactiveMoya` from the Carthage Build directory after `carthage update` completes. Or if you are using `ReactiveSwift` but not `RxSwift` or `Combine`, then `RxMoya`, `RxTest`, `RxCocoa`, `CombineMoya` etc. can safely be deleted. + +### Manually + +- 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 & Moya as a git [submodule](http://git-scm.com/docs/git-submodule) by running the following commands: + +```bash +$ git submodule add https://github.com/Alamofire/Alamofire.git +$ git submodule add https://github.com/Moya/Moya.git +``` + +- Open the new `Alamofire` folder, and drag the `Alamofire.xcodeproj` into the Project Navigator of your application's Xcode project. Do the same with the `Moya.xcodeproj` in the `Moya` folder. + +> They should appear nested underneath your application's blue project icon. Whether it is above or below all the other Xcode groups does not matter. + +- Verify that the deployment targets of the `xcodeproj`s match that of your application target in the Project Navigator. +- 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 macOS. + +> 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`. + +- Click on the `+` button under "Embedded Binaries" again and add the correct build target for `Moya`. + +- And that's it! + +> The three frameworks are 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 + +After [some setup](https://github.com/Moya/Moya/blob/master/docs/Examples/Basic.md), using Moya is really simple. You can access an API like this: + +```swift +provider = MoyaProvider() +provider.request(.zen) { result in + switch result { + case let .success(moyaResponse): + let data = moyaResponse.data + let statusCode = moyaResponse.statusCode + // do something with the response data or statusCode + case let .failure(error): + // this means there was a network failure - either the request + // wasn't sent (connectivity), or no response was received (server + // timed out). If the server responds with a 4xx or 5xx error, that + // will be sent as a ".success"-ful response. + } +} +``` + +That's a basic example. Many API requests need parameters. Moya encodes these +into the enum you use to access the endpoint, like this: + +```swift +provider = MoyaProvider() +provider.request(.userProfile("ashfurrow")) { result in + // do something with the result +} +``` + +No more typos in URLs. No more missing parameter values. No more messing with +parameter encoding. + +For more examples, see the [documentation](https://github.com/Moya/Moya/blob/master/docs/Examples). + +## Reactive Extensions + +Even cooler are the reactive extensions. Moya provides reactive extensions for +[ReactiveSwift](https://github.com/ReactiveCocoa/ReactiveSwift), +[RxSwift](https://github.com/ReactiveX/RxSwift), and +[Combine](https://developer.apple.com/documentation/combine). + +### ReactiveSwift + +[`ReactiveSwift` extension](https://github.com/Moya/Moya/blob/master/docs/ReactiveSwift.md) provides both `reactive.request(:callbackQueue:)` and +`reactive.requestWithProgress(:callbackQueue:)` methods that immediately return +`SignalProducer`s that you can start, bind, map, or whatever you want to do. +To handle errors, for instance, we could do the following: + +```swift +provider = MoyaProvider() +provider.reactive.request(.userProfile("ashfurrow")).start { event in + switch event { + case let .value(response): + image = UIImage(data: response.data) + case let .failed(error): + print(error) + default: + break + } +} +``` + +### RxSwift + +[`RxSwift` extension](https://github.com/Moya/Moya/blob/master/docs/RxSwift.md) also provide both `rx.request(:callbackQueue:)` and +`rx.requestWithProgress(:callbackQueue:)` methods, but return type is +different for both. In case of a normal `rx.request(:callbackQueue)`, the +return type is `Single` which emits either single element or an +error. In case of a `rx.requestWithProgress(:callbackQueue:)`, the return +type is `Observable`, since we may get multiple events +from progress and one last event which is a response. + +To handle errors, for instance, we could do the following: + +```swift +provider = MoyaProvider() +provider.rx.request(.userProfile("ashfurrow")).subscribe { event in + switch event { + case let .success(response): + image = UIImage(data: response.data) + case let .error(error): + print(error) + } +} +``` + +In addition to the option of using signals instead of callback blocks, there are +also a series of signal operators for RxSwift and ReactiveSwift that will attempt +to map the data received from the network response into either an image, some JSON, +or a string, with `mapImage()`, `mapJSON()`, and `mapString()`, respectively. If the mapping is unsuccessful, you'll get an error on the signal. You also get handy methods +for filtering out certain status codes. This means that you can place your code for +handling API errors like 400's in the same places as code for handling invalid +responses. + +### Combine + +`Combine` extension provides `requestPublisher(:callbackQueue:)` and +`requestWithProgressPublisher(:callbackQueue)` returning +`AnyPublisher` and `AnyPublisher` +respectively. + +Here's an example of `requestPublisher` usage: + +```swift +provider = MoyaProvider() +let cancellable = provider.requestPublisher(.userProfile("ashfurrow")) + .sink(receiveCompletion: { completion in + guard case let .failure(error) = completion else { return } + + print(error) + }, receiveValue: { response in + image = UIImage(data: response.data) + }) +``` + +## Community Projects + +[Moya has a great community around it and some people have created some very helpful extensions](https://github.com/Moya/Moya/blob/master/docs/CommunityProjects.md). + +## Contributing + +Hey! Do you like Moya? Awesome! We could actually really use your help! + +Open source isn't just writing code. Moya could use your help with any of the +following: + +- Finding (and reporting!) bugs. +- New feature suggestions. +- Answering questions on issues. +- Documentation improvements. +- Reviewing pull requests. +- Helping to manage issue priorities. +- Fixing bugs/new features. + +If any of that sounds cool to you, send a pull request! After your first +contribution, we will add you as a member to the repo so you can merge pull +requests and help steer the ship :ship: You can read more details about that [in our contributor guidelines](https://github.com/Moya/Moya/blob/master/Contributing.md). + +Moya's community has a tremendous positive energy, and the maintainers are committed to keeping things awesome. Like [in the CocoaPods community](https://github.com/CocoaPods/CocoaPods/wiki/Communication-&-Design-Rules), always assume positive intent; even if a comment sounds mean-spirited, give the person the benefit of the doubt. + +Please note that this project is released with a Contributor Code of Conduct. By participating in this project you agree to abide by [its terms](https://github.com/Moya/Moya/blob/master/Code%20of%20Conduct.md). + +### Adding new source files + +If you add or remove a source file from Moya, a corresponding change needs to be made to the `Moya.xcodeproj` project at the root of this repository. This project is used for Carthage. Don't worry, you'll get an automated warning when submitting a pull request if you forget. + +### Help us improve Moya documentation +Whether you’re a core member or a user trying it out for the first time, you can make a valuable contribution to Moya by improving the documentation. Help us by: + +- sending us feedback about something you thought was confusing or simply missing +- suggesting better wording or ways of explaining certain topics +- sending us a pull request via GitHub +- improving the [Chinese documentation](https://github.com/Moya/Moya/blob/master/Readme_CN.md) + + +## License + +Moya is released under an MIT license. See [License.md](https://github.com/Moya/Moya/blob/master/License.md) for more information. diff --git a/Pods/Moya/Sources/Moya/AnyEncodable.swift b/Pods/Moya/Sources/Moya/AnyEncodable.swift new file mode 100644 index 0000000..15c7128 --- /dev/null +++ b/Pods/Moya/Sources/Moya/AnyEncodable.swift @@ -0,0 +1,14 @@ +import Foundation + +struct AnyEncodable: Encodable { + + private let encodable: Encodable + + public init(_ encodable: Encodable) { + self.encodable = encodable + } + + func encode(to encoder: Encoder) throws { + try encodable.encode(to: encoder) + } +} diff --git a/Pods/Moya/Sources/Moya/Atomic.swift b/Pods/Moya/Sources/Moya/Atomic.swift new file mode 100644 index 0000000..339f59f --- /dev/null +++ b/Pods/Moya/Sources/Moya/Atomic.swift @@ -0,0 +1,31 @@ +// +// Atomic.swift +// Moya +// +// Created by Luciano Almeida on 15/12/19. +// + +import Foundation + +@propertyWrapper +final class Atomic { + private var lock: NSRecursiveLock = NSRecursiveLock() + + private var value: Value + + var wrappedValue: Value { + get { + lock.lock(); defer { lock.unlock() } + return value + } + + set { + lock.lock(); defer { lock.unlock() } + value = newValue + } + } + + init(wrappedValue value: Value) { + self.value = value + } +} diff --git a/Pods/Moya/Sources/Moya/Cancellable.swift b/Pods/Moya/Sources/Moya/Cancellable.swift new file mode 100644 index 0000000..368271c --- /dev/null +++ b/Pods/Moya/Sources/Moya/Cancellable.swift @@ -0,0 +1,26 @@ +/// Protocol to define the opaque type returned from a request. +public protocol Cancellable { + + /// A Boolean value stating whether a request is cancelled. + var isCancelled: Bool { get } + + /// Cancels the represented request. + func cancel() +} + +internal class CancellableWrapper: Cancellable { + internal var innerCancellable: Cancellable = SimpleCancellable() + + var isCancelled: Bool { innerCancellable.isCancelled } + + internal func cancel() { + innerCancellable.cancel() + } +} + +internal class SimpleCancellable: Cancellable { + var isCancelled = false + func cancel() { + isCancelled = true + } +} diff --git a/Pods/Moya/Sources/Moya/Endpoint.swift b/Pods/Moya/Sources/Moya/Endpoint.swift new file mode 100755 index 0000000..fd5fef7 --- /dev/null +++ b/Pods/Moya/Sources/Moya/Endpoint.swift @@ -0,0 +1,160 @@ +import Foundation + +/// Used for stubbing responses. +public enum EndpointSampleResponse { + + /// The network returned a response, including status code and data. + case networkResponse(Int, Data) + + /// The network returned response which can be fully customized. + case response(HTTPURLResponse, Data) + + /// The network failed to send the request, or failed to retrieve a response (eg a timeout). + case networkError(NSError) +} + +/// Class for reifying a target of the `Target` enum unto a concrete `Endpoint`. +/// - Note: As of Moya 11.0.0 Endpoint is no longer generic. +/// Existing code should work as is after removing the generic. +/// See #1529 and #1524 for the discussion. +open class Endpoint { + public typealias SampleResponseClosure = () -> EndpointSampleResponse + + /// A string representation of the URL for the request. + public let url: String + + /// A closure responsible for returning an `EndpointSampleResponse`. + public let sampleResponseClosure: SampleResponseClosure + + /// The HTTP method for the request. + public let method: Moya.Method + + /// The `Task` for the request. + public let task: Task + + /// The HTTP header fields for the request. + public let httpHeaderFields: [String: String]? + + public init(url: String, + sampleResponseClosure: @escaping SampleResponseClosure, + method: Moya.Method, + task: Task, + httpHeaderFields: [String: String]?) { + + self.url = url + self.sampleResponseClosure = sampleResponseClosure + self.method = method + self.task = task + self.httpHeaderFields = httpHeaderFields + } + + /// Convenience method for creating a new `Endpoint` with the same properties as the receiver, but with added HTTP header fields. + open func adding(newHTTPHeaderFields: [String: String]) -> Endpoint { + Endpoint(url: url, sampleResponseClosure: sampleResponseClosure, method: method, task: task, httpHeaderFields: add(httpHeaderFields: newHTTPHeaderFields)) + } + + /// Convenience method for creating a new `Endpoint` with the same properties as the receiver, but with replaced `task` parameter. + open func replacing(task: Task) -> Endpoint { + Endpoint(url: url, sampleResponseClosure: sampleResponseClosure, method: method, task: task, httpHeaderFields: httpHeaderFields) + } + + fileprivate func add(httpHeaderFields headers: [String: String]?) -> [String: String]? { + guard let unwrappedHeaders = headers, unwrappedHeaders.isEmpty == false else { + return self.httpHeaderFields + } + + var newHTTPHeaderFields = self.httpHeaderFields ?? [:] + unwrappedHeaders.forEach { key, value in + newHTTPHeaderFields[key] = value + } + return newHTTPHeaderFields + } +} + +/// Extension for converting an `Endpoint` into a `URLRequest`. +public extension Endpoint { + // swiftlint:disable cyclomatic_complexity + /// Returns the `Endpoint` converted to a `URLRequest` if valid. Throws an error otherwise. + func urlRequest() throws -> URLRequest { + guard let requestURL = Foundation.URL(string: url) else { + throw MoyaError.requestMapping(url) + } + + var request = URLRequest(url: requestURL) + request.httpMethod = method.rawValue + request.allHTTPHeaderFields = httpHeaderFields + + switch task { + case .requestPlain, .uploadFile, .uploadMultipart, .downloadDestination: + return request + case .requestData(let data): + request.httpBody = data + return request + case let .requestJSONEncodable(encodable): + return try request.encoded(encodable: encodable) + case let .requestCustomJSONEncodable(encodable, encoder: encoder): + return try request.encoded(encodable: encodable, encoder: encoder) + case let .requestParameters(parameters, parameterEncoding): + return try request.encoded(parameters: parameters, parameterEncoding: parameterEncoding) + case let .uploadCompositeMultipart(_, urlParameters): + let parameterEncoding = URLEncoding(destination: .queryString) + return try request.encoded(parameters: urlParameters, parameterEncoding: parameterEncoding) + case let .downloadParameters(parameters, parameterEncoding, _): + return try request.encoded(parameters: parameters, parameterEncoding: parameterEncoding) + case let .requestCompositeData(bodyData: bodyData, urlParameters: urlParameters): + request.httpBody = bodyData + let parameterEncoding = URLEncoding(destination: .queryString) + return try request.encoded(parameters: urlParameters, parameterEncoding: parameterEncoding) + case let .requestCompositeParameters(bodyParameters: bodyParameters, bodyEncoding: bodyParameterEncoding, urlParameters: urlParameters): + if let bodyParameterEncoding = bodyParameterEncoding as? URLEncoding, bodyParameterEncoding.destination != .httpBody { + fatalError("Only URLEncoding that `bodyEncoding` accepts is URLEncoding.httpBody. Others like `default`, `queryString` or `methodDependent` are prohibited - if you want to use them, add your parameters to `urlParameters` instead.") + } + let bodyfulRequest = try request.encoded(parameters: bodyParameters, parameterEncoding: bodyParameterEncoding) + let urlEncoding = URLEncoding(destination: .queryString) + return try bodyfulRequest.encoded(parameters: urlParameters, parameterEncoding: urlEncoding) + } + } + // swiftlint:enable cyclomatic_complexity +} + +/// Required for using `Endpoint` as a key type in a `Dictionary`. +extension Endpoint: Equatable, Hashable { + public func hash(into hasher: inout Hasher) { + switch task { + case let .uploadFile(file): + hasher.combine(file) + case let .uploadMultipart(multipartData), let .uploadCompositeMultipart(multipartData, _): + hasher.combine(multipartData) + default: + break + } + + if let request = try? urlRequest() { + hasher.combine(request) + } else { + hasher.combine(url) + } + } + + /// Note: If both Endpoints fail to produce a URLRequest the comparison will + /// fall back to comparing each Endpoint's hashValue. + public static func == (lhs: Endpoint, rhs: Endpoint) -> Bool { + let areEndpointsEqualInAdditionalProperties: Bool = { + switch (lhs.task, rhs.task) { + case (let .uploadFile(file1), let .uploadFile(file2)): + return file1 == file2 + case (let .uploadMultipart(multipartData1), let .uploadMultipart(multipartData2)), + (let .uploadCompositeMultipart(multipartData1, _), let .uploadCompositeMultipart(multipartData2, _)): + return multipartData1 == multipartData2 + default: + return true + } + }() + let lhsRequest = try? lhs.urlRequest() + let rhsRequest = try? rhs.urlRequest() + if lhsRequest != nil, rhsRequest == nil { return false } + if lhsRequest == nil, rhsRequest != nil { return false } + if lhsRequest == nil, rhsRequest == nil { return lhs.hashValue == rhs.hashValue && areEndpointsEqualInAdditionalProperties } + return lhsRequest == rhsRequest && areEndpointsEqualInAdditionalProperties + } +} diff --git a/Pods/Moya/Sources/Moya/Image.swift b/Pods/Moya/Sources/Moya/Image.swift new file mode 100644 index 0000000..b57b472 --- /dev/null +++ b/Pods/Moya/Sources/Moya/Image.swift @@ -0,0 +1,10 @@ +#if canImport(UIKit) + import UIKit.UIImage + public typealias ImageType = UIImage +#elseif canImport(AppKit) + import AppKit.NSImage + public typealias ImageType = NSImage +#endif + +/// An alias for the SDK's image type. +public typealias Image = ImageType diff --git a/Pods/Moya/Sources/Moya/Moya+Alamofire.swift b/Pods/Moya/Sources/Moya/Moya+Alamofire.swift new file mode 100644 index 0000000..1e77a7c --- /dev/null +++ b/Pods/Moya/Sources/Moya/Moya+Alamofire.swift @@ -0,0 +1,125 @@ +import Foundation +import Alamofire + +public typealias Session = Alamofire.Session +internal typealias Request = Alamofire.Request +internal typealias DownloadRequest = Alamofire.DownloadRequest +internal typealias UploadRequest = Alamofire.UploadRequest +internal typealias DataRequest = Alamofire.DataRequest + +internal typealias URLRequestConvertible = Alamofire.URLRequestConvertible + +/// Represents an HTTP method. +public typealias Method = Alamofire.HTTPMethod + +/// Choice of parameter encoding. +public typealias ParameterEncoding = Alamofire.ParameterEncoding +public typealias JSONEncoding = Alamofire.JSONEncoding +public typealias URLEncoding = Alamofire.URLEncoding + +/// Multipart form. +public typealias RequestMultipartFormData = Alamofire.MultipartFormData + +/// Multipart form data encoding result. +public typealias DownloadDestination = Alamofire.DownloadRequest.Destination + +/// Make the Alamofire Request type conform to our type, to prevent leaking Alamofire to plugins. +extension Request: RequestType { + public var sessionHeaders: [String: String] { + delegate?.sessionConfiguration.httpAdditionalHeaders as? [String: String] ?? [:] + } +} + +/// Represents Request interceptor type that can modify/act on Request +public typealias RequestInterceptor = Alamofire.RequestInterceptor + +/// Internal token that can be used to cancel requests +public final class CancellableToken: Cancellable, CustomDebugStringConvertible { + let cancelAction: () -> Void + let request: Request? + + public fileprivate(set) var isCancelled = false + + fileprivate var lock: DispatchSemaphore = DispatchSemaphore(value: 1) + + public func cancel() { + _ = lock.wait(timeout: DispatchTime.distantFuture) + defer { lock.signal() } + guard !isCancelled else { return } + isCancelled = true + cancelAction() + } + + public init(action: @escaping () -> Void) { + self.cancelAction = action + self.request = nil + } + + init(request: Request) { + self.request = request + self.cancelAction = { + request.cancel() + } + } + + /// A textual representation of this instance, suitable for debugging. + public var debugDescription: String { + guard let request = self.request else { + return "Empty Request" + } + return request.cURLDescription() + } + +} + +internal typealias RequestableCompletion = (HTTPURLResponse?, URLRequest?, Data?, Swift.Error?) -> Void + +internal protocol Requestable { + func response(callbackQueue: DispatchQueue?, completionHandler: @escaping RequestableCompletion) -> Self +} + +extension DataRequest: Requestable { + internal func response(callbackQueue: DispatchQueue?, completionHandler: @escaping RequestableCompletion) -> Self { + if let callbackQueue = callbackQueue { + return response(queue: callbackQueue) { handler in + completionHandler(handler.response, handler.request, handler.data, handler.error) + } + } else { + return response { handler in + completionHandler(handler.response, handler.request, handler.data, handler.error) + } + } + } +} + +extension DownloadRequest: Requestable { + internal func response(callbackQueue: DispatchQueue?, completionHandler: @escaping RequestableCompletion) -> Self { + if let callbackQueue = callbackQueue { + return response(queue: callbackQueue) { handler in + completionHandler(handler.response, handler.request, nil, handler.error) + } + } else { + return response { handler in + completionHandler(handler.response, handler.request, nil, handler.error) + } + } + } +} + +final class MoyaRequestInterceptor: RequestInterceptor { + var prepare: ((URLRequest) -> URLRequest)? + + @Atomic + var willSend: ((URLRequest) -> Void)? + + init(prepare: ((URLRequest) -> URLRequest)? = nil, willSend: ((URLRequest) -> Void)? = nil) { + self.prepare = prepare + self.willSend = willSend + } + + func adapt(_ urlRequest: URLRequest, for session: Alamofire.Session, completion: @escaping (Result) -> Void) { + let request = prepare?(urlRequest) ?? urlRequest + willSend?(request) + completion(.success(request)) + } +} diff --git a/Pods/Moya/Sources/Moya/MoyaError.swift b/Pods/Moya/Sources/Moya/MoyaError.swift new file mode 100644 index 0000000..4b16bd2 --- /dev/null +++ b/Pods/Moya/Sources/Moya/MoyaError.swift @@ -0,0 +1,102 @@ +import Foundation + +/// A type representing possible errors Moya can throw. +public enum MoyaError: Swift.Error { + + /// Indicates a response failed to map to an image. + case imageMapping(Response) + + /// Indicates a response failed to map to a JSON structure. + case jsonMapping(Response) + + /// Indicates a response failed to map to a String. + case stringMapping(Response) + + /// Indicates a response failed to map to a Decodable object. + case objectMapping(Swift.Error, Response) + + /// Indicates that Encodable couldn't be encoded into Data + case encodableMapping(Swift.Error) + + /// Indicates a response failed with an invalid HTTP status code. + case statusCode(Response) + + /// Indicates a response failed due to an underlying `Error`. + case underlying(Swift.Error, Response?) + + /// Indicates that an `Endpoint` failed to map to a `URLRequest`. + case requestMapping(String) + + /// Indicates that an `Endpoint` failed to encode the parameters for the `URLRequest`. + case parameterEncoding(Swift.Error) +} + +public extension MoyaError { + /// Depending on error type, returns a `Response` object. + var response: Moya.Response? { + switch self { + case .imageMapping(let response): return response + case .jsonMapping(let response): return response + case .stringMapping(let response): return response + case .objectMapping(_, let response): return response + case .encodableMapping: return nil + case .statusCode(let response): return response + case .underlying(_, let response): return response + case .requestMapping: return nil + case .parameterEncoding: return nil + } + } + + /// Depending on error type, returns an underlying `Error`. + internal var underlyingError: Swift.Error? { + switch self { + case .imageMapping: return nil + case .jsonMapping: return nil + case .stringMapping: return nil + case .objectMapping(let error, _): return error + case .encodableMapping(let error): return error + case .statusCode: return nil + case .underlying(let error, _): return error + case .requestMapping: return nil + case .parameterEncoding(let error): return error + } + } +} + +// MARK: - Error Descriptions + +extension MoyaError: LocalizedError { + public var errorDescription: String? { + switch self { + case .imageMapping: + return "Failed to map data to an Image." + case .jsonMapping: + return "Failed to map data to JSON." + case .stringMapping: + return "Failed to map data to a String." + case .objectMapping: + return "Failed to map data to a Decodable object." + case .encodableMapping: + return "Failed to encode Encodable object into data." + case .statusCode: + return "Status code didn't fall within the given range." + case .underlying(let error, _): + return error.localizedDescription + case .requestMapping: + return "Failed to map Endpoint to a URLRequest." + case .parameterEncoding(let error): + return "Failed to encode parameters for URLRequest. \(error.localizedDescription)" + } + } +} + +// MARK: - Error User Info + +extension MoyaError: CustomNSError { + public var errorUserInfo: [String: Any] { + var userInfo: [String: Any] = [:] + userInfo[NSLocalizedDescriptionKey] = errorDescription + userInfo[NSUnderlyingErrorKey] = underlyingError + return userInfo + } +} diff --git a/Pods/Moya/Sources/Moya/MoyaProvider+Defaults.swift b/Pods/Moya/Sources/Moya/MoyaProvider+Defaults.swift new file mode 100644 index 0000000..d0e9493 --- /dev/null +++ b/Pods/Moya/Sources/Moya/MoyaProvider+Defaults.swift @@ -0,0 +1,34 @@ +import Foundation + +/// These functions are default mappings to `MoyaProvider`'s properties: endpoints, requests, session etc. +public extension MoyaProvider { + final class func defaultEndpointMapping(for target: Target) -> Endpoint { + Endpoint( + url: URL(target: target).absoluteString, + sampleResponseClosure: { .networkResponse(200, target.sampleData) }, + method: target.method, + task: target.task, + httpHeaderFields: target.headers + ) + } + + final class func defaultRequestMapping(for endpoint: Endpoint, closure: RequestResultClosure) { + do { + let urlRequest = try endpoint.urlRequest() + closure(.success(urlRequest)) + } catch MoyaError.requestMapping(let url) { + closure(.failure(MoyaError.requestMapping(url))) + } catch MoyaError.parameterEncoding(let error) { + closure(.failure(MoyaError.parameterEncoding(error))) + } catch { + closure(.failure(MoyaError.underlying(error, nil))) + } + } + + final class func defaultAlamofireSession() -> Session { + let configuration = URLSessionConfiguration.default + configuration.headers = .default + + return Session(configuration: configuration, startRequestsImmediately: false) + } +} diff --git a/Pods/Moya/Sources/Moya/MoyaProvider+Internal.swift b/Pods/Moya/Sources/Moya/MoyaProvider+Internal.swift new file mode 100644 index 0000000..a36232d --- /dev/null +++ b/Pods/Moya/Sources/Moya/MoyaProvider+Internal.swift @@ -0,0 +1,296 @@ +import Foundation + +// MARK: - Method + +public extension Method { + /// A Boolean value determining whether the request supports multipart. + var supportsMultipart: Bool { + switch self { + case .post, .put, .patch, .connect: + return true + default: + return false + } + } +} + +// MARK: - MoyaProvider + +/// Internal extension to keep the inner-workings outside the main Moya.swift file. +public extension MoyaProvider { + /// Performs normal requests. + func requestNormal(_ target: Target, callbackQueue: DispatchQueue?, progress: Moya.ProgressBlock?, completion: @escaping Moya.Completion) -> Cancellable { + let endpoint = self.endpoint(target) + let stubBehavior = self.stubClosure(target) + let cancellableToken = CancellableWrapper() + + // Allow plugins to modify response + let pluginsWithCompletion: Moya.Completion = { result in + let processedResult = self.plugins.reduce(result) { $1.process($0, target: target) } + completion(processedResult) + } + + if trackInflights { + var inflightCompletionBlocks = self.inflightRequests[endpoint] + inflightCompletionBlocks?.append(pluginsWithCompletion) + self.internalInflightRequests[endpoint] = inflightCompletionBlocks + + if inflightCompletionBlocks != nil { + return cancellableToken + } else { + self.internalInflightRequests[endpoint] = [pluginsWithCompletion] + } + } + + let performNetworking = { (requestResult: Result) in + if cancellableToken.isCancelled { + self.cancelCompletion(pluginsWithCompletion, target: target) + return + } + + var request: URLRequest! + + switch requestResult { + case .success(let urlRequest): + request = urlRequest + case .failure(let error): + pluginsWithCompletion(.failure(error)) + return + } + + let networkCompletion: Moya.Completion = { result in + if self.trackInflights { + self.inflightRequests[endpoint]?.forEach { $0(result) } + self.internalInflightRequests.removeValue(forKey: endpoint) + } else { + pluginsWithCompletion(result) + } + } + + cancellableToken.innerCancellable = self.performRequest(target, request: request, callbackQueue: callbackQueue, progress: progress, completion: networkCompletion, endpoint: endpoint, stubBehavior: stubBehavior) + } + + requestClosure(endpoint, performNetworking) + + return cancellableToken + } + + // swiftlint:disable:next function_parameter_count + private func performRequest(_ target: Target, request: URLRequest, callbackQueue: DispatchQueue?, progress: Moya.ProgressBlock?, completion: @escaping Moya.Completion, endpoint: Endpoint, stubBehavior: Moya.StubBehavior) -> Cancellable { + switch stubBehavior { + case .never: + switch endpoint.task { + case .requestPlain, .requestData, .requestJSONEncodable, .requestCustomJSONEncodable, .requestParameters, .requestCompositeData, .requestCompositeParameters: + return self.sendRequest(target, request: request, callbackQueue: callbackQueue, progress: progress, completion: completion) + case .uploadFile(let file): + return self.sendUploadFile(target, request: request, callbackQueue: callbackQueue, file: file, progress: progress, completion: completion) + case .uploadMultipart(let multipartBody), .uploadCompositeMultipart(let multipartBody, _): + guard !multipartBody.isEmpty && endpoint.method.supportsMultipart else { + fatalError("\(target) is not a multipart upload target.") + } + return self.sendUploadMultipart(target, request: request, callbackQueue: callbackQueue, multipartBody: multipartBody, progress: progress, completion: completion) + case .downloadDestination(let destination), .downloadParameters(_, _, let destination): + return self.sendDownloadRequest(target, request: request, callbackQueue: callbackQueue, destination: destination, progress: progress, completion: completion) + } + default: + return self.stubRequest(target, request: request, callbackQueue: callbackQueue, completion: completion, endpoint: endpoint, stubBehavior: stubBehavior) + } + } + + func cancelCompletion(_ completion: Moya.Completion, target: Target) { + let error = MoyaError.underlying(NSError(domain: NSURLErrorDomain, code: NSURLErrorCancelled, userInfo: nil), nil) + plugins.forEach { $0.didReceive(.failure(error), target: target) } + completion(.failure(error)) + } + + /// Creates a function which, when called, executes the appropriate stubbing behavior for the given parameters. + final func createStubFunction(_ token: CancellableToken, forTarget target: Target, withCompletion completion: @escaping Moya.Completion, endpoint: Endpoint, plugins: [PluginType], request: URLRequest) -> (() -> Void) { // swiftlint:disable:this function_parameter_count + return { + if token.isCancelled { + self.cancelCompletion(completion, target: target) + return + } + + let validate = { (response: Moya.Response) -> Result in + let validCodes = target.validationType.statusCodes + guard !validCodes.isEmpty else { return .success(response) } + if validCodes.contains(response.statusCode) { + return .success(response) + } else { + let statusError = MoyaError.statusCode(response) + let error = MoyaError.underlying(statusError, response) + return .failure(error) + } + } + + switch endpoint.sampleResponseClosure() { + case .networkResponse(let statusCode, let data): + let response = Moya.Response(statusCode: statusCode, data: data, request: request, response: nil) + let result = validate(response) + plugins.forEach { $0.didReceive(result, target: target) } + completion(result) + case .response(let customResponse, let data): + let response = Moya.Response(statusCode: customResponse.statusCode, data: data, request: request, response: customResponse) + let result = validate(response) + plugins.forEach { $0.didReceive(result, target: target) } + completion(result) + case .networkError(let error): + let error = MoyaError.underlying(error, nil) + plugins.forEach { $0.didReceive(.failure(error), target: target) } + completion(.failure(error)) + } + } + } + + /// Notify all plugins that a stub is about to be performed. You must call this if overriding `stubRequest`. + final func notifyPluginsOfImpendingStub(for request: URLRequest, target: Target) -> URLRequest { + let alamoRequest = session.request(request) + alamoRequest.cancel() + + let preparedRequest = plugins.reduce(request) { $1.prepare($0, target: target) } + + let stubbedAlamoRequest = RequestTypeWrapper(request: alamoRequest, urlRequest: preparedRequest) + plugins.forEach { $0.willSend(stubbedAlamoRequest, target: target) } + + return preparedRequest + } +} + +private extension MoyaProvider { + private func interceptor(target: Target) -> MoyaRequestInterceptor { + return MoyaRequestInterceptor(prepare: { [weak self] urlRequest in + return self?.plugins.reduce(urlRequest) { $1.prepare($0, target: target) } ?? urlRequest + }) + } + + private func setup(interceptor: MoyaRequestInterceptor, with target: Target, and request: Request) { + interceptor.willSend = { [weak self, weak request] urlRequest in + guard let self = self, let request = request else { return } + + let stubbedAlamoRequest = RequestTypeWrapper(request: request, urlRequest: urlRequest) + self.plugins.forEach { $0.willSend(stubbedAlamoRequest, target: target) } + } + } + + func sendUploadMultipart(_ target: Target, request: URLRequest, callbackQueue: DispatchQueue?, multipartBody: [MultipartFormData], progress: Moya.ProgressBlock? = nil, completion: @escaping Moya.Completion) -> CancellableToken { + let formData = RequestMultipartFormData() + formData.applyMoyaMultipartFormData(multipartBody) + + let interceptor = self.interceptor(target: target) + let uploadRequest: UploadRequest = session.requestQueue.sync { + let uploadRequest = session.upload(multipartFormData: formData, with: request, interceptor: interceptor) + setup(interceptor: interceptor, with: target, and: uploadRequest) + + return uploadRequest + } + + let validationCodes = target.validationType.statusCodes + let validatedRequest = validationCodes.isEmpty ? uploadRequest : uploadRequest.validate(statusCode: validationCodes) + return sendAlamofireRequest(validatedRequest, target: target, callbackQueue: callbackQueue, progress: progress, completion: completion) + } + + func sendUploadFile(_ target: Target, request: URLRequest, callbackQueue: DispatchQueue?, file: URL, progress: ProgressBlock? = nil, completion: @escaping Completion) -> CancellableToken { + let interceptor = self.interceptor(target: target) + let uploadRequest: UploadRequest = session.requestQueue.sync { + let uploadRequest = session.upload(file, with: request, interceptor: interceptor) + setup(interceptor: interceptor, with: target, and: uploadRequest) + + return uploadRequest + } + + let validationCodes = target.validationType.statusCodes + let alamoRequest = validationCodes.isEmpty ? uploadRequest : uploadRequest.validate(statusCode: validationCodes) + return sendAlamofireRequest(alamoRequest, target: target, callbackQueue: callbackQueue, progress: progress, completion: completion) + } + + func sendDownloadRequest(_ target: Target, request: URLRequest, callbackQueue: DispatchQueue?, destination: @escaping DownloadDestination, progress: ProgressBlock? = nil, completion: @escaping Completion) -> CancellableToken { + let interceptor = self.interceptor(target: target) + let downloadRequest: DownloadRequest = session.requestQueue.sync { + let downloadRequest = session.download(request, interceptor: interceptor, to: destination) + setup(interceptor: interceptor, with: target, and: downloadRequest) + + return downloadRequest + } + + let validationCodes = target.validationType.statusCodes + let alamoRequest = validationCodes.isEmpty ? downloadRequest : downloadRequest.validate(statusCode: validationCodes) + return sendAlamofireRequest(alamoRequest, target: target, callbackQueue: callbackQueue, progress: progress, completion: completion) + } + + func sendRequest(_ target: Target, request: URLRequest, callbackQueue: DispatchQueue?, progress: Moya.ProgressBlock?, completion: @escaping Moya.Completion) -> CancellableToken { + let interceptor = self.interceptor(target: target) + let initialRequest: DataRequest = session.requestQueue.sync { + let initialRequest = session.request(request, interceptor: interceptor) + setup(interceptor: interceptor, with: target, and: initialRequest) + + return initialRequest + } + + let validationCodes = target.validationType.statusCodes + let alamoRequest = validationCodes.isEmpty ? initialRequest : initialRequest.validate(statusCode: validationCodes) + return sendAlamofireRequest(alamoRequest, target: target, callbackQueue: callbackQueue, progress: progress, completion: completion) + } + + // swiftlint:disable:next cyclomatic_complexity + func sendAlamofireRequest(_ alamoRequest: T, target: Target, callbackQueue: DispatchQueue?, progress progressCompletion: Moya.ProgressBlock?, completion: @escaping Moya.Completion) -> CancellableToken where T: Requestable, T: Request { + // Give plugins the chance to alter the outgoing request + let plugins = self.plugins + var progressAlamoRequest = alamoRequest + let progressClosure: (Progress) -> Void = { progress in + let sendProgress: () -> Void = { + progressCompletion?(ProgressResponse(progress: progress)) + } + + if let callbackQueue = callbackQueue { + callbackQueue.async(execute: sendProgress) + } else { + sendProgress() + } + } + + // Perform the actual request + if progressCompletion != nil { + switch progressAlamoRequest { + case let downloadRequest as DownloadRequest: + if let downloadRequest = downloadRequest.downloadProgress(closure: progressClosure) as? T { + progressAlamoRequest = downloadRequest + } + case let uploadRequest as UploadRequest: + if let uploadRequest = uploadRequest.uploadProgress(closure: progressClosure) as? T { + progressAlamoRequest = uploadRequest + } + case let dataRequest as DataRequest: + if let dataRequest = dataRequest.downloadProgress(closure: progressClosure) as? T { + progressAlamoRequest = dataRequest + } + default: break + } + } + + let completionHandler: RequestableCompletion = { response, request, data, error in + let result = convertResponseToResult(response, request: request, data: data, error: error) + // Inform all plugins about the response + plugins.forEach { $0.didReceive(result, target: target) } + if let progressCompletion = progressCompletion { + let value = try? result.get() + switch progressAlamoRequest { + case let downloadRequest as DownloadRequest: + progressCompletion(ProgressResponse(progress: downloadRequest.downloadProgress, response: value)) + case let uploadRequest as UploadRequest: + progressCompletion(ProgressResponse(progress: uploadRequest.uploadProgress, response: value)) + case let dataRequest as DataRequest: + progressCompletion(ProgressResponse(progress: dataRequest.downloadProgress, response: value)) + default: + progressCompletion(ProgressResponse(response: value)) + } + } + completion(result) + } + + progressAlamoRequest = progressAlamoRequest.response(callbackQueue: callbackQueue, completionHandler: completionHandler) + + progressAlamoRequest.resume() + + return CancellableToken(request: progressAlamoRequest) + } +} diff --git a/Pods/Moya/Sources/Moya/MoyaProvider.swift b/Pods/Moya/Sources/Moya/MoyaProvider.swift new file mode 100755 index 0000000..a2fef1d --- /dev/null +++ b/Pods/Moya/Sources/Moya/MoyaProvider.swift @@ -0,0 +1,212 @@ +import Foundation + +/// Closure to be executed when a request has completed. +public typealias Completion = (_ result: Result) -> Void + +/// Closure to be executed when progress changes. +public typealias ProgressBlock = (_ progress: ProgressResponse) -> Void + +/// A type representing the progress of a request. +public struct ProgressResponse { + + /// The optional response of the request. + public let response: Response? + + /// An object that conveys ongoing progress for a given request. + public let progressObject: Progress? + + /// Initializes a `ProgressResponse`. + public init(progress: Progress? = nil, response: Response? = nil) { + self.progressObject = progress + self.response = response + } + + /// The fraction of the overall work completed by the progress object. + public var progress: Double { + if completed { + return 1.0 + } else if let progressObject = progressObject, progressObject.totalUnitCount > 0 { + // if the Content-Length is specified we can rely on `fractionCompleted` + return progressObject.fractionCompleted + } else { + // if the Content-Length is not specified, return progress 0.0 until it's completed + return 0.0 + } + } + + /// A Boolean value stating whether the request is completed. + public var completed: Bool { response != nil } +} + +/// A protocol representing a minimal interface for a MoyaProvider. +/// Used by the reactive provider extensions. +public protocol MoyaProviderType: AnyObject { + + associatedtype Target: TargetType + + /// Designated request-making method. Returns a `Cancellable` token to cancel the request later. + func request(_ target: Target, callbackQueue: DispatchQueue?, progress: Moya.ProgressBlock?, completion: @escaping Moya.Completion) -> Cancellable +} + +/// Request provider class. Requests should be made through this class only. +open class MoyaProvider: MoyaProviderType { + + /// Closure that defines the endpoints for the provider. + public typealias EndpointClosure = (Target) -> Endpoint + + /// Closure that decides if and what request should be performed. + public typealias RequestResultClosure = (Result) -> Void + + /// Closure that resolves an `Endpoint` into a `RequestResult`. + public typealias RequestClosure = (Endpoint, @escaping RequestResultClosure) -> Void + + /// Closure that decides if/how a request should be stubbed. + public typealias StubClosure = (Target) -> Moya.StubBehavior + + /// A closure responsible for mapping a `TargetType` to an `EndPoint`. + public let endpointClosure: EndpointClosure + + /// A closure deciding if and what request should be performed. + public let requestClosure: RequestClosure + + /// A closure responsible for determining the stubbing behavior + /// of a request for a given `TargetType`. + public let stubClosure: StubClosure + + public let session: Session + + /// A list of plugins. + /// e.g. for logging, network activity indicator or credentials. + public let plugins: [PluginType] + + public let trackInflights: Bool + + open var inflightRequests: [Endpoint: [Moya.Completion]] { internalInflightRequests } + + @Atomic + var internalInflightRequests: [Endpoint: [Moya.Completion]] = [:] + + /// Propagated to Alamofire as callback queue. If nil - the Alamofire default (as of their API in 2017 - the main queue) will be used. + let callbackQueue: DispatchQueue? + + let lock: NSRecursiveLock = NSRecursiveLock() + + /// Initializes a provider. + public init(endpointClosure: @escaping EndpointClosure = MoyaProvider.defaultEndpointMapping, + requestClosure: @escaping RequestClosure = MoyaProvider.defaultRequestMapping, + stubClosure: @escaping StubClosure = MoyaProvider.neverStub, + callbackQueue: DispatchQueue? = nil, + session: Session = MoyaProvider.defaultAlamofireSession(), + plugins: [PluginType] = [], + trackInflights: Bool = false) { + + self.endpointClosure = endpointClosure + self.requestClosure = requestClosure + self.stubClosure = stubClosure + self.session = session + self.plugins = plugins + self.trackInflights = trackInflights + self.callbackQueue = callbackQueue + } + + /// Returns an `Endpoint` based on the token, method, and parameters by invoking the `endpointClosure`. + open func endpoint(_ token: Target) -> Endpoint { + endpointClosure(token) + } + + /// Designated request-making method. Returns a `Cancellable` token to cancel the request later. + @discardableResult + open func request(_ target: Target, + callbackQueue: DispatchQueue? = .none, + progress: ProgressBlock? = .none, + completion: @escaping Completion) -> Cancellable { + + let callbackQueue = callbackQueue ?? self.callbackQueue + return requestNormal(target, callbackQueue: callbackQueue, progress: progress, completion: completion) + } + + // swiftlint:disable function_parameter_count + /// When overriding this method, call `notifyPluginsOfImpendingStub` to prepare your request + /// and then use the returned `URLRequest` in the `createStubFunction` method. + /// Note: this was previously in an extension, however it must be in the original class declaration to allow subclasses to override. + @discardableResult + open func stubRequest(_ target: Target, request: URLRequest, callbackQueue: DispatchQueue?, completion: @escaping Moya.Completion, endpoint: Endpoint, stubBehavior: Moya.StubBehavior) -> CancellableToken { + let callbackQueue = callbackQueue ?? self.callbackQueue + let cancellableToken = CancellableToken { } + let preparedRequest = notifyPluginsOfImpendingStub(for: request, target: target) + let plugins = self.plugins + let stub: () -> Void = createStubFunction(cancellableToken, forTarget: target, withCompletion: completion, endpoint: endpoint, plugins: plugins, request: preparedRequest) + switch stubBehavior { + case .immediate: + switch callbackQueue { + case .none: + stub() + case .some(let callbackQueue): + callbackQueue.async(execute: stub) + } + case .delayed(let delay): + let killTimeOffset = Int64(CDouble(delay) * CDouble(NSEC_PER_SEC)) + let killTime = DispatchTime.now() + Double(killTimeOffset) / Double(NSEC_PER_SEC) + (callbackQueue ?? DispatchQueue.main).asyncAfter(deadline: killTime) { + stub() + } + case .never: + fatalError("Method called to stub request when stubbing is disabled.") + } + + return cancellableToken + } + // swiftlint:enable function_parameter_count +} + +// MARK: Stubbing + +/// Controls how stub responses are returned. +public enum StubBehavior { + + /// Do not stub. + case never + + /// Return a response immediately. + case immediate + + /// Return a response after a delay. + case delayed(seconds: TimeInterval) +} + +public extension MoyaProvider { + + // Swift won't let us put the StubBehavior enum inside the provider class, so we'll + // at least add some class functions to allow easy access to common stubbing closures. + + /// Do not stub. + final class func neverStub(_: Target) -> Moya.StubBehavior { .never } + + /// Return a response immediately. + final class func immediatelyStub(_: Target) -> Moya.StubBehavior { .immediate } + + /// Return a response after a delay. + final class func delayedStub(_ seconds: TimeInterval) -> (Target) -> Moya.StubBehavior { + return { _ in .delayed(seconds: seconds) } + } +} + +/// A public function responsible for converting the result of a `URLRequest` to a Result. +public func convertResponseToResult(_ response: HTTPURLResponse?, request: URLRequest?, data: Data?, error: Swift.Error?) -> + Result { + switch (response, data, error) { + case let (.some(response), data, .none): + let response = Moya.Response(statusCode: response.statusCode, data: data ?? Data(), request: request, response: response) + return .success(response) + case let (.some(response), _, .some(error)): + let response = Moya.Response(statusCode: response.statusCode, data: data ?? Data(), request: request, response: response) + let error = MoyaError.underlying(error, response) + return .failure(error) + case let (_, _, .some(error)): + let error = MoyaError.underlying(error, nil) + return .failure(error) + default: + let error = MoyaError.underlying(NSError(domain: NSURLErrorDomain, code: NSURLErrorUnknown, userInfo: nil), nil) + return .failure(error) + } +} diff --git a/Pods/Moya/Sources/Moya/MultiTarget.swift b/Pods/Moya/Sources/Moya/MultiTarget.swift new file mode 100644 index 0000000..d1f137e --- /dev/null +++ b/Pods/Moya/Sources/Moya/MultiTarget.swift @@ -0,0 +1,47 @@ +import Foundation + +/// A `TargetType` used to enable `MoyaProvider` to process multiple `TargetType`s. +public enum MultiTarget: TargetType { + /// The embedded `TargetType`. + case target(TargetType) + + /// Initializes a `MultiTarget`. + public init(_ target: TargetType) { + self = MultiTarget.target(target) + } + + /// The embedded target's base `URL`. + public var path: String { target.path } + + /// The baseURL of the embedded target. + public var baseURL: URL { target.baseURL } + + /// The HTTP method of the embedded target. + public var method: Moya.Method { target.method } + + /// The sampleData of the embedded target. + public var sampleData: Data { target.sampleData } + + /// The `Task` of the embedded target. + public var task: Task { target.task } + + /// The `ValidationType` of the embedded target. + public var validationType: ValidationType { target.validationType } + + /// The headers of the embedded target. + public var headers: [String: String]? { target.headers } + + /// The embedded `TargetType`. + public var target: TargetType { + switch self { + case .target(let target): return target + } + } +} + +extension MultiTarget: AccessTokenAuthorizable { + public var authorizationType: AuthorizationType? { + guard let authorizableTarget = target as? AccessTokenAuthorizable else { return nil } + return authorizableTarget.authorizationType + } +} diff --git a/Pods/Moya/Sources/Moya/MultipartFormData.swift b/Pods/Moya/Sources/Moya/MultipartFormData.swift new file mode 100644 index 0000000..e70d969 --- /dev/null +++ b/Pods/Moya/Sources/Moya/MultipartFormData.swift @@ -0,0 +1,65 @@ +import Foundation +import Alamofire + +/// Represents "multipart/form-data" for an upload. +public struct MultipartFormData: Hashable { + + /// Method to provide the form data. + public enum FormDataProvider: Hashable { + case data(Foundation.Data) + case file(URL) + case stream(InputStream, UInt64) + } + + public init(provider: FormDataProvider, name: String, fileName: String? = nil, mimeType: String? = nil) { + self.provider = provider + self.name = name + self.fileName = fileName + self.mimeType = mimeType + } + + /// The method being used for providing form data. + public let provider: FormDataProvider + + /// The name. + public let name: String + + /// The file name. + public let fileName: String? + + /// The MIME type + public let mimeType: String? + +} + +// MARK: RequestMultipartFormData appending +internal extension RequestMultipartFormData { + func append(data: Data, bodyPart: MultipartFormData) { + append(data, withName: bodyPart.name, fileName: bodyPart.fileName, mimeType: bodyPart.mimeType) + } + + func append(fileURL url: URL, bodyPart: MultipartFormData) { + if let fileName = bodyPart.fileName, let mimeType = bodyPart.mimeType { + append(url, withName: bodyPart.name, fileName: fileName, mimeType: mimeType) + } else { + append(url, withName: bodyPart.name) + } + } + + func append(stream: InputStream, length: UInt64, bodyPart: MultipartFormData) { + append(stream, withLength: length, name: bodyPart.name, fileName: bodyPart.fileName ?? "", mimeType: bodyPart.mimeType ?? "") + } + + func applyMoyaMultipartFormData(_ multipartBody: [Moya.MultipartFormData]) { + for bodyPart in multipartBody { + switch bodyPart.provider { + case .data(let data): + append(data: data, bodyPart: bodyPart) + case .file(let url): + append(fileURL: url, bodyPart: bodyPart) + case .stream(let stream, let length): + append(stream: stream, length: length, bodyPart: bodyPart) + } + } + } +} diff --git a/Pods/Moya/Sources/Moya/Plugin.swift b/Pods/Moya/Sources/Moya/Plugin.swift new file mode 100644 index 0000000..3bbe309 --- /dev/null +++ b/Pods/Moya/Sources/Moya/Plugin.swift @@ -0,0 +1,54 @@ +import Foundation + +/// A Moya Plugin receives callbacks to perform side effects wherever a request is sent or received. +/// +/// for example, a plugin may be used to +/// - log network requests +/// - hide and show a network activity indicator +/// - inject additional information into a request +public protocol PluginType { + /// Called to modify a request before sending. + func prepare(_ request: URLRequest, target: TargetType) -> URLRequest + + /// Called immediately before a request is sent over the network (or stubbed). + func willSend(_ request: RequestType, target: TargetType) + + /// Called after a response has been received, but before the MoyaProvider has invoked its completion handler. + func didReceive(_ result: Result, target: TargetType) + + /// Called to modify a result before completion. + func process(_ result: Result, target: TargetType) -> Result +} + +public extension PluginType { + func prepare(_ request: URLRequest, target: TargetType) -> URLRequest { request } + func willSend(_ request: RequestType, target: TargetType) { } + func didReceive(_ result: Result, target: TargetType) { } + func process(_ result: Result, target: TargetType) -> Result { result } +} + +/// Request type used by `willSend` plugin function. +public protocol RequestType { + + // Note: + // + // We use this protocol instead of the Alamofire request to avoid leaking that abstraction. + // A plugin should not know about Alamofire at all. + + /// Retrieve an `NSURLRequest` representation. + var request: URLRequest? { get } + + /// Additional headers appended to the request when added to the session. + var sessionHeaders: [String: String] { get } + + /// Authenticates the request with a username and password. + func authenticate(username: String, password: String, persistence: URLCredential.Persistence) -> Self + + /// Authenticates the request with an `NSURLCredential` instance. + func authenticate(with credential: URLCredential) -> Self + + /// cURL representation of the instance. + /// + /// - Returns: The cURL equivalent of the instance. + func cURLDescription(calling handler: @escaping (String) -> Void) -> Self +} diff --git a/Pods/Moya/Sources/Moya/Plugins/AccessTokenPlugin.swift b/Pods/Moya/Sources/Moya/Plugins/AccessTokenPlugin.swift new file mode 100644 index 0000000..faf2b92 --- /dev/null +++ b/Pods/Moya/Sources/Moya/Plugins/AccessTokenPlugin.swift @@ -0,0 +1,101 @@ +import Foundation + +// MARK: - AccessTokenAuthorizable + +/// A protocol for controlling the behavior of `AccessTokenPlugin`. +public protocol AccessTokenAuthorizable { + + /// Represents the authorization header to use for requests. + var authorizationType: AuthorizationType? { get } +} + +// MARK: - AuthorizationType + +/// An enum representing the header to use with an `AccessTokenPlugin` +public enum AuthorizationType { + + /// The `"Basic"` header. + case basic + + /// The `"Bearer"` header. + case bearer + + /// Custom header implementation. + case custom(String) + + public var value: String { + switch self { + case .basic: return "Basic" + case .bearer: return "Bearer" + case .custom(let customValue): return customValue + } + } +} + +extension AuthorizationType: Equatable { + public static func == (lhs: AuthorizationType, rhs: AuthorizationType) -> Bool { + switch (lhs, rhs) { + case (.basic, .basic), + (.bearer, .bearer): + return true + + case let (.custom(value1), .custom(value2)): + return value1 == value2 + + default: + return false + } + } +} + +// MARK: - AccessTokenPlugin + +/** + A plugin for adding basic or bearer-type authorization headers to requests. Example: + + ``` + Authorization: Basic + Authorization: Bearer + Authorization: <Сustom> + ``` + + */ +public struct AccessTokenPlugin: PluginType { + + public typealias TokenClosure = (TargetType) -> String + + /// A closure returning the access token to be applied in the header. + public let tokenClosure: TokenClosure + + /** + Initialize a new `AccessTokenPlugin`. + + - parameters: + - tokenClosure: A closure returning the token to be applied in the pattern `Authorization: ` + */ + public init(tokenClosure: @escaping TokenClosure) { + self.tokenClosure = tokenClosure + } + + /** + Prepare a request by adding an authorization header if necessary. + + - parameters: + - request: The request to modify. + - target: The target of the request. + - returns: The modified `URLRequest`. + */ + public func prepare(_ request: URLRequest, target: TargetType) -> URLRequest { + + guard let authorizable = target as? AccessTokenAuthorizable, + let authorizationType = authorizable.authorizationType + else { return request } + + var request = request + let realTarget = (target as? MultiTarget)?.target ?? target + let authValue = authorizationType.value + " " + tokenClosure(realTarget) + request.addValue(authValue, forHTTPHeaderField: "Authorization") + + return request + } +} diff --git a/Pods/Moya/Sources/Moya/Plugins/CredentialsPlugin.swift b/Pods/Moya/Sources/Moya/Plugins/CredentialsPlugin.swift new file mode 100644 index 0000000..88e1015 --- /dev/null +++ b/Pods/Moya/Sources/Moya/Plugins/CredentialsPlugin.swift @@ -0,0 +1,21 @@ +import Foundation + +/// Provides each request with optional URLCredentials. +public final class CredentialsPlugin: PluginType { + + public typealias CredentialClosure = (TargetType) -> URLCredential? + let credentialsClosure: CredentialClosure + + /// Initializes a CredentialsPlugin. + public init(credentialsClosure: @escaping CredentialClosure) { + self.credentialsClosure = credentialsClosure + } + + // MARK: Plugin + + public func willSend(_ request: RequestType, target: TargetType) { + if let credentials = credentialsClosure(target) { + _ = request.authenticate(with: credentials) + } + } +} diff --git a/Pods/Moya/Sources/Moya/Plugins/NetworkActivityPlugin.swift b/Pods/Moya/Sources/Moya/Plugins/NetworkActivityPlugin.swift new file mode 100644 index 0000000..988e90f --- /dev/null +++ b/Pods/Moya/Sources/Moya/Plugins/NetworkActivityPlugin.swift @@ -0,0 +1,30 @@ +import Foundation + +/// Network activity change notification type. +public enum NetworkActivityChangeType { + case began, ended +} + +/// Notify a request's network activity changes (request begins or ends). +public final class NetworkActivityPlugin: PluginType { + + public typealias NetworkActivityClosure = (_ change: NetworkActivityChangeType, _ target: TargetType) -> Void + let networkActivityClosure: NetworkActivityClosure + + /// Initializes a NetworkActivityPlugin. + public init(networkActivityClosure: @escaping NetworkActivityClosure) { + self.networkActivityClosure = networkActivityClosure + } + + // MARK: Plugin + + /// Called by the provider as soon as the request is about to start + public func willSend(_ request: RequestType, target: TargetType) { + networkActivityClosure(.began, target) + } + + /// Called by the provider as soon as a response arrives, even if the request is canceled. + public func didReceive(_ result: Result, target: TargetType) { + networkActivityClosure(.ended, target) + } +} diff --git a/Pods/Moya/Sources/Moya/Plugins/NetworkLoggerPlugin.swift b/Pods/Moya/Sources/Moya/Plugins/NetworkLoggerPlugin.swift new file mode 100644 index 0000000..90dfae5 --- /dev/null +++ b/Pods/Moya/Sources/Moya/Plugins/NetworkLoggerPlugin.swift @@ -0,0 +1,249 @@ +import Foundation + +/// Logs network activity (outgoing requests and incoming responses). +public final class NetworkLoggerPlugin { + + public var configuration: Configuration + + /// Initializes a NetworkLoggerPlugin. + public init(configuration: Configuration = Configuration()) { + self.configuration = configuration + } +} + +// MARK: - PluginType +extension NetworkLoggerPlugin: PluginType { + public func willSend(_ request: RequestType, target: TargetType) { + logNetworkRequest(request, target: target) { [weak self] output in + self?.configuration.output(target, output) + } + } + + public func didReceive(_ result: Result, target: TargetType) { + switch result { + case .success(let response): + configuration.output(target, logNetworkResponse(response, target: target, isFromError: false)) + case let .failure(error): + configuration.output(target, logNetworkError(error, target: target)) + } + } +} + +// MARK: - Logging +private extension NetworkLoggerPlugin { + + func logNetworkRequest(_ request: RequestType, target: TargetType, completion: @escaping ([String]) -> Void) { + //cURL formatting + if configuration.logOptions.contains(.formatRequestAscURL) { + _ = request.cURLDescription { [weak self] output in + guard let self = self else { return } + + completion([self.configuration.formatter.entry("Request", output, target)]) + } + return + } + + //Request presence check + guard let httpRequest = request.request else { + completion([configuration.formatter.entry("Request", "(invalid request)", target)]) + return + } + + // Adding log entries for each given log option + var output = [String]() + + output.append(configuration.formatter.entry("Request", httpRequest.description, target)) + + if configuration.logOptions.contains(.requestHeaders) { + var allHeaders = request.sessionHeaders + if let httpRequestHeaders = httpRequest.allHTTPHeaderFields { + allHeaders.merge(httpRequestHeaders) { $1 } + } + output.append(configuration.formatter.entry("Request Headers", allHeaders.description, target)) + } + + if configuration.logOptions.contains(.requestBody) { + if let bodyStream = httpRequest.httpBodyStream { + output.append(configuration.formatter.entry("Request Body Stream", bodyStream.description, target)) + } + + if let body = httpRequest.httpBody { + let stringOutput = configuration.formatter.requestData(body) + output.append(configuration.formatter.entry("Request Body", stringOutput, target)) + } + } + + if configuration.logOptions.contains(.requestMethod), + let httpMethod = httpRequest.httpMethod { + output.append(configuration.formatter.entry("HTTP Request Method", httpMethod, target)) + } + + completion(output) + } + + func logNetworkResponse(_ response: Response, target: TargetType, isFromError: Bool) -> [String] { + // Adding log entries for each given log option + var output = [String]() + + //Response presence check + if let httpResponse = response.response { + output.append(configuration.formatter.entry("Response", httpResponse.description, target)) + } else { + output.append(configuration.formatter.entry("Response", "Received empty network response for \(target).", target)) + } + + if (isFromError && configuration.logOptions.contains(.errorResponseBody)) + || configuration.logOptions.contains(.successResponseBody) { + + let stringOutput = configuration.formatter.responseData(response.data) + output.append(configuration.formatter.entry("Response Body", stringOutput, target)) + } + + return output + } + + func logNetworkError(_ error: MoyaError, target: TargetType) -> [String] { + //Some errors will still have a response, like errors due to Alamofire's HTTP code validation. + if let moyaResponse = error.response { + return logNetworkResponse(moyaResponse, target: target, isFromError: true) + } + + //Errors without an HTTPURLResponse are those due to connectivity, time-out and such. + return [configuration.formatter.entry("Error", "Error calling \(target) : \(error)", target)] + } +} + +// MARK: - Configuration +public extension NetworkLoggerPlugin { + struct Configuration { + + // MARK: - Typealiases + // swiftlint:disable nesting + public typealias OutputType = (_ target: TargetType, _ items: [String]) -> Void + // swiftlint:enable nesting + + // MARK: - Properties + + public var formatter: Formatter + public var output: OutputType + public var logOptions: LogOptions + + /// The designated way to instantiate a Configuration. + /// + /// - Parameters: + /// - formatter: An object holding all formatter closures available for customization. + /// - output: A closure responsible for writing the given log entries into your log system. + /// The default value writes entries to the debug console. + /// - logOptions: A set of options you can use to customize which request component is logged. + public init(formatter: Formatter = Formatter(), + output: @escaping OutputType = defaultOutput, + logOptions: LogOptions = .default) { + self.formatter = formatter + self.output = output + self.logOptions = logOptions + } + + // MARK: - Defaults + + public static func defaultOutput(target: TargetType, items: [String]) { + for item in items { + print(item, separator: ",", terminator: "\n") + } + } + } +} + +public extension NetworkLoggerPlugin.Configuration { + struct LogOptions: OptionSet { + public let rawValue: Int + public init(rawValue: Int) { self.rawValue = rawValue } + + /// The request's method will be logged. + public static let requestMethod: LogOptions = LogOptions(rawValue: 1 << 0) + /// The request's body will be logged. + public static let requestBody: LogOptions = LogOptions(rawValue: 1 << 1) + /// The request's headers will be logged. + public static let requestHeaders: LogOptions = LogOptions(rawValue: 1 << 2) + /// The request will be logged in the cURL format. + /// + /// If this option is used, the following components will be logged regardless of their respective options being set: + /// - request's method + /// - request's headers + /// - request's body. + public static let formatRequestAscURL: LogOptions = LogOptions(rawValue: 1 << 3) + /// The body of a response that is a success will be logged. + public static let successResponseBody: LogOptions = LogOptions(rawValue: 1 << 4) + /// The body of a response that is an error will be logged. + public static let errorResponseBody: LogOptions = LogOptions(rawValue: 1 << 5) + + //Aggregate options + /// Only basic components will be logged. + public static let `default`: LogOptions = [requestMethod, requestHeaders] + /// All components will be logged. + public static let verbose: LogOptions = [requestMethod, requestHeaders, requestBody, + successResponseBody, errorResponseBody] + } +} + +public extension NetworkLoggerPlugin.Configuration { + struct Formatter { + + // MARK: Typealiases + // swiftlint:disable nesting + public typealias DataFormatterType = (Data) -> (String) + public typealias EntryFormatterType = (_ identifier: String, _ message: String, _ target: TargetType) -> String + // swiftlint:enable nesting + + // MARK: Properties + + public var entry: EntryFormatterType + public var requestData: DataFormatterType + public var responseData: DataFormatterType + + /// The designated way to instantiate a Formatter. + /// + /// - Parameters: + /// - entry: The closure formatting a message into a new log entry. + /// - requestData: The closure converting HTTP request's body into a String. + /// The default value assumes the body's data is an utf8 String. + /// - responseData: The closure converting HTTP response's body into a String. + /// The default value assumes the body's data is an utf8 String. + public init(entry: @escaping EntryFormatterType = defaultEntryFormatter, + requestData: @escaping DataFormatterType = defaultDataFormatter, + responseData: @escaping DataFormatterType = defaultDataFormatter) { + self.entry = entry + self.requestData = requestData + self.responseData = responseData + } + + // MARK: Defaults + + public static func defaultDataFormatter(_ data: Data) -> String { + return String(data: data, encoding: .utf8) ?? "## Cannot map data to String ##" + } + + public static func defaultEntryFormatter(identifier: String, message: String, target: TargetType) -> String { + let date = defaultEntryDateFormatter.string(from: Date()) + return "Moya_Logger: [\(date)] \(identifier): \(message)" + } + + static var defaultEntryDateFormatter: DateFormatter = { + let formatter = DateFormatter() + formatter.timeStyle = .short + formatter.dateStyle = .short + return formatter + }() + } +} + +public extension NetworkLoggerPlugin { + /// Returns the default logger plugin + class var `default`: NetworkLoggerPlugin { + return NetworkLoggerPlugin(configuration: Configuration(logOptions: .default)) + } + + /// Returns the default verbose logger plugin + class var verbose: NetworkLoggerPlugin { + return NetworkLoggerPlugin(configuration: Configuration(logOptions: .verbose)) + } +} diff --git a/Pods/Moya/Sources/Moya/RequestTypeWrapper.swift b/Pods/Moya/Sources/Moya/RequestTypeWrapper.swift new file mode 100644 index 0000000..263d8b2 --- /dev/null +++ b/Pods/Moya/Sources/Moya/RequestTypeWrapper.swift @@ -0,0 +1,32 @@ +import Foundation + +// Workaround for new asynchronous handling of Alamofire's request creation. +struct RequestTypeWrapper: RequestType { + + var request: URLRequest? { _urlRequest } + + var sessionHeaders: [String: String] { _request.sessionHeaders } + + private var _request: Request + private var _urlRequest: URLRequest? + + init(request: Request, urlRequest: URLRequest?) { + self._request = request + self._urlRequest = urlRequest + } + + func authenticate(username: String, password: String, persistence: URLCredential.Persistence) -> RequestTypeWrapper { + let newRequest = _request.authenticate(username: username, password: password, persistence: persistence) + return RequestTypeWrapper(request: newRequest, urlRequest: _urlRequest) + } + + func authenticate(with credential: URLCredential) -> RequestTypeWrapper { + let newRequest = _request.authenticate(with: credential) + return RequestTypeWrapper(request: newRequest, urlRequest: _urlRequest) + } + + func cURLDescription(calling handler: @escaping (String) -> Void) -> RequestTypeWrapper { + _request.cURLDescription(calling: handler) + return self + } +} diff --git a/Pods/Moya/Sources/Moya/Response.swift b/Pods/Moya/Sources/Moya/Response.swift new file mode 100644 index 0000000..c2fe12a --- /dev/null +++ b/Pods/Moya/Sources/Moya/Response.swift @@ -0,0 +1,190 @@ +import Foundation + +/// Represents a response to a `MoyaProvider.request`. +public final class Response: CustomDebugStringConvertible, Equatable { + + /// The status code of the response. + public let statusCode: Int + + /// The response data. + public let data: Data + + /// The original URLRequest for the response. + public let request: URLRequest? + + /// The HTTPURLResponse object. + public let response: HTTPURLResponse? + + public init(statusCode: Int, data: Data, request: URLRequest? = nil, response: HTTPURLResponse? = nil) { + self.statusCode = statusCode + self.data = data + self.request = request + self.response = response + } + + /// A text description of the `Response`. + public var description: String { + "Status Code: \(statusCode), Data Length: \(data.count)" + } + + /// A text description of the `Response`. Suitable for debugging. + public var debugDescription: String { description } + + public static func == (lhs: Response, rhs: Response) -> Bool { + lhs.statusCode == rhs.statusCode + && lhs.data == rhs.data + && lhs.response == rhs.response + } +} + +public extension Response { + + /** + Returns the `Response` if the `statusCode` falls within the specified range. + + - parameters: + - statusCodes: The range of acceptable status codes. + - throws: `MoyaError.statusCode` when others are encountered. + */ + func filter(statusCodes: R) throws -> Response where R.Bound == Int { + guard statusCodes.contains(statusCode) else { + throw MoyaError.statusCode(self) + } + return self + } + + /** + Returns the `Response` if it has the specified `statusCode`. + + - parameters: + - statusCode: The acceptable status code. + - throws: `MoyaError.statusCode` when others are encountered. + */ + func filter(statusCode: Int) throws -> Response { + try filter(statusCodes: statusCode...statusCode) + } + + /** + Returns the `Response` if the `statusCode` falls within the range 200 - 299. + + - throws: `MoyaError.statusCode` when others are encountered. + */ + func filterSuccessfulStatusCodes() throws -> Response { + try filter(statusCodes: 200...299) + } + + /** + Returns the `Response` if the `statusCode` falls within the range 200 - 399. + + - throws: `MoyaError.statusCode` when others are encountered. + */ + func filterSuccessfulStatusAndRedirectCodes() throws -> Response { + try filter(statusCodes: 200...399) + } + + /// Maps data received from the signal into an Image. + func mapImage() throws -> Image { + guard let image = Image(data: data) else { + throw MoyaError.imageMapping(self) + } + return image + } + + /// Maps data received from the signal into a JSON object. + /// + /// - parameter failsOnEmptyData: A Boolean value determining + /// whether the mapping should fail if the data is empty. + func mapJSON(failsOnEmptyData: Bool = true) throws -> Any { + do { + return try JSONSerialization.jsonObject(with: data, options: .allowFragments) + } catch { + if data.isEmpty && !failsOnEmptyData { + return NSNull() + } + throw MoyaError.jsonMapping(self) + } + } + + /// Maps data received from the signal into a String. + /// + /// - parameter atKeyPath: Optional key path at which to parse string. + func mapString(atKeyPath keyPath: String? = nil) throws -> String { + if let keyPath = keyPath { + // Key path was provided, try to parse string at key path + guard let jsonDictionary = try mapJSON() as? NSDictionary, + let string = jsonDictionary.value(forKeyPath: keyPath) as? String else { + throw MoyaError.stringMapping(self) + } + return string + } else { + // Key path was not provided, parse entire response as string + guard let string = String(data: data, encoding: .utf8) else { + throw MoyaError.stringMapping(self) + } + return string + } + } + + /// Maps data received from the signal into a Decodable object. + /// + /// - parameter atKeyPath: Optional key path at which to parse object. + /// - parameter using: A `JSONDecoder` instance which is used to decode data to an object. + func map(_ type: D.Type, atKeyPath keyPath: String? = nil, using decoder: JSONDecoder = JSONDecoder(), failsOnEmptyData: Bool = true) throws -> D { + let serializeToData: (Any) throws -> Data? = { (jsonObject) in + guard JSONSerialization.isValidJSONObject(jsonObject) else { + return nil + } + do { + return try JSONSerialization.data(withJSONObject: jsonObject) + } catch { + throw MoyaError.jsonMapping(self) + } + } + let jsonData: Data + keyPathCheck: if let keyPath = keyPath { + guard let jsonObject = (try mapJSON(failsOnEmptyData: failsOnEmptyData) as? NSDictionary)?.value(forKeyPath: keyPath) else { + if failsOnEmptyData { + throw MoyaError.jsonMapping(self) + } else { + jsonData = data + break keyPathCheck + } + } + + if let data = try serializeToData(jsonObject) { + jsonData = data + } else { + let wrappedJsonObject = ["value": jsonObject] + let wrappedJsonData: Data + if let data = try serializeToData(wrappedJsonObject) { + wrappedJsonData = data + } else { + throw MoyaError.jsonMapping(self) + } + do { + return try decoder.decode(DecodableWrapper.self, from: wrappedJsonData).value + } catch let error { + throw MoyaError.objectMapping(error, self) + } + } + } else { + jsonData = data + } + do { + if jsonData.isEmpty && !failsOnEmptyData { + if let emptyJSONObjectData = "{}".data(using: .utf8), let emptyDecodableValue = try? decoder.decode(D.self, from: emptyJSONObjectData) { + return emptyDecodableValue + } else if let emptyJSONArrayData = "[{}]".data(using: .utf8), let emptyDecodableValue = try? decoder.decode(D.self, from: emptyJSONArrayData) { + return emptyDecodableValue + } + } + return try decoder.decode(D.self, from: jsonData) + } catch let error { + throw MoyaError.objectMapping(error, self) + } + } +} + +private struct DecodableWrapper: Decodable { + let value: T +} diff --git a/Pods/Moya/Sources/Moya/TargetType.swift b/Pods/Moya/Sources/Moya/TargetType.swift new file mode 100644 index 0000000..930b375 --- /dev/null +++ b/Pods/Moya/Sources/Moya/TargetType.swift @@ -0,0 +1,35 @@ +import Foundation + +/// The protocol used to define the specifications necessary for a `MoyaProvider`. +public protocol TargetType { + + /// The target's base `URL`. + var baseURL: URL { get } + + /// The path to be appended to `baseURL` to form the full `URL`. + var path: String { get } + + /// The HTTP method used in the request. + var method: Moya.Method { get } + + /// Provides stub data for use in testing. Default is `Data()`. + var sampleData: Data { get } + + /// The type of HTTP task to be performed. + var task: Task { get } + + /// The type of validation to perform on the request. Default is `.none`. + var validationType: ValidationType { get } + + /// The headers to be used in the request. + var headers: [String: String]? { get } +} + +public extension TargetType { + + /// The type of validation to perform on the request. Default is `.none`. + var validationType: ValidationType { .none } + + /// Provides stub data for use in testing. Default is `Data()`. + var sampleData: Data { Data() } +} diff --git a/Pods/Moya/Sources/Moya/Task.swift b/Pods/Moya/Sources/Moya/Task.swift new file mode 100644 index 0000000..191e259 --- /dev/null +++ b/Pods/Moya/Sources/Moya/Task.swift @@ -0,0 +1,41 @@ +import Foundation + +/// Represents an HTTP task. +public enum Task { + + /// A request with no additional data. + case requestPlain + + /// A requests body set with data. + case requestData(Data) + + /// A request body set with `Encodable` type + case requestJSONEncodable(Encodable) + + /// A request body set with `Encodable` type and custom encoder + case requestCustomJSONEncodable(Encodable, encoder: JSONEncoder) + + /// A requests body set with encoded parameters. + case requestParameters(parameters: [String: Any], encoding: ParameterEncoding) + + /// A requests body set with data, combined with url parameters. + case requestCompositeData(bodyData: Data, urlParameters: [String: Any]) + + /// A requests body set with encoded parameters combined with url parameters. + case requestCompositeParameters(bodyParameters: [String: Any], bodyEncoding: ParameterEncoding, urlParameters: [String: Any]) + + /// A file upload task. + case uploadFile(URL) + + /// A "multipart/form-data" upload task. + case uploadMultipart([MultipartFormData]) + + /// A "multipart/form-data" upload task combined with url parameters. + case uploadCompositeMultipart([MultipartFormData], urlParameters: [String: Any]) + + /// A file download task to a destination. + case downloadDestination(DownloadDestination) + + /// A file download task to a destination with extra parameters using the given encoding. + case downloadParameters(parameters: [String: Any], encoding: ParameterEncoding, destination: DownloadDestination) +} diff --git a/Pods/Moya/Sources/Moya/URL+Moya.swift b/Pods/Moya/Sources/Moya/URL+Moya.swift new file mode 100644 index 0000000..0c1303c --- /dev/null +++ b/Pods/Moya/Sources/Moya/URL+Moya.swift @@ -0,0 +1,17 @@ +import Foundation + +public extension URL { + + /// Initialize URL from Moya's `TargetType`. + init(target: T) { + // When a TargetType's path is empty, URL.appendingPathComponent may introduce trailing /, which may not be wanted in some cases + // See: https://github.com/Moya/Moya/pull/1053 + // And: https://github.com/Moya/Moya/issues/1049 + let targetPath = target.path + if targetPath.isEmpty { + self = target.baseURL + } else { + self = target.baseURL.appendingPathComponent(targetPath) + } + } +} diff --git a/Pods/Moya/Sources/Moya/URLRequest+Encoding.swift b/Pods/Moya/Sources/Moya/URLRequest+Encoding.swift new file mode 100644 index 0000000..232d86d --- /dev/null +++ b/Pods/Moya/Sources/Moya/URLRequest+Encoding.swift @@ -0,0 +1,28 @@ +import Foundation + +internal extension URLRequest { + + mutating func encoded(encodable: Encodable, encoder: JSONEncoder = JSONEncoder()) throws -> URLRequest { + do { + let encodable = AnyEncodable(encodable) + httpBody = try encoder.encode(encodable) + + let contentTypeHeaderName = "Content-Type" + if value(forHTTPHeaderField: contentTypeHeaderName) == nil { + setValue("application/json", forHTTPHeaderField: contentTypeHeaderName) + } + + return self + } catch { + throw MoyaError.encodableMapping(error) + } + } + + func encoded(parameters: [String: Any], parameterEncoding: ParameterEncoding) throws -> URLRequest { + do { + return try parameterEncoding.encode(self, with: parameters) + } catch { + throw MoyaError.parameterEncoding(error) + } + } +} diff --git a/Pods/Moya/Sources/Moya/ValidationType.swift b/Pods/Moya/Sources/Moya/ValidationType.swift new file mode 100644 index 0000000..ffc8d8f --- /dev/null +++ b/Pods/Moya/Sources/Moya/ValidationType.swift @@ -0,0 +1,47 @@ +import Foundation + +/// Represents the status codes to validate through Alamofire. +public enum ValidationType { + + /// No validation. + case none + + /// Validate success codes (only 2xx). + case successCodes + + /// Validate success codes and redirection codes (only 2xx and 3xx). + case successAndRedirectCodes + + /// Validate only the given status codes. + case customCodes([Int]) + + /// The list of HTTP status codes to validate. + var statusCodes: [Int] { + switch self { + case .successCodes: + return Array(200..<300) + case .successAndRedirectCodes: + return Array(200..<400) + case .customCodes(let codes): + return codes + case .none: + return [] + } + } +} + +extension ValidationType: Equatable { + + public static func == (lhs: ValidationType, rhs: ValidationType) -> Bool { + switch (lhs, rhs) { + case (.none, .none), + (.successCodes, .successCodes), + (.successAndRedirectCodes, .successAndRedirectCodes): + return true + case (.customCodes(let code1), .customCodes(let code2)): + return code1 == code2 + default: + return false + } + } +} diff --git a/Pods/Pods.xcodeproj/project.pbxproj b/Pods/Pods.xcodeproj/project.pbxproj new file mode 100644 index 0000000..b737ea2 --- /dev/null +++ b/Pods/Pods.xcodeproj/project.pbxproj @@ -0,0 +1,4341 @@ +// !$*UTF8*$! +{ + archiveVersion = 1; + classes = { + }; + objectVersion = 56; + objects = { + +/* Begin PBXBuildFile section */ + 0024FB3EA4398F0CCE435DF4134077AB /* RxRelay-dummy.m in Sources */ = {isa = PBXBuildFile; fileRef = BA8EAB6201729627D3C7299F26D4EE54 /* RxRelay-dummy.m */; }; + 0097064E7F7D3F413161738CC5C25EEC /* MBProgressHUD.m in Sources */ = {isa = PBXBuildFile; fileRef = 56969AC68B2EED540B9FBF1E0D237B8D /* MBProgressHUD.m */; }; + 00A2749F46C967ED4725A32357E3FB1B /* ConstraintLayoutSupport.swift in Sources */ = {isa = PBXBuildFile; fileRef = E60F8ED3C26A4DFE0400C21FB2BE072B /* ConstraintLayoutSupport.swift */; }; + 02560F1312F13EF15E0EB5FA952C9A48 /* PointerType.swift in Sources */ = {isa = PBXBuildFile; fileRef = 6AB41D31B155EAB764A9C053A0DE59CD /* PointerType.swift */; }; + 034A1879FF63C73CC22689EC8CBECBBC /* RetryStrategy.swift in Sources */ = {isa = PBXBuildFile; fileRef = 553E529F93F751DF0489E958694F11D8 /* RetryStrategy.swift */; }; + 044973538553B114516678D144E318CA /* Serializer.swift in Sources */ = {isa = PBXBuildFile; fileRef = A0989B49F85763612695C610DDE3995F /* Serializer.swift */; }; + 04637C70546B34F93C3A1D79C3F78B37 /* ConstraintDirectionalInsetTarget.swift in Sources */ = {isa = PBXBuildFile; fileRef = CBB2733EB8602C8BA1DE249204349BBB /* ConstraintDirectionalInsetTarget.swift */; }; + 04A8430BFC619C34E5F4D3878D094380 /* CachedResponseHandler.swift in Sources */ = {isa = PBXBuildFile; fileRef = 54C7D8C91C6BD127E758FD153F5CAE2A /* CachedResponseHandler.swift */; }; + 057D0EC1E728D714A73210ACAF1FAC6A /* UISearchBar+Rx.swift in Sources */ = {isa = PBXBuildFile; fileRef = 0F1253A739AF193B8223BE13ABA2A2BE /* UISearchBar+Rx.swift */; }; + 0591132B5EA1BE4DDA268D8A9C3D0421 /* LayoutConstraint.swift in Sources */ = {isa = PBXBuildFile; fileRef = A6785DD60F3F01E17A54F423E8397E23 /* LayoutConstraint.swift */; }; + 0618E661B571A4FCC8B886F792E756CE /* MoyaProvider.swift in Sources */ = {isa = PBXBuildFile; fileRef = 6EA8E69F4FC1AD4BC47B9FAA09D391D1 /* MoyaProvider.swift */; }; + 06E43B4751069B47B3BD4AFD936A57E3 /* ConstraintPriority.swift in Sources */ = {isa = PBXBuildFile; fileRef = 834ED77A734859A8A9236980263E4AF4 /* ConstraintPriority.swift */; }; + 07550E0A8451CACE9593873C543F1B78 /* RxTabBarControllerDelegateProxy.swift in Sources */ = {isa = PBXBuildFile; fileRef = 881FD56231A6918A0EAD0806FB1D9A18 /* RxTabBarControllerDelegateProxy.swift */; }; + 079F0820555C5B86C9FBD5EC6344137F /* Protected.swift in Sources */ = {isa = PBXBuildFile; fileRef = 518597BD67B90E044EDCA15142FA2D54 /* Protected.swift */; }; + 07C677042BB048A9440E13D5EEB8DC0E /* AnimatedImageView.swift in Sources */ = {isa = PBXBuildFile; fileRef = DB2C7BCF3EA896AC2BAD9CAD275BB460 /* AnimatedImageView.swift */; }; + 0833E66E7F19849322305D67777B77DB /* Foundation.framework in Frameworks */ = {isa = PBXBuildFile; fileRef = 6A1970A14C2672638850C555C17ADE89 /* Foundation.framework */; }; + 08923846D88DF3ED6D918079C91116C6 /* ImageFormat.swift in Sources */ = {isa = PBXBuildFile; fileRef = 7965E10A5058A7FDC743C628B6A209E4 /* ImageFormat.swift */; }; + 0907413AF1BF312948C6CA8289CE29AE /* ControlProperty.swift in Sources */ = {isa = PBXBuildFile; fileRef = 588185259F665B2270B61BC5EEEDB105 /* ControlProperty.swift */; }; + 094F725274CC4EC8EB2F0D2551C26019 /* ObserveOn.swift in Sources */ = {isa = PBXBuildFile; fileRef = BC12D927E7A7FFE4391A073866062EF0 /* ObserveOn.swift */; }; + 0A1E7F06A1E1CA1DE2B389E6AE0A66A0 /* Indicator.swift in Sources */ = {isa = PBXBuildFile; fileRef = 31BB5D3806E36F2811C5F7E9C7E0A00B /* Indicator.swift */; }; + 0A50200D02E79569C5EAFEDE5448DEA8 /* PublishRelay.swift in Sources */ = {isa = PBXBuildFile; fileRef = 52F042037CA28D5A455E060DD097C638 /* PublishRelay.swift */; }; + 0A7B97BD9262E628FCF5684C817D3D73 /* ObserverType.swift in Sources */ = {isa = PBXBuildFile; fileRef = 2DAB2159DEB43FA519F6B8254AF5728E /* ObserverType.swift */; }; + 0AA33EBB857A5205F87C09CCB99EAC74 /* Foundation.framework in Frameworks */ = {isa = PBXBuildFile; fileRef = 6A1970A14C2672638850C555C17ADE89 /* Foundation.framework */; }; + 0B5BB08F1937AD6324F0ADDD8F9E067B /* Driver.swift in Sources */ = {isa = PBXBuildFile; fileRef = E02AEC6F043CC7E4CACFA5D1EFD6EB27 /* Driver.swift */; }; + 0B994CDC79B1AD3A7BE62490D27C60C8 /* ConstraintAttributes.swift in Sources */ = {isa = PBXBuildFile; fileRef = 8B3F60740202D2919EAB02088A75C6DE /* ConstraintAttributes.swift */; }; + 0C080D5202A572C8434CA8635D35B29C /* ValidationType.swift in Sources */ = {isa = PBXBuildFile; fileRef = C807A9D8CD9D55D1BD98345635AE1623 /* ValidationType.swift */; }; + 0CB878167AA17431D1069C94A3EFF8F4 /* Infallible+Zip+arity.swift in Sources */ = {isa = PBXBuildFile; fileRef = 960152331447046185D9888B4AED166C /* Infallible+Zip+arity.swift */; }; + 0DA0657F0B4D4AF03048C3F0591C5F07 /* Pods-yinmeng-ios-dummy.m in Sources */ = {isa = PBXBuildFile; fileRef = 1BBD7BC93FC22FBD9C79EAB4AC435A7E /* Pods-yinmeng-ios-dummy.m */; }; + 0E1A429FC9CD37AF039A2A19A0D018D9 /* Switch.swift in Sources */ = {isa = PBXBuildFile; fileRef = 0487859709F230146392D21D1B192DC0 /* Switch.swift */; }; + 0EA96364E99A403FB19009B589203048 /* NetworkLoggerPlugin.swift in Sources */ = {isa = PBXBuildFile; fileRef = BDC9E1192B2CBB200B902E65C687D558 /* NetworkLoggerPlugin.swift */; }; + 0F4D0B7B522466B970AA826F57343EFF /* DataTransform.swift in Sources */ = {isa = PBXBuildFile; fileRef = F0A41DDDA8CABBF8754FE1EE9942B51A /* DataTransform.swift */; }; + 0FB2B84C4514FAE2D6B7B9E937784F55 /* KFImageProtocol.swift in Sources */ = {isa = PBXBuildFile; fileRef = 9DBF24BFBDEDD9C43BB60E43954D93C9 /* KFImageProtocol.swift */; }; + 10FF6AC524FAED0730F4BB577CF243B9 /* NopDisposable.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5BBD217833E818303FFD2DD7E1DD6817 /* NopDisposable.swift */; }; + 111810B8652D290C58076B92FCE40A1F /* RxPickerViewAdapter.swift in Sources */ = {isa = PBXBuildFile; fileRef = 2E6CA143EB6F64C9E9AD81EF8A9D3820 /* RxPickerViewAdapter.swift */; }; + 114F6342633413C8BBEC4169F34CFAFD /* RxTextViewDelegateProxy.swift in Sources */ = {isa = PBXBuildFile; fileRef = 29D71D26A754963F763183793E0737A6 /* RxTextViewDelegateProxy.swift */; }; + 11CCD832BD537718892C6A216A38490A /* URLRequest+Alamofire.swift in Sources */ = {isa = PBXBuildFile; fileRef = C4E611CCA47B1AFF3C1E57F8C2965B0C /* URLRequest+Alamofire.swift */; }; + 123E6BAD784E74477DC5B5CFF0272759 /* AnyExtensions.swift in Sources */ = {isa = PBXBuildFile; fileRef = C599239C5C9502586FE95F6C59479D15 /* AnyExtensions.swift */; }; + 12490402D5B61C9A226CBBDA0CC9AA23 /* CurrentThreadScheduler.swift in Sources */ = {isa = PBXBuildFile; fileRef = 18C45484AE9F211603671E126686D88F /* CurrentThreadScheduler.swift */; }; + 13F86B00E27F85F2A19E7FC2D60032D3 /* SkipUntil.swift in Sources */ = {isa = PBXBuildFile; fileRef = D6575A7C92CAA45BC7CAAB15672122A1 /* SkipUntil.swift */; }; + 14CAA40442778EFE3DF8B07CE170CAF7 /* UITextView+Rx.swift in Sources */ = {isa = PBXBuildFile; fileRef = 089F4ED85F7C9FD8E053CA99D41D3132 /* UITextView+Rx.swift */; }; + 160F66863942DB8C996DB1D79984C7AD /* ImmediateSchedulerType.swift in Sources */ = {isa = PBXBuildFile; fileRef = B00EB68258A05718515A533A9F917D11 /* ImmediateSchedulerType.swift */; }; + 16F9DEE85ECC94DE79B387073AC78AC7 /* DisposeBase.swift in Sources */ = {isa = PBXBuildFile; fileRef = 1CCA1BCCD3C2E9007F3F56C9E8AC6398 /* DisposeBase.swift */; }; + 1787EBB3723875770997006509209EDD /* RxTableViewDataSourceProxy.swift in Sources */ = {isa = PBXBuildFile; fileRef = 67C143D7E7508931CFD2E2398C7BA9F0 /* RxTableViewDataSourceProxy.swift */; }; + 17A8E8E15AA453D69DEF72EA593C00CA /* CompositeDisposable.swift in Sources */ = {isa = PBXBuildFile; fileRef = 7867FF4FE4FF1D6345613A45E339635D /* CompositeDisposable.swift */; }; + 180BE95F60406A62CD794746BFE108B8 /* KFAnimatedImage.swift in Sources */ = {isa = PBXBuildFile; fileRef = A3340A012067886751EC877DE2A085FB /* KFAnimatedImage.swift */; }; + 18211EE7B495AA06EBBED1D6FD9423C0 /* RxCocoa-dummy.m in Sources */ = {isa = PBXBuildFile; fileRef = 8A3398D47F647EC9C9854F30FAA9A225 /* RxCocoa-dummy.m */; }; + 183D8B3E057B885EA7DF9A8CDCCE9029 /* ConstraintMakerRelatable.swift in Sources */ = {isa = PBXBuildFile; fileRef = 32639E8193F95CA5F554F746CA3F05AD /* ConstraintMakerRelatable.swift */; }; + 186E59D8CB5FC42AA40B9F8B1C0C27A5 /* Infallible.swift in Sources */ = {isa = PBXBuildFile; fileRef = A6A3220A212C0BC4ABE0058268E8FAA6 /* Infallible.swift */; }; + 196351F59003315C03DD17E9536AAD36 /* CompactMap.swift in Sources */ = {isa = PBXBuildFile; fileRef = 81B176F830BCA2FC63200329DE776384 /* CompactMap.swift */; }; + 197457852FC83E905248660B0F930452 /* AuthenticationInterceptor.swift in Sources */ = {isa = PBXBuildFile; fileRef = DB9D0DFFB1AA39DDF8B49325F07BEBD1 /* AuthenticationInterceptor.swift */; }; + 19BB09AF94BD545E40C2766045BDDD77 /* ExtendCustomBasicType.swift in Sources */ = {isa = PBXBuildFile; fileRef = C3D7C8B8CB5663108F150E48EB940FDF /* ExtendCustomBasicType.swift */; }; + 1A3A6D1CD56F36D4F2C74B4EA79967E7 /* Filter.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5C17122D9169B76E0AB08E43B215523C /* Filter.swift */; }; + 1AFD57838680DF58184FF94D14C7F3FF /* RequestInterceptor.swift in Sources */ = {isa = PBXBuildFile; fileRef = 87AAF208F89B5776787B00ED7C4139D0 /* RequestInterceptor.swift */; }; + 1B14ABB3EBE1CF1E69D4E393ADE3E9E4 /* OtherExtension.swift in Sources */ = {isa = PBXBuildFile; fileRef = EDB3853E94E387C7E2F1D43C468ED500 /* OtherExtension.swift */; }; + 1B9E805DAD08E186C49A07E76CE551F2 /* ReplaySubject.swift in Sources */ = {isa = PBXBuildFile; fileRef = 9895F4D070396F9D33D6C602E53C0D77 /* ReplaySubject.swift */; }; + 1CBDD9F1C5BE4FAE59177A9E4E26ED68 /* Skip.swift in Sources */ = {isa = PBXBuildFile; fileRef = 9D4D5FD14129673A9CDB7002DBABE33E /* Skip.swift */; }; + 1CC3FBF38E35B664C2A003664C58E2D7 /* ControlEvent.swift in Sources */ = {isa = PBXBuildFile; fileRef = 9541ABA1A2C54DE7EED55370247C46AA /* ControlEvent.swift */; }; + 1CFA21C851234CFA8841CF06A19CA1B3 /* NibOwnerLoadable.swift in Sources */ = {isa = PBXBuildFile; fileRef = 0A4ABF00795A4D24AA39AE0648DAAFF8 /* NibOwnerLoadable.swift */; }; + 1F285EAFE181E45D258B44A554FF8837 /* Kingfisher-dummy.m in Sources */ = {isa = PBXBuildFile; fileRef = B4FAC3BE27572FE3185D20211224395A /* Kingfisher-dummy.m */; }; + 1F64C124283555FF5E1944FA37501247 /* Signal+Subscription.swift in Sources */ = {isa = PBXBuildFile; fileRef = 95D551A418E6BD3AAE54051EE0A0129C /* Signal+Subscription.swift */; }; + 1F6F0B8C1A8EA633EFEBE64EB781A6B5 /* UINavigationController+Rx.swift in Sources */ = {isa = PBXBuildFile; fileRef = 1A5F64B79665DAAF7330A9B901B15EFF /* UINavigationController+Rx.swift */; }; + 2087DD8278E2FC32F75C947E058EA423 /* NSObject+Rx+KVORepresentable.swift in Sources */ = {isa = PBXBuildFile; fileRef = D05C01883F0A989F4169EA75A319E4CE /* NSObject+Rx+KVORepresentable.swift */; }; + 20C99AA440645B161DCD0E6698F4A351 /* GroupedObservable.swift in Sources */ = {isa = PBXBuildFile; fileRef = 8770E250C6062015540FA168FD612B2B /* GroupedObservable.swift */; }; + 220D6AC9B1B1EC8EFFB204F9C1EAC842 /* ConstraintMakerEditable.swift in Sources */ = {isa = PBXBuildFile; fileRef = AA4C20251B8F62BF6DC2548854609658 /* ConstraintMakerEditable.swift */; }; + 2279FE56C854E4A8D1623EFF123490BA /* GIFAnimatedImage.swift in Sources */ = {isa = PBXBuildFile; fileRef = 9D73294AC7AF8EC9156DBA588DC9CE3D /* GIFAnimatedImage.swift */; }; + 23A3CED3EE6A0A4815A92D9E0B960328 /* ImageDownloaderDelegate.swift in Sources */ = {isa = PBXBuildFile; fileRef = A296A412119288A86A5336E1C181E566 /* ImageDownloaderDelegate.swift */; }; + 23CB3C6D36D477A8DDBDA86ED0C29396 /* Timer.swift in Sources */ = {isa = PBXBuildFile; fileRef = 7C161168F47BE22BA1D8157F0A37F4C2 /* Timer.swift */; }; + 241FB0C1BD55CC6F05C7FD78590EE5A1 /* MultiTarget.swift in Sources */ = {isa = PBXBuildFile; fileRef = 1D524DB6FB9E645710C7B04B107FB333 /* MultiTarget.swift */; }; + 24658CFD39BCB4586D56C427F8EA751D /* BuiltInBasicType.swift in Sources */ = {isa = PBXBuildFile; fileRef = 16B897EE9E0FB539D6DCE44EC4FE5968 /* BuiltInBasicType.swift */; }; + 24C8FC3B11676AD57F3A7914E6621AD0 /* TextInput.swift in Sources */ = {isa = PBXBuildFile; fileRef = F306E6A5D3D559D9E47C8FF351159D2B /* TextInput.swift */; }; + 24F54746A72C89AED62D33CF008D0BE1 /* Zip.swift in Sources */ = {isa = PBXBuildFile; fileRef = 947FCB4637962EF20818268291E26E85 /* Zip.swift */; }; + 252B64A12E2810921E86B78ECD5BDA9D /* UIApplication+Rx.swift in Sources */ = {isa = PBXBuildFile; fileRef = A4A885E79A8DF08471834BA9D0D31ED3 /* UIApplication+Rx.swift */; }; + 256558233B40ACA6818F143BBC5B8017 /* ConstraintViewDSL.swift in Sources */ = {isa = PBXBuildFile; fileRef = D5773666DA885BF217F31523BE08FD6B /* ConstraintViewDSL.swift */; }; + 258A528FB1FD89D83512AA538B069E71 /* ImageDrawing.swift in Sources */ = {isa = PBXBuildFile; fileRef = 91B4895A5E4828D58DFE315830059A72 /* ImageDrawing.swift */; }; + 263A6B3B9C8592FC16697D2AB6333AC9 /* RxCocoa.swift in Sources */ = {isa = PBXBuildFile; fileRef = 326857EAC596FAC2DD9D5071A5B96D15 /* RxCocoa.swift */; }; + 2662EA3D1400EC4BD90947902CD85670 /* Platform.Darwin.swift in Sources */ = {isa = PBXBuildFile; fileRef = A69562BE3DD6D05DD80BAD1460F44C4C /* Platform.Darwin.swift */; }; + 26D320CBBB9394E2CD2AA967CF579315 /* TVMonogramView+Kingfisher.swift in Sources */ = {isa = PBXBuildFile; fileRef = 17D5BC96435F4DD211BCF227E506B92E /* TVMonogramView+Kingfisher.swift */; }; + 2742BB22F7F098635E8D99F6A6FF844A /* DefaultIfEmpty.swift in Sources */ = {isa = PBXBuildFile; fileRef = C426FFC0480ABDFDDC457EE5FE191E5E /* DefaultIfEmpty.swift */; }; + 275C15979C1EC7DB6234974758037906 /* PublishRelay+Signal.swift in Sources */ = {isa = PBXBuildFile; fileRef = A124A76CB3B2F5D7198358B2E123B564 /* PublishRelay+Signal.swift */; }; + 27F2BE5D6E990841E8DA1DF91CF3623B /* Signal.swift in Sources */ = {isa = PBXBuildFile; fileRef = CF2909F5D4495CA4ADC352EEF99AA4EC /* Signal.swift */; }; + 282FCD4EA8B05830E9108690B8CD336B /* Session.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5254AF871AE5D79369426F1E9DFD4BFB /* Session.swift */; }; + 2878735FE61E1EEB4C493A8B8ED3DCAC /* EnumType.swift in Sources */ = {isa = PBXBuildFile; fileRef = 60A3141E90976A3DD62256D0A73B9572 /* EnumType.swift */; }; + 28A857C092C01D8BE7257A552DDDCD7F /* Bag.swift in Sources */ = {isa = PBXBuildFile; fileRef = FEDFCFC90E99F4AD01D5647DF4CB5FB4 /* Bag.swift */; }; + 28B20C35F4E1B3DDE716C831B049ADBC /* _RX.h in Headers */ = {isa = PBXBuildFile; fileRef = 71A22E298D1E26A25192B7D79CB9C7BE /* _RX.h */; settings = {ATTRIBUTES = (Public, ); }; }; + 28F7BF27F82AD7A83B634F70E879ECFA /* RxSwift-dummy.m in Sources */ = {isa = PBXBuildFile; fileRef = A612F6D773EF0336F7EEA1B142F733F1 /* RxSwift-dummy.m */; }; + 2987A730911012C32AF6695D7B54E35C /* Foundation.framework in Frameworks */ = {isa = PBXBuildFile; fileRef = 6A1970A14C2672638850C555C17ADE89 /* Foundation.framework */; }; + 2A4D8872017458ADB952D7362CD3216D /* AddRef.swift in Sources */ = {isa = PBXBuildFile; fileRef = A91E7B0C850AC3EB49D57C2F5AC657BA /* AddRef.swift */; }; + 2AA5064ABDA1A14FD82F98F25CF853D8 /* Atomic.swift in Sources */ = {isa = PBXBuildFile; fileRef = 9FE80A6E04D0DEC038F7B01D95633AE8 /* Atomic.swift */; }; + 2AC794BEBE17BA6257A13065584EC5DF /* UIDatePicker+Rx.swift in Sources */ = {isa = PBXBuildFile; fileRef = 8A9425DD88305B16CADE1573B70E7D7C /* UIDatePicker+Rx.swift */; }; + 2AD8987B16604E75E19FE7172332B9BE /* ImageModifier.swift in Sources */ = {isa = PBXBuildFile; fileRef = DFBC5B2993997B725D364216FE7C3DF6 /* ImageModifier.swift */; }; + 2AF40AD9BAE58EECFEE829EF7996669B /* Window.swift in Sources */ = {isa = PBXBuildFile; fileRef = D247DB9583EC8A9EA2396FEEE9A0BEBC /* Window.swift */; }; + 2CF7F5AEDD22D446868F6EC11694B46A /* ScheduledItemType.swift in Sources */ = {isa = PBXBuildFile; fileRef = 92037C313E25E9C5B1ECD6B53CF18C6C /* ScheduledItemType.swift */; }; + 2DAB889F1C979E0BDF2A951CF07F453E /* Do.swift in Sources */ = {isa = PBXBuildFile; fileRef = AEEBA06C08ECDC8AA5CCA71C013759FA /* Do.swift */; }; + 2E7321581005F0AAF767213937D29680 /* NSButton+Kingfisher.swift in Sources */ = {isa = PBXBuildFile; fileRef = D93E22C14E699039A509F617FA39695B /* NSButton+Kingfisher.swift */; }; + 2E9420467955EA6220D079A3678B4CCF /* CombineLatest+arity.swift in Sources */ = {isa = PBXBuildFile; fileRef = DA05AFE5E1E48A41436B4A70147E660C /* CombineLatest+arity.swift */; }; + 2EFF6DCB0FC66EB564B96A35840D5016 /* RxTableViewDataSourcePrefetchingProxy.swift in Sources */ = {isa = PBXBuildFile; fileRef = 1FCF2D3324E392803C9EFBB38E7A9ABA /* RxTableViewDataSourcePrefetchingProxy.swift */; }; + 2F29E8F0615655488301B37DCCE74DD2 /* Observable+Bind.swift in Sources */ = {isa = PBXBuildFile; fileRef = D9244D2668F560CE0CB0F0065186F8EB /* Observable+Bind.swift */; }; + 2F7ECD73855CF5C4B91D44495A9D186D /* Deferred.swift in Sources */ = {isa = PBXBuildFile; fileRef = AB501C06BD3310ADAA40217FA862D851 /* Deferred.swift */; }; + 2FCCAB4BA1D71EDB993309159D5DFA7C /* RecursiveLock.swift in Sources */ = {isa = PBXBuildFile; fileRef = FBD270BC6C902DDBA8971425BF78B4A3 /* RecursiveLock.swift */; }; + 309C54EC9536180B960B9CB8EBD412E3 /* CustomDateFormatTransform.swift in Sources */ = {isa = PBXBuildFile; fileRef = D741ADECEE7BA668846D15DEE1332031 /* CustomDateFormatTransform.swift */; }; + 3118CFD451916A9BB78E222597E8969E /* ObservableType.swift in Sources */ = {isa = PBXBuildFile; fileRef = 82EEBDF2AE2F00B7933D6A5DF8FDF0AD /* ObservableType.swift */; }; + 31E3621410AFFDD2DC866DAC48B735CE /* AsSingle.swift in Sources */ = {isa = PBXBuildFile; fileRef = 21E4BE15EF64CDD45908BF2A541F2A66 /* AsSingle.swift */; }; + 320C0D7A88AA812EFB20016BA1F5D7AE /* AFError.swift in Sources */ = {isa = PBXBuildFile; fileRef = 443CA8C627022D8C1934F8F42533236E /* AFError.swift */; }; + 3278ED404885BB1E20388250FC601681 /* AsyncSubject.swift in Sources */ = {isa = PBXBuildFile; fileRef = 46CE5C282594AAB0BC74E3DE1A773F2B /* AsyncSubject.swift */; }; + 33BC540DE351661FAAA24950E165D4F1 /* MangledName.swift in Sources */ = {isa = PBXBuildFile; fileRef = 2A8DE9D85F9B8D23A00C6EDE272AAE8D /* MangledName.swift */; }; + 361EA7ABBDD80F154DDC208D9CE920DD /* Deserializer.swift in Sources */ = {isa = PBXBuildFile; fileRef = 972FCFDB49C8D15767A6488B65F2999B /* Deserializer.swift */; }; + 362DD94616F8D1CA08A33B4F41273239 /* MainScheduler.swift in Sources */ = {isa = PBXBuildFile; fileRef = 66BCA8A6AE43B359068161172075AD29 /* MainScheduler.swift */; }; + 3660B4F629053ABC3C1DF69366770289 /* ConstraintConfig.swift in Sources */ = {isa = PBXBuildFile; fileRef = D6D6C3517EAD559475BB89B3A07F826D /* ConstraintConfig.swift */; }; + 371CD58570B89DE6A3090CC6CE16AEE7 /* UIControl+Rx.swift in Sources */ = {isa = PBXBuildFile; fileRef = 4ED914EA5EE1E5DAC87E75CFEEEBE002 /* UIControl+Rx.swift */; }; + 375CAADA212D838EE018E292E684F61E /* Cancellable.swift in Sources */ = {isa = PBXBuildFile; fileRef = 57BE0C87BBB0A537606F16CD108FAECF /* Cancellable.swift */; }; + 377229136C0061FE2FABE71862C2070F /* ItemEvents.swift in Sources */ = {isa = PBXBuildFile; fileRef = DFCC95E9F5590674CB559C0596A2DC4A /* ItemEvents.swift */; }; + 3841545F19CF975D5CA907A73A949FF6 /* Kingfisher-Kingfisher in Resources */ = {isa = PBXBuildFile; fileRef = C298ABB78D9B05529B89D8322DB2E7B0 /* Kingfisher-Kingfisher */; }; + 385BC4B250B6A6DB8AAAEA77D5B7A46F /* Combine.swift in Sources */ = {isa = PBXBuildFile; fileRef = 88195126F4E96A3774802B0BA8877C77 /* Combine.swift */; }; + 38B9D58E94D9C1CECD7E381C64A2329D /* UILayoutSupport+Extensions.swift in Sources */ = {isa = PBXBuildFile; fileRef = EF820E238AB6C626388D71E7F83DD362 /* UILayoutSupport+Extensions.swift */; }; + 38BFFE498FF2491FD1C152319A94E9F5 /* ImageContext.swift in Sources */ = {isa = PBXBuildFile; fileRef = 0F964475871A4284F485DC930EB7FE0D /* ImageContext.swift */; }; + 3957E07A50A304366C83854C41E6013B /* Materialize.swift in Sources */ = {isa = PBXBuildFile; fileRef = 75FFF56047C4C60A6E7F1E572172AC93 /* Materialize.swift */; }; + 3A030CA5A4DD41F59802F907A93F85DF /* HexColorTransform.swift in Sources */ = {isa = PBXBuildFile; fileRef = AEE012945F1ACD7D860DD82B208D5D32 /* HexColorTransform.swift */; }; + 3A379670D0CFBC0FCC9D0F66E944D074 /* RxTextStorageDelegateProxy.swift in Sources */ = {isa = PBXBuildFile; fileRef = E76B1466F3C89ABD081A805991109083 /* RxTextStorageDelegateProxy.swift */; }; + 3A59D8FBAF9A54906E3644AC80465AFB /* Notifications.swift in Sources */ = {isa = PBXBuildFile; fileRef = 05C2B32ED7987DD94725453C00328CE3 /* Notifications.swift */; }; + 3AA3DABB241FB655F8EE42D02EC95DFC /* Kingfisher.swift in Sources */ = {isa = PBXBuildFile; fileRef = 6E0F4988883481C19FAFF403697872DD /* Kingfisher.swift */; }; + 3C53583CB1A5F4926491D8838F580074 /* BuiltInBridgeType.swift in Sources */ = {isa = PBXBuildFile; fileRef = F4457E12C3F2B5AADAA643E6B0F5C555 /* BuiltInBridgeType.swift */; }; + 3EE7A29FCEE9B2A257B977E7137BC44C /* UITabBar+Rx.swift in Sources */ = {isa = PBXBuildFile; fileRef = 74E7B0CB0BD4C32719550BAEE7471ABC /* UITabBar+Rx.swift */; }; + 3EFE8454C7301C05A00EC9870F47968B /* RxTableViewDataSourceType.swift in Sources */ = {isa = PBXBuildFile; fileRef = 26A2F37034623F4E9BF155F2042659EF /* RxTableViewDataSourceType.swift */; }; + 3FA127A261BB563409868A0DC21807B2 /* ResponseSerialization.swift in Sources */ = {isa = PBXBuildFile; fileRef = 9BFCC48A5DBF6A66F64E5ACE27854985 /* ResponseSerialization.swift */; }; + 40D926572C52D27517FFC92545819FFB /* AuthenticationChallengeResponsable.swift in Sources */ = {isa = PBXBuildFile; fileRef = 7572072A13A12227DE23BD58E99E7B41 /* AuthenticationChallengeResponsable.swift */; }; + 414CF2DE69210BDE0A1C0256F87E061A /* Enumerated.swift in Sources */ = {isa = PBXBuildFile; fileRef = 2A36E5193632E241668CBF9B7B2CB7D5 /* Enumerated.swift */; }; + 4155E1924B8FC76EF105D44698EFB548 /* Delegate.swift in Sources */ = {isa = PBXBuildFile; fileRef = F9F013D28FC8ECBAF33DF99272DEC729 /* Delegate.swift */; }; + 419A11A8F7797E02FA5AAC6D8B4B3C2F /* UIStepper+Rx.swift in Sources */ = {isa = PBXBuildFile; fileRef = CA138CAED2178679471A0C1994A53ADD /* UIStepper+Rx.swift */; }; + 4251CDB971A8B94270E34381974BC9F8 /* _RXKVOObserver.h in Headers */ = {isa = PBXBuildFile; fileRef = 720BE3DE6F24DCF57D71D73928C99C2B /* _RXKVOObserver.h */; settings = {ATTRIBUTES = (Public, ); }; }; + 426C76C68C9FA3582F26BBB9E96316E4 /* _RX.m in Sources */ = {isa = PBXBuildFile; fileRef = 0D5B6D4F9F8CF76D040623D82B12D15E /* _RX.m */; }; + 42A1F6E790D900B1AC3653DBEFF8EAA6 /* Date+Dispatch.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5EC0523BF8CA0D3FF2934609B979DBED /* Date+Dispatch.swift */; }; + 42B6ACFCF650183030867CB3EF345E95 /* ConstraintMakerFinalizable.swift in Sources */ = {isa = PBXBuildFile; fileRef = 0E6A6730169419E002FF07C1AE880F77 /* ConstraintMakerFinalizable.swift */; }; + 42E7EEF0A33D83D355C821212F97A390 /* Buffer.swift in Sources */ = {isa = PBXBuildFile; fileRef = F2D487B9F0F6B5545D5A1715E39B9BCA /* Buffer.swift */; }; + 43C89358BB61E73227F6791E4697FCCC /* RedirectHandler.swift in Sources */ = {isa = PBXBuildFile; fileRef = 739CDDE742C44BA839AD3DA536BDD57F /* RedirectHandler.swift */; }; + 43DFB49930346A1A730DC21E94E2F731 /* ImageProcessor.swift in Sources */ = {isa = PBXBuildFile; fileRef = FE2C700E88155AD2A39178D87B6644F5 /* ImageProcessor.swift */; }; + 444DBA6CD07054A7900CF1A1334419BC /* ConcurrentDispatchQueueScheduler.swift in Sources */ = {isa = PBXBuildFile; fileRef = D38B8AB8BAF2B28F16F577931098B969 /* ConcurrentDispatchQueueScheduler.swift */; }; + 45F6BA1117D64D98B32E0C77670EF906 /* RxCocoaRuntime.h in Headers */ = {isa = PBXBuildFile; fileRef = A69D2E9F349C5F6AC3EC7F70DB0CCFDD /* RxCocoaRuntime.h */; settings = {ATTRIBUTES = (Public, ); }; }; + 47D3FBF90386DABCAB70AA2CA176C8EB /* ControlEvent+Driver.swift in Sources */ = {isa = PBXBuildFile; fileRef = 97E745BB2E59AE041727B826B1E61BBB /* ControlEvent+Driver.swift */; }; + 482B74C0548970BB9C095E2D8530E421 /* ParameterEncoding.swift in Sources */ = {isa = PBXBuildFile; fileRef = 2E78E508B94164D9227009C03D41986A /* ParameterEncoding.swift */; }; + 4965C451517127864A70BD41E0FA8AF9 /* Event.swift in Sources */ = {isa = PBXBuildFile; fileRef = 1C7BAB5978403A78EBF174C01FF8C71E /* Event.swift */; }; + 4B23B05F62E805619C9B5BA83E34F4A9 /* Box.swift in Sources */ = {isa = PBXBuildFile; fileRef = 1828EE850F0785BEBBEEB6381406536B /* Box.swift */; }; + 4BAD99B7394E225CEDBF94B8100BCC7F /* ConstraintRelation.swift in Sources */ = {isa = PBXBuildFile; fileRef = F52EC1967CD22048EB37327070C47EB5 /* ConstraintRelation.swift */; }; + 4BFFEA52EC61D92F315006DEB55CC6E5 /* PrimitiveSequence+Concurrency.swift in Sources */ = {isa = PBXBuildFile; fileRef = 3AF54C9D06FA26EEFB4A6D8DDB4C6C83 /* PrimitiveSequence+Concurrency.swift */; }; + 4D5E233A3AAB006B7EC565C74D18A8C1 /* RecursiveLock.swift in Sources */ = {isa = PBXBuildFile; fileRef = D88811C8F2904BE3EDD7B26CE505C673 /* RecursiveLock.swift */; }; + 4DA72FD7F1FB2C0449EDEF4B8A579807 /* ConstraintPriorityTarget.swift in Sources */ = {isa = PBXBuildFile; fileRef = A52935DC312F87728290A3ACA2167BCD /* ConstraintPriorityTarget.swift */; }; + 4DDE90582DEB58DC0EF7BCC911D3BCBA /* Single.swift in Sources */ = {isa = PBXBuildFile; fileRef = 4DB8E452090D235990597C3AB1BE8E11 /* Single.swift */; }; + 4DEAE5703BDD544C9956BF42F7D57CE5 /* DiskStorage.swift in Sources */ = {isa = PBXBuildFile; fileRef = 8CDAEEA9FC477033FF5344F6CBE85CB2 /* DiskStorage.swift */; }; + 4F315C18FC854325DD5D062DD7A363D5 /* ObservableConvertibleType+SharedSequence.swift in Sources */ = {isa = PBXBuildFile; fileRef = F035F0F1D2D858918B6C937E1F71A98E /* ObservableConvertibleType+SharedSequence.swift */; }; + 4F894DAB31F1A68FD37EA61B87CDC043 /* StoryboardSceneBased.swift in Sources */ = {isa = PBXBuildFile; fileRef = AB91063BFA0B85155CE39C26F80044C5 /* StoryboardSceneBased.swift */; }; + 514272471493DBBD026BC35D58547601 /* Timeout.swift in Sources */ = {isa = PBXBuildFile; fileRef = 654DEBE109ACCEE862E7F084EE7ED13C /* Timeout.swift */; }; + 5150F2661A947E67A50557847BAA22C0 /* AnonymousObserver.swift in Sources */ = {isa = PBXBuildFile; fileRef = BBE5FECC28B966616BA85A7C62F7FA40 /* AnonymousObserver.swift */; }; + 5223E292D90519A9F902F743DE388C22 /* InvocableScheduledItem.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5DC90B70DB4293C27D4B5733F05EC3CC /* InvocableScheduledItem.swift */; }; + 5230B70A7B448918B83D3B983533D29A /* KVORepresentable+CoreGraphics.swift in Sources */ = {isa = PBXBuildFile; fileRef = 8D0507B1E2AB4B8A447354D000FEF414 /* KVORepresentable+CoreGraphics.swift */; }; + 529173B31EFCD3D199E79866AFBEC86C /* HTTPHeaders.swift in Sources */ = {isa = PBXBuildFile; fileRef = F0933F5FD3BA39AA382ECC963D6550B8 /* HTTPHeaders.swift */; }; + 529BE65BAC3A56AB2FF74B26B63D3029 /* Dematerialize.swift in Sources */ = {isa = PBXBuildFile; fileRef = AFF9C7F95915AA09C2220E7711A63B74 /* Dematerialize.swift */; }; + 52DD330B3BED8407E4EFED176F0B4DBA /* Foundation.framework in Frameworks */ = {isa = PBXBuildFile; fileRef = 6A1970A14C2672638850C555C17ADE89 /* Foundation.framework */; }; + 533F06C629B5676D3E165946F1CAB400 /* UIKit.framework in Frameworks */ = {isa = PBXBuildFile; fileRef = 3397E4A82849848801375ABF4E7B4080 /* UIKit.framework */; }; + 5357162246E301753EE5CBE40BF75038 /* Optional.swift in Sources */ = {isa = PBXBuildFile; fileRef = 1517F2B568C0846F286EF269D17902A5 /* Optional.swift */; }; + 5380454C48A12A6E376122ABD8096968 /* ConstraintDescription.swift in Sources */ = {isa = PBXBuildFile; fileRef = 64F516F56589A2470DFA0E30E85DBB80 /* ConstraintDescription.swift */; }; + 53F5DA7BA570018EFB8761D97C00DA6D /* PublishSubject.swift in Sources */ = {isa = PBXBuildFile; fileRef = 70933FA1D55CE70EA5A4110C98DEC09D /* PublishSubject.swift */; }; + 5435E924E7CE7B05B7F650C078A12F5B /* UITabBarController+Rx.swift in Sources */ = {isa = PBXBuildFile; fileRef = E727269035DBECA74CF6FA02E1B24B09 /* UITabBarController+Rx.swift */; }; + 543824E1170EF49570C40DAE54604F21 /* _RXDelegateProxy.h in Headers */ = {isa = PBXBuildFile; fileRef = AAC31C95D09575257C31EB192272C7C2 /* _RXDelegateProxy.h */; settings = {ATTRIBUTES = (Public, ); }; }; + 5484C183C3C25F933AEDAFADF8E4C404 /* Kingfisher-umbrella.h in Headers */ = {isa = PBXBuildFile; fileRef = 4FE70A655C85EA7C91C24E5B3457D9B0 /* Kingfisher-umbrella.h */; settings = {ATTRIBUTES = (Public, ); }; }; + 54A091154030EF2F51399D01C732D578 /* ConcurrentMainScheduler.swift in Sources */ = {isa = PBXBuildFile; fileRef = 728E3C167CE3ED7F8123F48D5A84771E /* ConcurrentMainScheduler.swift */; }; + 54EEEBA0AA7C4D84A5D0752813489F5F /* InvocableType.swift in Sources */ = {isa = PBXBuildFile; fileRef = C4E6211C49C3ADB158FA16A1751D5E34 /* InvocableType.swift */; }; + 55713DE36F28B0D078ADAD60D5EE7FF4 /* ObservableConvertibleType+Driver.swift in Sources */ = {isa = PBXBuildFile; fileRef = EFC734B57692B8F617FD03908D932F63 /* ObservableConvertibleType+Driver.swift */; }; + 557AE7547352CEA86AEE5518CC1A503E /* RxCocoa-umbrella.h in Headers */ = {isa = PBXBuildFile; fileRef = 66EAB16FAAFDFDFF614A83B83544F60A /* RxCocoa-umbrella.h */; settings = {ATTRIBUTES = (Public, ); }; }; + 558B0B6DA4F450EB47428619840800E9 /* Throttle.swift in Sources */ = {isa = PBXBuildFile; fileRef = AB1550C20B92B5D8CBB8484C4660BE90 /* Throttle.swift */; }; + 55E51F45F1E157D3B4942BA7252C277E /* ConstraintRelatableTarget.swift in Sources */ = {isa = PBXBuildFile; fileRef = C019E68F4B2DE55C5FD2493950035664 /* ConstraintRelatableTarget.swift */; }; + 567E2B1BAE575E6556A2E57191BA2DA7 /* DelegateProxyType.swift in Sources */ = {isa = PBXBuildFile; fileRef = 544D687E21BDD58B48D554A5709A7901 /* DelegateProxyType.swift */; }; + 56A72F6D13D930C4A2568F24DEA33C8D /* ConstraintLayoutSupportDSL.swift in Sources */ = {isa = PBXBuildFile; fileRef = D9278F439B7C4235C53C200B17F84E46 /* ConstraintLayoutSupportDSL.swift */; }; + 56AC6DC6459AE47E7BC4AF06E5B148D2 /* ConstraintDSL.swift in Sources */ = {isa = PBXBuildFile; fileRef = B90F3E609D4D31B9CE6BA0937072B8DB /* ConstraintDSL.swift */; }; + 56CAC06DB79E51F4ED416927D57C79A9 /* Measuable.swift in Sources */ = {isa = PBXBuildFile; fileRef = 84E7CDD4F491C19202D78BD1D18EA01E /* Measuable.swift */; }; + 58C91B4AB36E6B16421106CA634C58EF /* MBProgressHUD-dummy.m in Sources */ = {isa = PBXBuildFile; fileRef = C4166DF44E4B7DCF69575608F281517C /* MBProgressHUD-dummy.m */; }; + 598A8B5AC028B7EAFE6339965A063384 /* CombineLatest+Collection.swift in Sources */ = {isa = PBXBuildFile; fileRef = 917C955DCF6B29BABB9B623BE0758691 /* CombineLatest+Collection.swift */; }; + 5A39F3F258372FA025F08ECAFFFCF71D /* NSTextField+Rx.swift in Sources */ = {isa = PBXBuildFile; fileRef = F3EF76F454F323E3B71A0221AFFC8238 /* NSTextField+Rx.swift */; }; + 5A3DE5038C0E8C2BAFC3316589D0F918 /* NotificationCenter+Rx.swift in Sources */ = {isa = PBXBuildFile; fileRef = C1706327EA78CAEFF1336CC5568AD36C /* NotificationCenter+Rx.swift */; }; + 5A8A82AA7F76A861CE989B801C506551 /* SynchronizedUnsubscribeType.swift in Sources */ = {isa = PBXBuildFile; fileRef = FA5D56DE5D48CA926F73DF626BACA99D /* SynchronizedUnsubscribeType.swift */; }; + 5B0CD721D955D01B28AFE5291318A7DE /* Delay.swift in Sources */ = {isa = PBXBuildFile; fileRef = 445854BBB677492BEB10430E549CF31D /* Delay.swift */; }; + 5B92A66A66BD639411C3D839A0F87B0C /* Request.swift in Sources */ = {isa = PBXBuildFile; fileRef = C6D030CA131DAC625D4D9FDC5FD000E3 /* Request.swift */; }; + 5BA418EFF060B7BEFDAF9B3E1E56ED4E /* ReplayRelay.swift in Sources */ = {isa = PBXBuildFile; fileRef = 2868D931558DCC05627934B9EF6362E6 /* ReplayRelay.swift */; }; + 5BAC1EF86D0E57E44E404B2796993561 /* MBProgressHUD-umbrella.h in Headers */ = {isa = PBXBuildFile; fileRef = C3ABFDAE24AACD8E1EEE68793DE9803B /* MBProgressHUD-umbrella.h */; settings = {ATTRIBUTES = (Public, ); }; }; + 5BE4EFBB9E0CB1968E72E793FF118931 /* ImageCache.swift in Sources */ = {isa = PBXBuildFile; fileRef = 48252905C19EDB8DCAE2BE4BE7B68A85 /* ImageCache.swift */; }; + 5CCB87A1A86D7C03A5D678B262B37071 /* Foundation.framework in Frameworks */ = {isa = PBXBuildFile; fileRef = 6A1970A14C2672638850C555C17ADE89 /* Foundation.framework */; }; + 5D36B99F3CAB1FC7337082D9581FECA6 /* Debugging.swift in Sources */ = {isa = PBXBuildFile; fileRef = 8CDDAB158F06801DD368BFA93A07800C /* Debugging.swift */; }; + 5EBC224DDA3EC6CCE8C42EED6063FD35 /* ImageProgressive.swift in Sources */ = {isa = PBXBuildFile; fileRef = F329A03B4D1A8412BFD9F49535A2D291 /* ImageProgressive.swift */; }; + 5FEA895A04C350A054C05410C2807F00 /* SubjectType.swift in Sources */ = {isa = PBXBuildFile; fileRef = 17D7B878065E9387C23C43CFACC3A867 /* SubjectType.swift */; }; + 604D3C93C17978C23600EC415949AB64 /* ConstraintInsets.swift in Sources */ = {isa = PBXBuildFile; fileRef = EE92ADF7F5D694CD90670878273D0E22 /* ConstraintInsets.swift */; }; + 6066DF8EBAAF4EAD3A904AFF921C3CBB /* ImageDataProcessor.swift in Sources */ = {isa = PBXBuildFile; fileRef = FB5DD901158FEFCA27ADE24D3A8E12FA /* ImageDataProcessor.swift */; }; + 608DC0C8110DDFF5D8E5A43BB48A6A86 /* UISlider+Rx.swift in Sources */ = {isa = PBXBuildFile; fileRef = 160D2BDCA79733E1BBB01B00F9404132 /* UISlider+Rx.swift */; }; + 611CEF7FF1EF9EA1BCEF6C73EEE3ACCF /* ConstraintLayoutGuide.swift in Sources */ = {isa = PBXBuildFile; fileRef = 594A5F9AE55C8EAD11AFE74EE0DAC3C7 /* ConstraintLayoutGuide.swift */; }; + 612674D32D68391DF2AF6E89FA6D9BBC /* Pods-yinmeng-ios-umbrella.h in Headers */ = {isa = PBXBuildFile; fileRef = 9B3AF9BB0F7EB5558031DD21AD2F86CC /* Pods-yinmeng-ios-umbrella.h */; settings = {ATTRIBUTES = (Public, ); }; }; + 61E63227D5A012BA17E37229455BA5B8 /* AnonymousDisposable.swift in Sources */ = {isa = PBXBuildFile; fileRef = 30F3EE79D4A82DDA5FBAD0C2C8D6753A /* AnonymousDisposable.swift */; }; + 61EB40AB5F1BB5E6FDC8C5CDE06C3DE9 /* RxPickerViewDataSourceType.swift in Sources */ = {isa = PBXBuildFile; fileRef = DF2E2C729461BB0F5D730E63F64A5F23 /* RxPickerViewDataSourceType.swift */; }; + 61FCA0616CE6512DCA67D74562D6EA1D /* ReflectionHelper.swift in Sources */ = {isa = PBXBuildFile; fileRef = A79AD749EBBF7C8E00F924437B94E568 /* ReflectionHelper.swift */; }; + 62C1A489E5C6414819815F3219B52FE8 /* URLTransform.swift in Sources */ = {isa = PBXBuildFile; fileRef = 2C4725814B303164AE7425543FDA788C /* URLTransform.swift */; }; + 6339E0715C212DB48BD9F6A3FFD883DA /* Sample.swift in Sources */ = {isa = PBXBuildFile; fileRef = 6BC184BD2886B5395146315871D4F629 /* Sample.swift */; }; + 643A7AFFB7AEB70B2B9B7E0926055023 /* RetryPolicy.swift in Sources */ = {isa = PBXBuildFile; fileRef = 2A271DE0F470E6D6B4CF963A21854DEA /* RetryPolicy.swift */; }; + 64986C72DEBFAB6607409ED2AC830D1E /* Error.swift in Sources */ = {isa = PBXBuildFile; fileRef = 9D5553E70A731CAE3CC0589428DF9FFA /* Error.swift */; }; + 654D9C29A846E7ED4DD5BF0BFC8D64B8 /* UISwitch+Rx.swift in Sources */ = {isa = PBXBuildFile; fileRef = 8DCA321A43CEC56664AD41086F8B7141 /* UISwitch+Rx.swift */; }; + 660E73ECB1E50185B9D21BAA127DC3A0 /* UIRefreshControl+Rx.swift in Sources */ = {isa = PBXBuildFile; fileRef = 9FC9415FA1C1593D995CF4413F86119E /* UIRefreshControl+Rx.swift */; }; + 66411B211AAEB0C4DB6491A8AED6FEAF /* WKInterfaceImage+Kingfisher.swift in Sources */ = {isa = PBXBuildFile; fileRef = 2AEBE0DF14984ECC53D005ED92A73024 /* WKInterfaceImage+Kingfisher.swift */; }; + 67B10FEAA3B7E5387D20E76B1085E94D /* URLSessionConfiguration+Alamofire.swift in Sources */ = {isa = PBXBuildFile; fileRef = ABF8C3D769C418801ABB2905159428B8 /* URLSessionConfiguration+Alamofire.swift */; }; + 67E941CADB3CDDEEDF8CE4EE4A4A05BB /* MBProgressHUD.h in Headers */ = {isa = PBXBuildFile; fileRef = A8A0F224AF15F0E14442ECFCC641E624 /* MBProgressHUD.h */; settings = {ATTRIBUTES = (Public, ); }; }; + 68AF5CE54DF91D0EA6E1DD02432DCB0A /* Placeholder.swift in Sources */ = {isa = PBXBuildFile; fileRef = 8472FB3724242C375626B5D19B004A36 /* Placeholder.swift */; }; + 6927E0A61FCF762B43C75325110C3D77 /* Infallible+Bind.swift in Sources */ = {isa = PBXBuildFile; fileRef = 394A07B9CD7A0E87C54639C7326B5B28 /* Infallible+Bind.swift */; }; + 69657DEC11BB7E4F9F5B6DE8E1148B3E /* _RXObjCRuntime.h in Headers */ = {isa = PBXBuildFile; fileRef = 35651FD3900CCCFFCDA6DD8ECE470B93 /* _RXObjCRuntime.h */; settings = {ATTRIBUTES = (Public, ); }; }; + 69D07BBB6641693C30C1D2A3774F6721 /* GraphicsContext.swift in Sources */ = {isa = PBXBuildFile; fileRef = 70B306F880D3FA0554EF152D25916163 /* GraphicsContext.swift */; }; + 69DE75BA185BBAB5FDAA28321F3C849F /* ConstraintItem.swift in Sources */ = {isa = PBXBuildFile; fileRef = FE77747AB7C6876DC80B43C5DCE4ABF0 /* ConstraintItem.swift */; }; + 69FE518ED5298543E204E1509D30952A /* KF.swift in Sources */ = {isa = PBXBuildFile; fileRef = 105DC924B68D07DCCA5F7BBD13103F15 /* KF.swift */; }; + 6AC1B881BB319C89AD023A02CDC8FC3D /* ConstraintLayoutGuide+Extensions.swift in Sources */ = {isa = PBXBuildFile; fileRef = 96EB1FBABEA3906F0EF58EE47E45A83B /* ConstraintLayoutGuide+Extensions.swift */; }; + 6AFDE75A0DBBC5BB095963EFD1DBE944 /* WithLatestFrom.swift in Sources */ = {isa = PBXBuildFile; fileRef = A4E676ABA267DB49404DD1A3CCB33F17 /* WithLatestFrom.swift */; }; + 6B4A32082CED69B110A83E603813FDB7 /* Infallible+Operators.swift in Sources */ = {isa = PBXBuildFile; fileRef = 8FC8131B3030B737FB4BE9DBCBAB4C9E /* Infallible+Operators.swift */; }; + 6BD6A6695D05908524545A776D4C36B9 /* ImageDataProvider.swift in Sources */ = {isa = PBXBuildFile; fileRef = 005B0AA170372B033FC09D4E58FBAC9A /* ImageDataProvider.swift */; }; + 6BDA2BC21E394076C2E58E9269F4AABD /* SchedulerType+SharedSequence.swift in Sources */ = {isa = PBXBuildFile; fileRef = 495812E6EEB9BFC5FBAD933FB325C0BE /* SchedulerType+SharedSequence.swift */; }; + 6C1EED16F5E7B9F4BA1698A5D083EC50 /* FormatIndicatedCacheSerializer.swift in Sources */ = {isa = PBXBuildFile; fileRef = FBDDA0D117F42E4FE226978800527457 /* FormatIndicatedCacheSerializer.swift */; }; + 6C5571DAC14E51299671ABC2AF0E1A62 /* Plugin.swift in Sources */ = {isa = PBXBuildFile; fileRef = 07360B313B37C9A5C5310D3E0442D54B /* Plugin.swift */; }; + 6DA16B11139D88B0C3BD21BF65790D34 /* Debounce.swift in Sources */ = {isa = PBXBuildFile; fileRef = 2DAD506D24AC12D48E8C572B4C5B8674 /* Debounce.swift */; }; + 6DB19BEE9C42CBE8101A114524B38CE7 /* NSView+Rx.swift in Sources */ = {isa = PBXBuildFile; fileRef = FE06975BE3E77F3DFD642DD868FE617D /* NSView+Rx.swift */; }; + 6DFB5C921332D5E14BF251A5ADA46473 /* RxNavigationControllerDelegateProxy.swift in Sources */ = {isa = PBXBuildFile; fileRef = 304C3471BD45700A1BFEFC1877E24B5A /* RxNavigationControllerDelegateProxy.swift */; }; + 6EAC8B6FA2D115DE708A58C601DD25E1 /* Constraint.swift in Sources */ = {isa = PBXBuildFile; fileRef = 8FF51600836B6E9C1393D1B32AE0409F /* Constraint.swift */; }; + 6F803B4767FE50C12E3F0402DC0A3BE5 /* PriorityQueue.swift in Sources */ = {isa = PBXBuildFile; fileRef = C33F711F76B40DF65DA404994ED241BA /* PriorityQueue.swift */; }; + 71D07A691D1D78FD8B421B127CE7496B /* Image.swift in Sources */ = {isa = PBXBuildFile; fileRef = 4DB0FE9FA272BBF1E359F79E2FE6B469 /* Image.swift */; }; + 71E6B1C3D8711A083F76B6D3C0D561B6 /* Foundation.framework in Frameworks */ = {isa = PBXBuildFile; fileRef = 6A1970A14C2672638850C555C17ADE89 /* Foundation.framework */; }; + 7212ACC786B61C86DE7EBED50CC29FD5 /* MoyaProvider+Internal.swift in Sources */ = {isa = PBXBuildFile; fileRef = 0764DAF106A0E6A03874313AD80FDDB7 /* MoyaProvider+Internal.swift */; }; + 729183886B27549C5B666CC3F5C1B495 /* Infallible+CombineLatest+arity.swift in Sources */ = {isa = PBXBuildFile; fileRef = 7D131FE518C0CECBEA619AA8A5490197 /* Infallible+CombineLatest+arity.swift */; }; + 72EE3F69E6154EF5C5524DE4F4EE0B5C /* Queue.swift in Sources */ = {isa = PBXBuildFile; fileRef = 29CBD6F8B67F5629CFB1D1326F23E28A /* Queue.swift */; }; + 72FCE0D3F5EA7EB908C108DFD468B267 /* RxCollectionViewDataSourcePrefetchingProxy.swift in Sources */ = {isa = PBXBuildFile; fileRef = 8D02F219043B80DB62FA686E85C09B35 /* RxCollectionViewDataSourcePrefetchingProxy.swift */; }; + 731C34C22800D5F0AF417E801D3409B0 /* SessionDataTask.swift in Sources */ = {isa = PBXBuildFile; fileRef = B2958A0E6033229331C79C4CD02FB145 /* SessionDataTask.swift */; }; + 732C29255F73EF3D83D49BD4F8FEAA8F /* MultipartUpload.swift in Sources */ = {isa = PBXBuildFile; fileRef = 7CFEE4BC9AEF52579A20AF4717B3205C /* MultipartUpload.swift */; }; + 737747B9A98257DB58112C3A23686669 /* MultipartFormData.swift in Sources */ = {isa = PBXBuildFile; fileRef = 215B8518AD4396707F88E578B313121F /* MultipartFormData.swift */; }; + 753A064C58BBF2D833F709412D9E9FE3 /* Platform.Darwin.swift in Sources */ = {isa = PBXBuildFile; fileRef = FA88BA483915DE8B6B9D5D7B9A4AAE90 /* Platform.Darwin.swift */; }; + 7542BDA803F84EC71005AE526659436A /* Observable+Concurrency.swift in Sources */ = {isa = PBXBuildFile; fileRef = 10DF3559568462A634A6F7EE6FFBCA00 /* Observable+Concurrency.swift */; }; + 761DF0256CBB0CA4506580DFBB612194 /* KingfisherManager.swift in Sources */ = {isa = PBXBuildFile; fileRef = 0292DCF642DD7EA1D1116B8623A8C599 /* KingfisherManager.swift */; }; + 76374B984BAD760575C5223FEC2C6FC1 /* MoyaError.swift in Sources */ = {isa = PBXBuildFile; fileRef = A3CC4FE478601A48919D7092CBFF414A /* MoyaError.swift */; }; + 768A33DCEB41CBC5C7ECF5F0220B1A97 /* SharedSequence+Concurrency.swift in Sources */ = {isa = PBXBuildFile; fileRef = 191A401108B388D3700F7B69157F58FA /* SharedSequence+Concurrency.swift */; }; + 76F608B4608884FCB00256FEF79A61E3 /* SynchronizedDisposeType.swift in Sources */ = {isa = PBXBuildFile; fileRef = 537DF163C75C79892595630BC3CBA09F /* SynchronizedDisposeType.swift */; }; + 77AB6AF4BFC6DE016DA7C057B5799C84 /* ServerTrustEvaluation.swift in Sources */ = {isa = PBXBuildFile; fileRef = CCF0B72B35A6BCD96CBC1A3F6A6ED7B4 /* ServerTrustEvaluation.swift */; }; + 77F109FA3951C23E7F0E7A4F5581F488 /* MoyaProvider+Defaults.swift in Sources */ = {isa = PBXBuildFile; fileRef = 4189EEA5194A0B67B0929125B7D8F3B9 /* MoyaProvider+Defaults.swift */; }; + 78079FE3271F118CE83CFD8D5E4F8C21 /* TransformOf.swift in Sources */ = {isa = PBXBuildFile; fileRef = 8DA1B7070D9B7E6489E50762BA7CC29B /* TransformOf.swift */; }; + 782082D9F5529E63F249E8811BA6FD10 /* RxPickerViewDataSourceProxy.swift in Sources */ = {isa = PBXBuildFile; fileRef = E3F3D140901AD39649AC074216CAC836 /* RxPickerViewDataSourceProxy.swift */; }; + 78B1DD1219182494A6AFAD26AAB20AA6 /* Concurrency.swift in Sources */ = {isa = PBXBuildFile; fileRef = 4B2092F7A452FCAC892734476E6676E3 /* Concurrency.swift */; }; + 78EB4944F6EE0CF299F715B7340E19AB /* Empty.swift in Sources */ = {isa = PBXBuildFile; fileRef = 25CF572152EDEF89E43D914242F08BE0 /* Empty.swift */; }; + 798C7D29511D498BDB7BEC4996708557 /* Configuration.swift in Sources */ = {isa = PBXBuildFile; fileRef = 7430E48DEB35987DD064EE0D7363953F /* Configuration.swift */; }; + 79AB21FCF882EB4FC9DD5F111C2F53D3 /* Moya-dummy.m in Sources */ = {isa = PBXBuildFile; fileRef = 2CCCFEF676D5297ACAAB23C1A5CB7CAE /* Moya-dummy.m */; }; + 79C7D4E9901AA11C25F8C71F3E9DF612 /* Properties.swift in Sources */ = {isa = PBXBuildFile; fileRef = A3821293C89F3E60BD6231B1E48974A1 /* Properties.swift */; }; + 79F3A6E62579CE8906D3DA8B984347CC /* Using.swift in Sources */ = {isa = PBXBuildFile; fileRef = 7FA5EF7CC85AF8D7A9C4307E6247274B /* Using.swift */; }; + 7B81980B63BBD77A851BCD01FF160D44 /* HistoricalSchedulerTimeConverter.swift in Sources */ = {isa = PBXBuildFile; fileRef = 913295D3902A731E0FEF7891F2DFFD66 /* HistoricalSchedulerTimeConverter.swift */; }; + 7BA5D9B38DAEDD6A5166ECF2A498D194 /* RxCollectionViewDataSourceType.swift in Sources */ = {isa = PBXBuildFile; fileRef = 8898277C74B39B8C2709D3BDFF6C793E /* RxCollectionViewDataSourceType.swift */; }; + 7C9C0D2AB5BB6670928CC95B4DA46814 /* RxSearchBarDelegateProxy.swift in Sources */ = {isa = PBXBuildFile; fileRef = 3F5105C63B26C8CD36ECD3E4D25A4DFC /* RxSearchBarDelegateProxy.swift */; }; + 7CB4D382650A1BB458B68BF3B39FE27D /* AnyEncodable.swift in Sources */ = {isa = PBXBuildFile; fileRef = 045D5D90782798F36E8E8F973DAC5B28 /* AnyEncodable.swift */; }; + 7D64BC3E6CAA4AB54EAC0AAADE93F578 /* OperationQueue+Alamofire.swift in Sources */ = {isa = PBXBuildFile; fileRef = F63084A32C04D39192F17E5B2082033C /* OperationQueue+Alamofire.swift */; }; + 7D9031DCB898CD9DE37C4BD4F3FC550D /* DateFormatterTransform.swift in Sources */ = {isa = PBXBuildFile; fileRef = DEA6B630488DF0930202C22D36F757CB /* DateFormatterTransform.swift */; }; + 7E29FFE700C1C3AC047E58CC1E8EA468 /* SubscriptionDisposable.swift in Sources */ = {isa = PBXBuildFile; fileRef = 4E71EDCC1B6F580E01E54903C36737EB /* SubscriptionDisposable.swift */; }; + 7E313C5665BD42F0877BFD2CEBBD82CE /* URL+Moya.swift in Sources */ = {isa = PBXBuildFile; fileRef = 87AD720C8F2A51587F1C491E884DB664 /* URL+Moya.swift */; }; + 80C4B7E883C94E18102938F43B0EF240 /* ImageView+Kingfisher.swift in Sources */ = {isa = PBXBuildFile; fileRef = B35DC4FCD2EEF00AF73453F41872FF54 /* ImageView+Kingfisher.swift */; }; + 80D1BF4CD8C1A9EF7DA5012AAAE4D988 /* KFImageRenderer.swift in Sources */ = {isa = PBXBuildFile; fileRef = 11D7747447E5C511F9D8307F10E5168C /* KFImageRenderer.swift */; }; + 80F0B9ABC3E9D190B7A3C755A903EF54 /* Concat.swift in Sources */ = {isa = PBXBuildFile; fileRef = A54253F4F6876CCFC845DA722D6C8CE8 /* Concat.swift */; }; + 810421CBB613D2EA65E39D66C98C1B5A /* Generate.swift in Sources */ = {isa = PBXBuildFile; fileRef = 591861115B56C34EE893545E4F44ECE0 /* Generate.swift */; }; + 81148E8E0935476F92B10881A023D0DC /* ControlTarget.swift in Sources */ = {isa = PBXBuildFile; fileRef = EF5F5DC6C61E0C786AA3BA02874662A1 /* ControlTarget.swift */; }; + 817B896013FD56C04CD26E2F6C67EA7E /* NSTextAttachment+Kingfisher.swift in Sources */ = {isa = PBXBuildFile; fileRef = F098DF51276D641070E6E01539D4B986 /* NSTextAttachment+Kingfisher.swift */; }; + 81E4CCFEB1307757E98744344B75B9FB /* RequestModifier.swift in Sources */ = {isa = PBXBuildFile; fileRef = F9E3641046F777BA820AB2055AA51792 /* RequestModifier.swift */; }; + 81E6A0FF7F286008345ECFA3A2103FA8 /* Alamofire.swift in Sources */ = {isa = PBXBuildFile; fileRef = 220B3F8A303994576980CB9C15199150 /* Alamofire.swift */; }; + 820E300519E853EAC9E09ED6CC71EBDC /* StoryboardBased.swift in Sources */ = {isa = PBXBuildFile; fileRef = 0F2F174FA9B884D41464BD84265273E9 /* StoryboardBased.swift */; }; + 82747E86C0002A1A0BE8467C000C88F9 /* Reduce.swift in Sources */ = {isa = PBXBuildFile; fileRef = C45FE00D96FB11A4BF6998884E30C879 /* Reduce.swift */; }; + 82FD97FBBEFE51E2D3B434AF4954FC93 /* EventMonitor.swift in Sources */ = {isa = PBXBuildFile; fileRef = 2D85DF2E1C33DB9B470D4EFFB7F4A1FC /* EventMonitor.swift */; }; + 846C97A8C420EFD9B8C4B77ADBB1E8F5 /* TransformType.swift in Sources */ = {isa = PBXBuildFile; fileRef = 1CEDEE8EE3D758478549E54DB2D8CB8D /* TransformType.swift */; }; + 84AEE29F4E7DDA962C49D6FAC6044EBC /* RxCocoaObjCRuntimeError+Extensions.swift in Sources */ = {isa = PBXBuildFile; fileRef = A4DBD0A365804120DBE621B87A954E25 /* RxCocoaObjCRuntimeError+Extensions.swift */; }; + 86C39B668AB190EE95464C8AB1E0111A /* Resource.swift in Sources */ = {isa = PBXBuildFile; fileRef = 94B8075CA095FDBA9AE87F86A21B0C30 /* Resource.swift */; }; + 87304D5AF2582C6E7839864112534CBE /* Result.swift in Sources */ = {isa = PBXBuildFile; fileRef = 95AF3FFD5DA43879FFD1FEF529C36275 /* Result.swift */; }; + 8951BE47D18264444C90F76B1695A1D0 /* ObservableType+PrimitiveSequence.swift in Sources */ = {isa = PBXBuildFile; fileRef = 36683A54CDD175D2798404369B19387A /* ObservableType+PrimitiveSequence.swift */; }; + 89EE8751EC67604A80510F131F373127 /* Map.swift in Sources */ = {isa = PBXBuildFile; fileRef = E4E95E8B077E462C80766715ADCA4CF0 /* Map.swift */; }; + 8A7A14267160A9EACDC74A9E21B8F058 /* Image.swift in Sources */ = {isa = PBXBuildFile; fileRef = 002ED0D813882532198DEB9328551828 /* Image.swift */; }; + 8A8AD24A8CE75FBE807EB5A9FC11E62A /* Bag.swift in Sources */ = {isa = PBXBuildFile; fileRef = DDB4D4AEF2A47181ABD692BE53C6DF1A /* Bag.swift */; }; + 8AEE5B74A5BAC274D6589F229D867768 /* UITableView+Rx.swift in Sources */ = {isa = PBXBuildFile; fileRef = 9C6E055D8D9B83521DB2D0B74D91A032 /* UITableView+Rx.swift */; }; + 8BE63006C33671D8617303C1FBDF4AD0 /* Just.swift in Sources */ = {isa = PBXBuildFile; fileRef = B4C8D32181C1DD0673EF71FC021C399D /* Just.swift */; }; + 8C3394695CB4CCECD873D1384F4BA076 /* Export.swift in Sources */ = {isa = PBXBuildFile; fileRef = 6009157C9973464C53AFA7E068E984F7 /* Export.swift */; }; + 8CD5DE204C3C5F6557878ADE2675A406 /* HelpingMapper.swift in Sources */ = {isa = PBXBuildFile; fileRef = 1BBE63969630CA64CDD14AE518F9ED70 /* HelpingMapper.swift */; }; + 8D72B695C7EF0186A0C0F1A18F944880 /* PropertyInfo.swift in Sources */ = {isa = PBXBuildFile; fileRef = 477447EAA52D7E8C1E3C05F2DD47F9B1 /* PropertyInfo.swift */; }; + 8E698F134A953250D5834C8B83CDAD34 /* DispatchQueue+Alamofire.swift in Sources */ = {isa = PBXBuildFile; fileRef = 7E97E1D4DF8BFA3FE2C603D6B934D9D2 /* DispatchQueue+Alamofire.swift */; }; + 8E6F33205BF126E6DECF929A32A98869 /* Never.swift in Sources */ = {isa = PBXBuildFile; fileRef = 4F5800717EBB5879045C06670DA4C8AC /* Never.swift */; }; + 8E778C0090C85DDB5290B07143FFD917 /* Filter.swift in Sources */ = {isa = PBXBuildFile; fileRef = 590615ED68A80BD1EF1DBF8F477F1B12 /* Filter.swift */; }; + 8E85763AE29BEF0A46EE875B8F069E8E /* Foundation.framework in Frameworks */ = {isa = PBXBuildFile; fileRef = 6A1970A14C2672638850C555C17ADE89 /* Foundation.framework */; }; + 8F1CD0744791BEC18F73D6FF3A150090 /* TailRecursiveSink.swift in Sources */ = {isa = PBXBuildFile; fileRef = 64576C6FC886A417A4683A9816DA5D4F /* TailRecursiveSink.swift */; }; + 90585B3B5526DB8ECBD1AB8EF2C4D5A2 /* UISegmentedControl+Rx.swift in Sources */ = {isa = PBXBuildFile; fileRef = 2B71FB79E7C0B7102E8EF89E2C326862 /* UISegmentedControl+Rx.swift */; }; + 924E2F405AE00EDF695B3D926EB6BB1A /* OperationQueueScheduler.swift in Sources */ = {isa = PBXBuildFile; fileRef = C909B32972D2D22DB9AE521E98C47040 /* OperationQueueScheduler.swift */; }; + 92B3198E1EBE2EC545BB36AF6A9CC368 /* MemoryStorage.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5DE5F4C9535F3ECFDE536AF77F583A78 /* MemoryStorage.swift */; }; + 9426B0386E4DC02F4E347A457C39144A /* NetworkActivityPlugin.swift in Sources */ = {isa = PBXBuildFile; fileRef = 615C9F76DEEA89A8A3638328942C191B /* NetworkActivityPlugin.swift */; }; + 946AABD244DF0FA4F9BE1A018AF02D44 /* Take.swift in Sources */ = {isa = PBXBuildFile; fileRef = B2301559B216DC943D96B6C3EA6187EE /* Take.swift */; }; + 95563637A4972EEA70958AC205B9D88A /* TargetType.swift in Sources */ = {isa = PBXBuildFile; fileRef = 91834F0831C28901ECD936CE6E242605 /* TargetType.swift */; }; + 956ACEDE64971D2B3AE15D1EDAD4AB56 /* DistinctUntilChanged.swift in Sources */ = {isa = PBXBuildFile; fileRef = CFD438AE9A13700F3A27158491EDF9CD /* DistinctUntilChanged.swift */; }; + 95E194A3AABB5407231E898B6686F73E /* ConstraintMakerRelatable+Extensions.swift in Sources */ = {isa = PBXBuildFile; fileRef = 763C57CB99AAF692D5804D56D94FE7EA /* ConstraintMakerRelatable+Extensions.swift */; }; + 961B5042F0BFBD2C5FCDCCF40E2EA7CD /* UIButton+Rx.swift in Sources */ = {isa = PBXBuildFile; fileRef = 3497648C5E7B80D2ABC218A50A6CA389 /* UIButton+Rx.swift */; }; + 96C658C96E9D8CCC2C450D5615A348AF /* Amb.swift in Sources */ = {isa = PBXBuildFile; fileRef = ED35C12CB343C92F81259E4F33B299B5 /* Amb.swift */; }; + 96D8402B4AFC4AC7349F1B487D6EB08C /* Transformable.swift in Sources */ = {isa = PBXBuildFile; fileRef = 1DDD0126DBB77C7B793703E3B7918072 /* Transformable.swift */; }; + 96F9E4762C05BF7B009FA52FC18C18C5 /* NSObject+Rx+RawRepresentable.swift in Sources */ = {isa = PBXBuildFile; fileRef = E8FC0222908D1595E407695DD27A15FB /* NSObject+Rx+RawRepresentable.swift */; }; + 97F63B52ED34F3A5A222C208253462F1 /* Observable.swift in Sources */ = {isa = PBXBuildFile; fileRef = 4529DBA9667227E1B099ADC681AB5850 /* Observable.swift */; }; + 98CC71A93BBD481D6C77E99854E65282 /* HistoricalScheduler.swift in Sources */ = {isa = PBXBuildFile; fileRef = 086CC48512270C1C4BB20AE3B7A179F9 /* HistoricalScheduler.swift */; }; + 98F570DA48370453D648BD526FDAAEAA /* LayoutConstraintItem.swift in Sources */ = {isa = PBXBuildFile; fileRef = 97360AE19AF07AC87B391E1E0C708F18 /* LayoutConstraintItem.swift */; }; + 9930A6A180279D0493FB8DB95BF23C21 /* Moya+Alamofire.swift in Sources */ = {isa = PBXBuildFile; fileRef = D3D2E46D8BE94722DCF2428829BFE1C4 /* Moya+Alamofire.swift */; }; + 9A151985A3D24023E8B2996BF3EBA2BB /* RxCocoa.h in Headers */ = {isa = PBXBuildFile; fileRef = 057D6C489248FFA4166DD24D93435763 /* RxCocoa.h */; settings = {ATTRIBUTES = (Public, ); }; }; + 9A3537E0E6B50DE756E96CDB3AD4EDE3 /* MultipartFormData.swift in Sources */ = {isa = PBXBuildFile; fileRef = 8AD039748141FD7199964AF985765430 /* MultipartFormData.swift */; }; + 9ADE1DD7C6AD8B57FD158350A66EF8D0 /* SharedSequence+Operators+arity.swift in Sources */ = {isa = PBXBuildFile; fileRef = C22601C0B2814C78512F594A7731DE19 /* SharedSequence+Operators+arity.swift */; }; + 9AE3FEDB17CA68DFCD0BC534B8205E7A /* KFImage.swift in Sources */ = {isa = PBXBuildFile; fileRef = 9BAC09FA3F4AA34E2FD9045902942CE8 /* KFImage.swift */; }; + 9C14C583C78E7461369235D895A978B7 /* CPListItem+Kingfisher.swift in Sources */ = {isa = PBXBuildFile; fileRef = C963DD2091D258FD11B459ACF20AF09A /* CPListItem+Kingfisher.swift */; }; + 9C9548E8B4675954566202F7B87FF0E6 /* ConstraintConstantTarget.swift in Sources */ = {isa = PBXBuildFile; fileRef = E7B65070F724AC357CCEA7DBCA350373 /* ConstraintConstantTarget.swift */; }; + 9D798263C35826FDE38859EFF5CC9542 /* Bag+Rx.swift in Sources */ = {isa = PBXBuildFile; fileRef = 402F4EF7983996E485AA8AD6E305B46D /* Bag+Rx.swift */; }; + 9E02CFFEFE1BEC978B512286F03D31DA /* ConstraintInsetTarget.swift in Sources */ = {isa = PBXBuildFile; fileRef = 45FEC9077C3B5C14B02AB4E46F22E157 /* ConstraintInsetTarget.swift */; }; + 9E8BA4FB802EDCD492DAF618CA7BFCE8 /* SharedSequence.swift in Sources */ = {isa = PBXBuildFile; fileRef = 2B46D1FBCE62A21E03DAB229F57AD114 /* SharedSequence.swift */; }; + 9EED5194D92B5A4B4E81FF9D6D98B7E0 /* StartWith.swift in Sources */ = {isa = PBXBuildFile; fileRef = 3602398BB4B83B59240F9614C1DF5EA4 /* StartWith.swift */; }; + 9F370B3928A333AD7E41680A29B1F051 /* RxCollectionViewReactiveArrayDataSource.swift in Sources */ = {isa = PBXBuildFile; fileRef = E52F3E93B1A3D47F523D83D8473237C0 /* RxCollectionViewReactiveArrayDataSource.swift */; }; + 9FD204AB576F46B2AFA28B4074837ABC /* SerialDispatchQueueScheduler.swift in Sources */ = {isa = PBXBuildFile; fileRef = 154835255F9916E0769C0D71A8A3267C /* SerialDispatchQueueScheduler.swift */; }; + A0208B623442A26CB9157F193CBB4A7F /* Platform.Linux.swift in Sources */ = {isa = PBXBuildFile; fileRef = 06FAB48DA0C18A3EE1754D953DB58E96 /* Platform.Linux.swift */; }; + A03FDA8BC5741880B1EF11AFD248EF48 /* ConstraintOffsetTarget.swift in Sources */ = {isa = PBXBuildFile; fileRef = 1DCDE799B9543F90237D7DA862252A2B /* ConstraintOffsetTarget.swift */; }; + A0E5EC9E431A5BD01C4695BC6AE5DEDA /* ExtendCustomModelType.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5096A43515DC7129C76B0F73FC4B6049 /* ExtendCustomModelType.swift */; }; + A12579942726F0D2EC587B8ED74D6253 /* SwiftSupport.swift in Sources */ = {isa = PBXBuildFile; fileRef = 239DDF3AEECE822C3281639FD6546369 /* SwiftSupport.swift */; }; + A20321979D272B922CD60B531BD05F7F /* UIPickerView+Rx.swift in Sources */ = {isa = PBXBuildFile; fileRef = 96DB504A50F1E4FBCD16D5BC49EFCF0C /* UIPickerView+Rx.swift */; }; + A214A653E430C9079AA7B1090169262D /* UICollectionView+Rx.swift in Sources */ = {isa = PBXBuildFile; fileRef = D37B24A95EEF2249678FBE363925D312 /* UICollectionView+Rx.swift */; }; + A2A423B6246A35EB8FB11B1924389E05 /* RxMutableBox.swift in Sources */ = {isa = PBXBuildFile; fileRef = DEA1B032D5AF107EC317CDAE847D3CE5 /* RxMutableBox.swift */; }; + A3E3AB7C765C21AE17B1E6EE6560040C /* SnapKit-umbrella.h in Headers */ = {isa = PBXBuildFile; fileRef = 04860F824879B09726E0E71EE19968C8 /* SnapKit-umbrella.h */; settings = {ATTRIBUTES = (Public, ); }; }; + A3F2B57A7C28E3362A8E55F1B015D9C8 /* Accelerate.framework in Frameworks */ = {isa = PBXBuildFile; fileRef = D1336AFDB9F472B9E17B6861880F66FA /* Accelerate.framework */; }; + A473AE2DB5554BC6CB289664628012A5 /* ConnectableObservableType.swift in Sources */ = {isa = PBXBuildFile; fileRef = FA5485B4C3E504F337F2AD065ABAEF76 /* ConnectableObservableType.swift */; }; + A523488C60BF961290D0B1ABB9ADACEC /* RequestCompression.swift in Sources */ = {isa = PBXBuildFile; fileRef = 516DBB0CADC2C6DBC5C12C20E9C7DFE4 /* RequestCompression.swift */; }; + A549C0E0DBBD2D57F007FD6088F426BD /* Scan.swift in Sources */ = {isa = PBXBuildFile; fileRef = B3492495BDAA3EE808EBA7E27B444532 /* Scan.swift */; }; + A58048C722771C3C46C2623274174B7B /* SingleAssignmentDisposable.swift in Sources */ = {isa = PBXBuildFile; fileRef = F3DA46923ADA705C392069960BB60E9A /* SingleAssignmentDisposable.swift */; }; + A5A8BF973BFE9C9304372A26C9F2E35B /* ConstraintMakerExtendable.swift in Sources */ = {isa = PBXBuildFile; fileRef = 7CDE2F9CE2B04EA6687EE664E9B1F447 /* ConstraintMakerExtendable.swift */; }; + A606B3D514262F030ED18600F01588BF /* AsMaybe.swift in Sources */ = {isa = PBXBuildFile; fileRef = E08F77D6D513C32F418E1FC2AE7AD85A /* AsMaybe.swift */; }; + A61CDA7A9C259DC743A7553676B4E537 /* First.swift in Sources */ = {isa = PBXBuildFile; fileRef = ED443DD7A5B81CF799FF1A9B14CA60C8 /* First.swift */; }; + A67083E623272EF11F0ED2115AF7D273 /* KingfisherOptionsInfo.swift in Sources */ = {isa = PBXBuildFile; fileRef = B43B6B9F0AC1A3B441577C4268863C3B /* KingfisherOptionsInfo.swift */; }; + A674A2F3F5F0304A6524F702EA301B42 /* NSDecimalNumberTransform.swift in Sources */ = {isa = PBXBuildFile; fileRef = AAD6332E824227FDE29BB9A1CB1E6DA4 /* NSDecimalNumberTransform.swift */; }; + A6D2F8EBCCEE6CE64FA4964877BF89F3 /* Repeat.swift in Sources */ = {isa = PBXBuildFile; fileRef = 1E14FBC686914E2AF7C4383BFAA062B5 /* Repeat.swift */; }; + A6FFEA8E51C1C175570C501EB520CE5E /* CacheSerializer.swift in Sources */ = {isa = PBXBuildFile; fileRef = 27459C8DF241339CDE5DD49FB1C25C8D /* CacheSerializer.swift */; }; + A755043CEE0384C2BB9238AF2F200F4B /* AccessTokenPlugin.swift in Sources */ = {isa = PBXBuildFile; fileRef = 9D5A16599059CA238869B241131BA02D /* AccessTokenPlugin.swift */; }; + A766E407DA39FF588AEC62A4C30387A6 /* DispatchQueueConfiguration.swift in Sources */ = {isa = PBXBuildFile; fileRef = 3956A13898BA7AE3AD6AED0406907F52 /* DispatchQueueConfiguration.swift */; }; + A77BC5063F494F8F4F92644B6A8C93E0 /* Foundation.framework in Frameworks */ = {isa = PBXBuildFile; fileRef = 6A1970A14C2672638850C555C17ADE89 /* Foundation.framework */; }; + A88B62F0F6C55645EE179934998FB6AC /* Reusable.swift in Sources */ = {isa = PBXBuildFile; fileRef = 0D924D0F2142E1C7FED799E98F5B5A2C /* Reusable.swift */; }; + A93FC5BCB5B02182D27377A3724A60B1 /* RxSearchControllerDelegateProxy.swift in Sources */ = {isa = PBXBuildFile; fileRef = 192C6CC3B7F6F517C4D157448480ECF7 /* RxSearchControllerDelegateProxy.swift */; }; + A9FB28DEC9FEAD03294A753F0C6A738B /* Producer.swift in Sources */ = {isa = PBXBuildFile; fileRef = E1876E647F0F13D8AD9A41FED3B7C6C2 /* Producer.swift */; }; + AA721ECC2B36AFB7D9FE70C83E6D63F9 /* Response.swift in Sources */ = {isa = PBXBuildFile; fileRef = CCB3459EBA17D69CB52198314FF7186C /* Response.swift */; }; + AAA7A11591D6E4B06124708291C37698 /* RxTabBarDelegateProxy.swift in Sources */ = {isa = PBXBuildFile; fileRef = 74F603E9DCC9F74E70AC2EEF9A832481 /* RxTabBarDelegateProxy.swift */; }; + AACC3B4A90C3C71FEF3BB1C2FC0374F1 /* Maybe.swift in Sources */ = {isa = PBXBuildFile; fileRef = 6673F5D40ED1C9BF12C1C9864D29C16B /* Maybe.swift */; }; + AAFBF86E17174FF6DD3BBA2BB393D3EA /* ImagePrefetcher.swift in Sources */ = {isa = PBXBuildFile; fileRef = DCD283B934B4346CF12CEB62458A829D /* ImagePrefetcher.swift */; }; + AB60B7775C160D5D62FBC93FAC8F90EC /* Moya-umbrella.h in Headers */ = {isa = PBXBuildFile; fileRef = 126D7923B95B1B893763329F065ECC1C /* Moya-umbrella.h */; settings = {ATTRIBUTES = (Public, ); }; }; + AB88D7A71BA82D3BAF097C992BFB221B /* UISearchController+Rx.swift in Sources */ = {isa = PBXBuildFile; fileRef = 7A6CCF2E51B64ED58E9F5F6BC18C4500 /* UISearchController+Rx.swift */; }; + ABD5C72702876EFB6C39BCC62269DED2 /* BooleanDisposable.swift in Sources */ = {isa = PBXBuildFile; fileRef = 1E088C67BD72950301BB89F16F31469A /* BooleanDisposable.swift */; }; + AC3FB067C57DB569636CAFD05974F484 /* BinaryDisposable.swift in Sources */ = {isa = PBXBuildFile; fileRef = 765D531DF5050A417659B07DDB7A51B1 /* BinaryDisposable.swift */; }; + AC5802EA58F43F1223804D5CF9E51A31 /* Completable.swift in Sources */ = {isa = PBXBuildFile; fileRef = DFDBA24A5039ED5E5456D2E8FC495205 /* Completable.swift */; }; + AC8A2E59A2B5FFAD78AD95F4B053DB76 /* ShareReplayScope.swift in Sources */ = {isa = PBXBuildFile; fileRef = 61ADA54F40A6900545707A222D69889B /* ShareReplayScope.swift */; }; + ACA3DBC73A19F3CDF9C4FAB09988D0E6 /* RxScrollViewDelegateProxy.swift in Sources */ = {isa = PBXBuildFile; fileRef = 165629B479649391782C794AE7C8E435 /* RxScrollViewDelegateProxy.swift */; }; + AD635D9C6B76653B9049C2767A165CDC /* AsyncLock.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5318EE8340C75CB1C311FB0C5C0035CE /* AsyncLock.swift */; }; + AD75E7744AC7055BD537E5F9E4A098B4 /* CredentialsPlugin.swift in Sources */ = {isa = PBXBuildFile; fileRef = B2679DB8FCA54DDF8E7DA3AC4A11488F /* CredentialsPlugin.swift */; }; + AE64B504EC63283C3EEC47A88A0C5F43 /* ObservableConvertibleType+Infallible.swift in Sources */ = {isa = PBXBuildFile; fileRef = 10D600B6F7169DFD7E81912260743F3F /* ObservableConvertibleType+Infallible.swift */; }; + AEF083E81756E640AB92BFF5CC853355 /* PrimitiveSequence+Zip+arity.swift in Sources */ = {isa = PBXBuildFile; fileRef = FC28EF831FDDD06091CC7AB0416845FC /* PrimitiveSequence+Zip+arity.swift */; }; + AF0C1DE86BD97C967EAD57DD459EDE65 /* Sink.swift in Sources */ = {isa = PBXBuildFile; fileRef = D389385F88DD239B71595D6B278BC5EA /* Sink.swift */; }; + AFAC1D4EBD53A048346210536741DF13 /* CoreGraphics.framework in Frameworks */ = {isa = PBXBuildFile; fileRef = 7160612C75B8C873D77B5AEDED76632B /* CoreGraphics.framework */; }; + AFAEE9EC6534DE2F69C1FD33B034C92E /* KingfisherError.swift in Sources */ = {isa = PBXBuildFile; fileRef = CD4F149DBFD18F4A20A4320599D8CC19 /* KingfisherError.swift */; }; + B00B8088EB50EA3F0F875993C675F421 /* UITextField+Rx.swift in Sources */ = {isa = PBXBuildFile; fileRef = BE8D91CD998AB1AE8E676FD3F36C8F2D /* UITextField+Rx.swift */; }; + B03B5579590D528CBA6D11FF638BC2AF /* Typealiases.swift in Sources */ = {isa = PBXBuildFile; fileRef = 1EF2CDD729DADF5969E617BB9AD37B87 /* Typealiases.swift */; }; + B0EF3E2802E1715202F99325EAE0F27A /* Task.swift in Sources */ = {isa = PBXBuildFile; fileRef = F02A17D4EB2C620CA1EDD34E9934989F /* Task.swift */; }; + B13CAD74E806387CF131495AD8CF453F /* Lock.swift in Sources */ = {isa = PBXBuildFile; fileRef = 259AF82D05F6D3AF5D26FB0CCF6354E5 /* Lock.swift */; }; + B17D933C8F8BC6A4F91AA620D7D7A870 /* ParameterEncoder.swift in Sources */ = {isa = PBXBuildFile; fileRef = CA8EB7DF526B4C2F17EB0BBE0F8760CC /* ParameterEncoder.swift */; }; + B274128C2FE5EDE87850D4C9B996F4C8 /* PriorityQueue.swift in Sources */ = {isa = PBXBuildFile; fileRef = 8DD8CAC74ECCE5DF13BE36C29354F6B3 /* PriorityQueue.swift */; }; + B3167FEDC691D1DDF267F855CFF33636 /* DelegateProxy.swift in Sources */ = {isa = PBXBuildFile; fileRef = 33B4FAC947A0378CAAD60F6A6B4DBCC6 /* DelegateProxy.swift */; }; + B3F14F1B196B5858BD951366FA89FA6D /* RxWKNavigationDelegateProxy.swift in Sources */ = {isa = PBXBuildFile; fileRef = 4488B560629B5C88A5E9FF2ED9FCDFD5 /* RxWKNavigationDelegateProxy.swift */; }; + B43017FEC99D227D4CDD81DD2C27D9D9 /* ConstraintMakerPrioritizable.swift in Sources */ = {isa = PBXBuildFile; fileRef = E0231B13AFD942D7715BD4A70ABFE808 /* ConstraintMakerPrioritizable.swift */; }; + B4AE9B23299C9CE3B70FAA7A66D50F7C /* SchedulerType.swift in Sources */ = {isa = PBXBuildFile; fileRef = 69D940AC28230A45C640E32E10438178 /* SchedulerType.swift */; }; + B4BA49385319831FD3A3921DFCF76230 /* ObserverBase.swift in Sources */ = {isa = PBXBuildFile; fileRef = 207583CD61F84971AE55DE2ACF2B29A9 /* ObserverBase.swift */; }; + B4ED29084E130F41F61D6E4B15DB3551 /* RxSwift-umbrella.h in Headers */ = {isa = PBXBuildFile; fileRef = F1A40D020BF4C65249FEA2EDF53B89F5 /* RxSwift-umbrella.h */; settings = {ATTRIBUTES = (Public, ); }; }; + B52177FF72FDAC3EDB7195DE98F5501E /* QuartzCore.framework in Frameworks */ = {isa = PBXBuildFile; fileRef = FB540682DA51451BDAD851F89E558DD5 /* QuartzCore.framework */; }; + B53EB1446767571221ED954E16FDE1AA /* Disposables.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56D520627040A3B6D58DF009393C985E /* Disposables.swift */; }; + B59095D5EF330419B3ADFBAD7EBC2B1F /* NSButton+Rx.swift in Sources */ = {isa = PBXBuildFile; fileRef = AC6F737678C4E112EBB6476E99F02B44 /* NSButton+Rx.swift */; }; + B5ACECCDD52AF69EBA2E11666BBAEB42 /* RxCollectionViewDataSourceProxy.swift in Sources */ = {isa = PBXBuildFile; fileRef = 42D446B359AD540FA2AEFD87D7ABE15C /* RxCollectionViewDataSourceProxy.swift */; }; + B5E5A2CB9CD57723F8117D9402A80FD3 /* SingleAsync.swift in Sources */ = {isa = PBXBuildFile; fileRef = 33055FA32252223B1AB3116721D6096B /* SingleAsync.swift */; }; + B66C3C5709346F849100234EFCDB664E /* Queue.swift in Sources */ = {isa = PBXBuildFile; fileRef = 94C392D9062D4196B340E6F77067B6F2 /* Queue.swift */; }; + B752F7C4BECB65894B1F49421049CE5F /* ConstraintView.swift in Sources */ = {isa = PBXBuildFile; fileRef = 0D0D830BAD1F66163C68EB9A1BA9E147 /* ConstraintView.swift */; }; + BA5658B6C27A81FA4665E507A1ED88DA /* Driver+Subscription.swift in Sources */ = {isa = PBXBuildFile; fileRef = 19B406112800825F5B01A0BBED47F0BE /* Driver+Subscription.swift */; }; + BAB17A1C6CAD14B3788973EAF8466C93 /* NetworkReachabilityManager.swift in Sources */ = {isa = PBXBuildFile; fileRef = 4917FB9D005872281B22F006F7001E9E /* NetworkReachabilityManager.swift */; }; + BAD3834746DAB3C038417D16101B29A2 /* NSControl+Rx.swift in Sources */ = {isa = PBXBuildFile; fileRef = DCEC2DBF8E26969A4BB2B54F2B1EA8A7 /* NSControl+Rx.swift */; }; + BB72FC9215BD907A82AE928782813D6C /* NSObject+Rx.swift in Sources */ = {isa = PBXBuildFile; fileRef = 64FA3F6B350E532395A97AB96530BE97 /* NSObject+Rx.swift */; }; + BBC7EE440D9B9A4B3511B1831C428A0D /* Catch.swift in Sources */ = {isa = PBXBuildFile; fileRef = 4B40027C27CE4E459A38C1D87C106545 /* Catch.swift */; }; + BBD437FE6BFF63452E6B7E08DFAB4DD9 /* UIBarButtonItem+Rx.swift in Sources */ = {isa = PBXBuildFile; fileRef = F75DD06A2A169049C9A0D1E77A6D13EA /* UIBarButtonItem+Rx.swift */; }; + BBDD1E970F7D15CEA5E1F39F47641664 /* ObservableType+Extensions.swift in Sources */ = {isa = PBXBuildFile; fileRef = CD8E57ECFD6B142763B5C63323162920 /* ObservableType+Extensions.swift */; }; + BC16AFDE4BAC1CD19CDE329F20CC6EC4 /* CallbackQueue.swift in Sources */ = {isa = PBXBuildFile; fileRef = 75C831D0F3B6ECF5593AC202900F9B4F /* CallbackQueue.swift */; }; + BC5A53F94EAA2F46352749E54BE69838 /* Source.swift in Sources */ = {isa = PBXBuildFile; fileRef = 1BC8BE591A383FB0802A1161825B227F /* Source.swift */; }; + BD47CB74CD9B2B4D2D942C9B65748DFB /* SnapKit-dummy.m in Sources */ = {isa = PBXBuildFile; fileRef = ECAC747BA8670ABD37A0C5AA715875AF /* SnapKit-dummy.m */; }; + BE432D00488E08C853DC689BE24C54F4 /* HandyJSON-dummy.m in Sources */ = {isa = PBXBuildFile; fileRef = 2C97BCD706DEE807EF3868F37A8ECCA1 /* HandyJSON-dummy.m */; }; + BFDCAD2AEBDD1AEF0345EE96D33DAC94 /* Create.swift in Sources */ = {isa = PBXBuildFile; fileRef = 6F85D9716CFD2A169AB2FC3954F8916B /* Create.swift */; }; + C00C4FF56C3B54CEB62ACA9DFB166FCD /* DelaySubscription.swift in Sources */ = {isa = PBXBuildFile; fileRef = 3F6E79FDA2485804EB4B20DAEDA26366 /* DelaySubscription.swift */; }; + C04739CBCEE445B66192BFA708655EDF /* StringEncoding+Alamofire.swift in Sources */ = {isa = PBXBuildFile; fileRef = 6FE1258734CD0D5DE5C0C1545F096DAF /* StringEncoding+Alamofire.swift */; }; + C12DCA02D36C5C6167F566AFC96A6057 /* _RXObjCRuntime.m in Sources */ = {isa = PBXBuildFile; fileRef = A208FBE87421B2ABC0142F6A07D0B553 /* _RXObjCRuntime.m */; }; + C17A8818F6F518F4367C0C551782FB3B /* Range.swift in Sources */ = {isa = PBXBuildFile; fileRef = BF481B014D924D41F0FDE7089D3263B0 /* Range.swift */; }; + C20F7278CDDB5021D18140A001BA7470 /* Infallible+Create.swift in Sources */ = {isa = PBXBuildFile; fileRef = 94CA369E5A9E7E47E7DBCAAD6F63D296 /* Infallible+Create.swift */; }; + C2D4FEEAF01038DB5C31CA401C105476 /* _RXDelegateProxy.m in Sources */ = {isa = PBXBuildFile; fileRef = CF309802F2CAB75940F49AD77E8DFA05 /* _RXDelegateProxy.m */; }; + C378AC3DF57A41F6F16D01BBD7A1BB02 /* UIActivityIndicatorView+Rx.swift in Sources */ = {isa = PBXBuildFile; fileRef = 55D10B797A89889598E86DF39D020451 /* UIActivityIndicatorView+Rx.swift */; }; + C39C9E0F5F4CB376E9C8286E5838B7DD /* BehaviorSubject.swift in Sources */ = {isa = PBXBuildFile; fileRef = C689E3BB4983E6D479A62F1211506E90 /* BehaviorSubject.swift */; }; + C46DF9765B3769C9EDA8BCC7052B6D23 /* LockOwnerType.swift in Sources */ = {isa = PBXBuildFile; fileRef = FBD96A9F6932FA01432273082AB94D9C /* LockOwnerType.swift */; }; + C4E9B6DBCE3A78C2127FA3A6269E57CA /* KFImageOptions.swift in Sources */ = {isa = PBXBuildFile; fileRef = BE3D4635725BE29F6866D4B1964447A8 /* KFImageOptions.swift */; }; + C538C2B3F5A5D6BA85BBDCB544777AD4 /* Utils.swift in Sources */ = {isa = PBXBuildFile; fileRef = ECBD12025121C746DDEB9B44E608E3E6 /* Utils.swift */; }; + C549FDEDD8E7F6D7AE0B15C125D183A8 /* Foundation.framework in Frameworks */ = {isa = PBXBuildFile; fileRef = 6A1970A14C2672638850C555C17ADE89 /* Foundation.framework */; }; + C6A1AF1239CD2F0D4745BAA097E1E63F /* RxCollectionViewDelegateProxy.swift in Sources */ = {isa = PBXBuildFile; fileRef = 90028E4B472E1FCD0B7A391D37BC0C80 /* RxCollectionViewDelegateProxy.swift */; }; + C784A7AAD94DD830A9EB5ADDEE6DE1BB /* KVORepresentable.swift in Sources */ = {isa = PBXBuildFile; fileRef = E8A3665F113C176C699C4A60D6739452 /* KVORepresentable.swift */; }; + C79B457EA34AAC885AABAAB4FE227837 /* UITableView+Reusable.swift in Sources */ = {isa = PBXBuildFile; fileRef = 95F799040C1A70E136CAE7A41476545C /* UITableView+Reusable.swift */; }; + C812836F779AF53458795EEF5066F29A /* ScheduledItem.swift in Sources */ = {isa = PBXBuildFile; fileRef = ED806FA43E5458BB64EB1B488B5B6772 /* ScheduledItem.swift */; }; + C8269B42DED12AB1F275648D0BD32E45 /* URLEncodedFormEncoder.swift in Sources */ = {isa = PBXBuildFile; fileRef = 0FE18AD6C78E4D9C1E9EDB83E8763861 /* URLEncodedFormEncoder.swift */; }; + C920144CE195D2198DAE63F2D976AADB /* HandyJSON-umbrella.h in Headers */ = {isa = PBXBuildFile; fileRef = E6EA7642AC0A935140B695C8DE1F91B1 /* HandyJSON-umbrella.h */; settings = {ATTRIBUTES = (Public, ); }; }; + CA1BFC94E5AD2E95C061B14902827755 /* ExtensionHelpers.swift in Sources */ = {isa = PBXBuildFile; fileRef = 501CF92DCF5E2F25FE033F445BAA7A3A /* ExtensionHelpers.swift */; }; + CB3ACAC0625702DEC5BBB5F9AC0CC737 /* RxTableViewReactiveArrayDataSource.swift in Sources */ = {isa = PBXBuildFile; fileRef = EEB214E2E4C3D3FB6CA0C4109D2F0FF6 /* RxTableViewReactiveArrayDataSource.swift */; }; + CBF35F58D74E7F9E25EA97F82CBCEA10 /* SkipWhile.swift in Sources */ = {isa = PBXBuildFile; fileRef = 4B32547DF2C9A9E64087A593AC3EE911 /* SkipWhile.swift */; }; + CC5BC4391CF7452AF3254D8CAFC82062 /* ImageTransition.swift in Sources */ = {isa = PBXBuildFile; fileRef = 2686E2F30E71D302C7EC46BF9AC726BE /* ImageTransition.swift */; }; + CCADF670B558392F08CC5302CE8DFC34 /* SynchronizedOnType.swift in Sources */ = {isa = PBXBuildFile; fileRef = 37706A10928DD59317F2AABB995786F0 /* SynchronizedOnType.swift */; }; + CCBCFE35FEFAD9C1307334491148DA27 /* RxRelay-umbrella.h in Headers */ = {isa = PBXBuildFile; fileRef = 6DEEF0A78457ED9D46DBF84E913E83F6 /* RxRelay-umbrella.h */; settings = {ATTRIBUTES = (Public, ); }; }; + CDD0A0D9253EFF9923F92E89BC96A882 /* SwitchIfEmpty.swift in Sources */ = {isa = PBXBuildFile; fileRef = E83D56D118A8CD729AB9F4DD106214B6 /* SwitchIfEmpty.swift */; }; + CE08483A41A5535019BE5E198792480B /* KVORepresentable+Swift.swift in Sources */ = {isa = PBXBuildFile; fileRef = 7B953B1CDFABA00A04E6AC9124999CF9 /* KVORepresentable+Swift.swift */; }; + CEB12B808790BBA447EF912D41AB9C78 /* DispatchQueue+Extensions.swift in Sources */ = {isa = PBXBuildFile; fileRef = 0BBE9868390C0ACA219A59A1F61C4F09 /* DispatchQueue+Extensions.swift */; }; + CF32140300489AD5D6D5A74E4605FDAF /* DispatchQueue+Extensions.swift in Sources */ = {isa = PBXBuildFile; fileRef = 24119F92E2DB0B0C6650DEA1131020F3 /* DispatchQueue+Extensions.swift */; }; + CF7FAB0C5D474E379798F82E5DB4092B /* ContextDescriptorType.swift in Sources */ = {isa = PBXBuildFile; fileRef = 1B2863E7FB03DAF37957D8B19A20FAF5 /* ContextDescriptorType.swift */; }; + CFB94F60324C50650E055314D46837BA /* PrivacyInfo.xcprivacy in Resources */ = {isa = PBXBuildFile; fileRef = 8B776E2E2FACA7C1A7173E403F37910F /* PrivacyInfo.xcprivacy */; }; + D0560E8E2E5EB407B5D8E0381BF453FA /* URLConvertible+URLRequestConvertible.swift in Sources */ = {isa = PBXBuildFile; fileRef = DF65591BAA77BD5923D4083691EB5F0F /* URLConvertible+URLRequestConvertible.swift */; }; + D072D375CE0C6D2F4A98A57FEEBF6BA2 /* Zip+arity.swift in Sources */ = {isa = PBXBuildFile; fileRef = DCE9ED04C9F6410492A87A2B8BC43451 /* Zip+arity.swift */; }; + D09FBBADAF7C5C757AA5AB5DFE54BD25 /* Alamofire-dummy.m in Sources */ = {isa = PBXBuildFile; fileRef = 78F5BA1E49C1B6FE56A4B5323CD9AFF8 /* Alamofire-dummy.m */; }; + D2004A03ADD62CD0C4649710F32A91F5 /* NSTextStorage+Rx.swift in Sources */ = {isa = PBXBuildFile; fileRef = 932FF7024616D8D82633AB22546C7DC0 /* NSTextStorage+Rx.swift */; }; + D2032194EB7D200A1F6715A3C024D994 /* CombineLatest.swift in Sources */ = {isa = PBXBuildFile; fileRef = 02F4A94A543B7090414D2D11E1C5F3A2 /* CombineLatest.swift */; }; + D204501A876D178E882CF0D3CAA30473 /* VirtualTimeScheduler.swift in Sources */ = {isa = PBXBuildFile; fileRef = DA54EB4CF78AC3516E9E65506DE207FB /* VirtualTimeScheduler.swift */; }; + D2C1DE6833F16A9EDEAE12D39DBBECD8 /* SubscribeOn.swift in Sources */ = {isa = PBXBuildFile; fileRef = 79A0A26C9F36ABCC4EB50D474EC8DA4D /* SubscribeOn.swift */; }; + D2C293D847E95B01671EB3E6A32F11C7 /* WKWebView+Rx.swift in Sources */ = {isa = PBXBuildFile; fileRef = 8051259FDEC630E944D8CD2114B0226B /* WKWebView+Rx.swift */; }; + D3318EE7E4339E6C5A6070D251DC845F /* Rx.swift in Sources */ = {isa = PBXBuildFile; fileRef = 8C1E768C4764D3F7B03199D967453517 /* Rx.swift */; }; + D33F8516AAC7AC1435DCB095BCE65681 /* CFNetwork.framework in Frameworks */ = {isa = PBXBuildFile; fileRef = 6D74FF06CA5AE8F2F5D48301BE439D32 /* CFNetwork.framework */; }; + D368E6F70C5E6998548A72E65F92432D /* Validation.swift in Sources */ = {isa = PBXBuildFile; fileRef = 383C3B11450462CA845076D5A31455A7 /* Validation.swift */; }; + D3AB490FA372E1922315D4F2E5709254 /* InfiniteSequence.swift in Sources */ = {isa = PBXBuildFile; fileRef = DEBFD271D48A85EF07F3B6731D534416 /* InfiniteSequence.swift */; }; + D3BC528010D39EB2D79585A671FD80B6 /* UIScrollView+Rx.swift in Sources */ = {isa = PBXBuildFile; fileRef = A5C55ED5BE5E14115CFDB19FC0330C46 /* UIScrollView+Rx.swift */; }; + D47B1058991EEC007A109B8E354EDB80 /* ObservableConvertibleType+Signal.swift in Sources */ = {isa = PBXBuildFile; fileRef = EFD03F6EF61FF91A6224DD8CF8BF2FCE /* ObservableConvertibleType+Signal.swift */; }; + D4933D17DC286C3DABCFD930BED56DD9 /* UIGestureRecognizer+Rx.swift in Sources */ = {isa = PBXBuildFile; fileRef = B089112AF8A786152A4CFA32042AA817 /* UIGestureRecognizer+Rx.swift */; }; + D4A79D2D2532673DF39ED456EB7005CF /* TakeWithPredicate.swift in Sources */ = {isa = PBXBuildFile; fileRef = 9BF394511EEFCC9854970C278A4EEFAB /* TakeWithPredicate.swift */; }; + D507CB260B300128E39601CD83627509 /* Reactive.swift in Sources */ = {isa = PBXBuildFile; fileRef = 98358BCC95E6655702825CEE45C0C8FA /* Reactive.swift */; }; + D525A536B7A32329405A34062C2BCED6 /* Decode.swift in Sources */ = {isa = PBXBuildFile; fileRef = 08095C11257E23D25E208304881B3A90 /* Decode.swift */; }; + D5CFDCFE3128D6FA2A4D385FDFD42AA1 /* URLRequest+Encoding.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5859599DB876A373ACA4D7088EA30151 /* URLRequest+Encoding.swift */; }; + D6FDE9DFAC4AA548A9A4E2D6BBCE54FC /* ControlProperty+Driver.swift in Sources */ = {isa = PBXBuildFile; fileRef = F7B5707C4DB109E219C5031257DCD1F3 /* ControlProperty+Driver.swift */; }; + D73BED39648BD901FA022356FD6A4468 /* RecursiveScheduler.swift in Sources */ = {isa = PBXBuildFile; fileRef = 09071625C0D4ED0715EBF9938CAB0C6B /* RecursiveScheduler.swift */; }; + D7BCBE1EB4A638403C265CE2199EFF1B /* CFNetwork.framework in Frameworks */ = {isa = PBXBuildFile; fileRef = 6D74FF06CA5AE8F2F5D48301BE439D32 /* CFNetwork.framework */; }; + D7CB5610FA8E358DDBBCFC468EA56DAF /* String+MD5.swift in Sources */ = {isa = PBXBuildFile; fileRef = 0DD70DADAD30E2F4D27E3DD7A1EAC006 /* String+MD5.swift */; }; + D8548F55D2A30E5935CD1773CFD1510E /* ImageDownloader.swift in Sources */ = {isa = PBXBuildFile; fileRef = 3C27EB2E04E045DFB79BE6AAA63A7EA2 /* ImageDownloader.swift */; }; + D9CC66222E55827BDBE32EFAB31B5381 /* KFOptionsSetter.swift in Sources */ = {isa = PBXBuildFile; fileRef = C8B66F25D7F18C08892764CAD99E025D /* KFOptionsSetter.swift */; }; + DADAAFFCDC241D3E6A4DCF567C12D280 /* RequestTypeWrapper.swift in Sources */ = {isa = PBXBuildFile; fileRef = 9B09861BBDC46C3D1F767E4F57F0FCD6 /* RequestTypeWrapper.swift */; }; + DB975FF8F6C9DE0D5B319961CAEDD4E1 /* AtomicInt.swift in Sources */ = {isa = PBXBuildFile; fileRef = 0A998D586FC04E7F45D15D9E8E02E70B /* AtomicInt.swift */; }; + DBD70DE28BDBC4B1C09EEBA3F6D76BF3 /* UIButton+Kingfisher.swift in Sources */ = {isa = PBXBuildFile; fileRef = A8D08D8E537F6EC253D8EBE79FC6542A /* UIButton+Kingfisher.swift */; }; + DC4F588F90F6E49F9B67F0782B392E39 /* PrimitiveSequence.swift in Sources */ = {isa = PBXBuildFile; fileRef = 065A74676EEAD75E1F49A21AACEAF349 /* PrimitiveSequence.swift */; }; + DDC0F4786752FBF4B07E3A4D4E273DA2 /* UICollectionView+Reusable.swift in Sources */ = {isa = PBXBuildFile; fileRef = 016AA1ECBFE5BEF6D881059F1B2DD9BC /* UICollectionView+Reusable.swift */; }; + DE71610B229DF6E2B65A8574BAF21414 /* SectionedViewDataSourceType.swift in Sources */ = {isa = PBXBuildFile; fileRef = C32614C0F923CC34E7C2BE3F692976AB /* SectionedViewDataSourceType.swift */; }; + DEBBCD7FF906F4D5F2CC4BF62F3A5803 /* Completable+AndThen.swift in Sources */ = {isa = PBXBuildFile; fileRef = A2D58F2F6C7CC4D368CE0D57F40CD27B /* Completable+AndThen.swift */; }; + E0D995EBFD58A33805684F01024138E7 /* BehaviorRelay.swift in Sources */ = {isa = PBXBuildFile; fileRef = 9382A27EEA32D49627659BC72C56FCBF /* BehaviorRelay.swift */; }; + E154CD956DF116A1E59C8D6A6891A9BF /* Cancelable.swift in Sources */ = {isa = PBXBuildFile; fileRef = B0D85CAD20866F6833A22BDA6668ECB1 /* Cancelable.swift */; }; + E21CC70AD211E5F874C1208BA7D1631E /* Sequence.swift in Sources */ = {isa = PBXBuildFile; fileRef = E68CB21AF7E7B8C4BFF5A00B209D9666 /* Sequence.swift */; }; + E2EF09A2D0A87418F0628B2CFAD304D8 /* Metadata.swift in Sources */ = {isa = PBXBuildFile; fileRef = AB1E15FD768D00EEFADE79898DA43AA2 /* Metadata.swift */; }; + E3B0F5D520566D7244B300501D43F86E /* Multicast.swift in Sources */ = {isa = PBXBuildFile; fileRef = AD3FD403D8E30A8001D1F494B36EFA49 /* Multicast.swift */; }; + E424F89BEDDE19083BAAB0FA1D73E853 /* Binder.swift in Sources */ = {isa = PBXBuildFile; fileRef = CF107C4AC5643080B30C4DC1AD3CA088 /* Binder.swift */; }; + E4AC5D4B5B930DDF6912483ED8436635 /* WithUnretained.swift in Sources */ = {isa = PBXBuildFile; fileRef = 95509362358E1B4F96EED27DC01B1C24 /* WithUnretained.swift */; }; + E4CA5C8A54DD0978858EE82D7D78ECB1 /* VirtualTimeConverterType.swift in Sources */ = {isa = PBXBuildFile; fileRef = 634E359FC76F57C6E032A112422B8130 /* VirtualTimeConverterType.swift */; }; + E54EA1C1B2B9304A9F7956AE0C9589D2 /* SerialDisposable.swift in Sources */ = {isa = PBXBuildFile; fileRef = 28E9D0CEE48F6310B3A68093744A1146 /* SerialDisposable.swift */; }; + E6251F02EE12804D1B66AE32E716E664 /* SessionDelegate.swift in Sources */ = {isa = PBXBuildFile; fileRef = E597FA331BDE835D4356BA91AC2EE05B /* SessionDelegate.swift */; }; + E6599DE13C01C6FA8F79536A8970DD3A /* Reusable-dummy.m in Sources */ = {isa = PBXBuildFile; fileRef = D205770569FAE2C81B52F154322D2563 /* Reusable-dummy.m */; }; + E65F73FA2E14351853CD4EB8729D0AC7 /* Errors.swift in Sources */ = {isa = PBXBuildFile; fileRef = 1E818ED04F94422CB5C8B2554572826C /* Errors.swift */; }; + E7035A074129575E62A0136DD93D8E8F /* DateTransform.swift in Sources */ = {isa = PBXBuildFile; fileRef = 64854FC0AC6AFE7ACB68D2C7BEAAE398 /* DateTransform.swift */; }; + E710A550162879CE918FC411CF567789 /* Logger.swift in Sources */ = {isa = PBXBuildFile; fileRef = 418F325839254785FCE40E01EC615D42 /* Logger.swift */; }; + E7123AB366D99D42043E352B1A128369 /* Foundation.framework in Frameworks */ = {isa = PBXBuildFile; fileRef = 6A1970A14C2672638850C555C17ADE89 /* Foundation.framework */; }; + E7378F61AD6959D5538E595EA4A48AF4 /* AVAssetImageDataProvider.swift in Sources */ = {isa = PBXBuildFile; fileRef = 420DDEA65A2C63C6CA966D994E696D54 /* AVAssetImageDataProvider.swift */; }; + E7B06E98F3530C96FB6B2D8272169C22 /* Endpoint.swift in Sources */ = {isa = PBXBuildFile; fileRef = 6C198ADB3A802CC083707D46D42F735C /* Endpoint.swift */; }; + E7C58133036040A730E4546D0C0DE87F /* Reusable-umbrella.h in Headers */ = {isa = PBXBuildFile; fileRef = CBFCE48108EA5B7391D309F207FA3E5A /* Reusable-umbrella.h */; settings = {ATTRIBUTES = (Public, ); }; }; + E895A8F95627AB1F7C2F1D7B035BAE1C /* ScheduledDisposable.swift in Sources */ = {isa = PBXBuildFile; fileRef = 42F715AC86D9585FC5BB7F7C07DD7DAC /* ScheduledDisposable.swift */; }; + E95D6E6462506EFD8EA9332AD9BC492A /* SizeExtensions.swift in Sources */ = {isa = PBXBuildFile; fileRef = 840E59B83C8C092BD38138A7D44A473E /* SizeExtensions.swift */; }; + E98DC8FB2578E76A812E0C94BA10E1B1 /* ConstraintDirectionalInsets.swift in Sources */ = {isa = PBXBuildFile; fileRef = 8A18BCB5C7FD8D506C4D66B8A1BE5B63 /* ConstraintDirectionalInsets.swift */; }; + E99A170AB4E460307ACAFC938CA2B591 /* ToArray.swift in Sources */ = {isa = PBXBuildFile; fileRef = 9FE96E6FECBEF720CD9DD849F12E6D61 /* ToArray.swift */; }; + EA5FE4B4B3BF04976C37430E4F3721EF /* RxPickerViewDelegateProxy.swift in Sources */ = {isa = PBXBuildFile; fileRef = B4F8C603320BB82716CEBA31405BB25A /* RxPickerViewDelegateProxy.swift */; }; + EBE8A06FA3C662A9D01320EF1FD0E120 /* RefCountDisposable.swift in Sources */ = {isa = PBXBuildFile; fileRef = 69C17E66AE494BF8C88740E1EDB36891 /* RefCountDisposable.swift */; }; + ECE6F23823454A8FDB3F97CE1A7CD182 /* RedirectHandler.swift in Sources */ = {isa = PBXBuildFile; fileRef = C0F94D368DE622488019CFFA18E34262 /* RedirectHandler.swift */; }; + ECF2F956B37A4C28B228BC291A57AD6E /* RequestTaskMap.swift in Sources */ = {isa = PBXBuildFile; fileRef = 44142825DF6D5162BCAC2FEFBF148BED /* RequestTaskMap.swift */; }; + ED3841B1E7CECC078D6BCDD78FDA7E36 /* SchedulerServices+Emulation.swift in Sources */ = {isa = PBXBuildFile; fileRef = E78DB89A84C09AD3FA55F3FEF697370C /* SchedulerServices+Emulation.swift */; }; + ED4155032D3BF65BD7B649E490A6EEFE /* TakeLast.swift in Sources */ = {isa = PBXBuildFile; fileRef = 0705C992AE1A7F2F2FF703DD1338C3F7 /* TakeLast.swift */; }; + ED71E932B7F30AD7CFD2A04968A2B5CC /* CBridge.swift in Sources */ = {isa = PBXBuildFile; fileRef = E2CC1F55AB1BB43F87FEC4D4CD10D1FE /* CBridge.swift */; }; + EE4E233D2DD0DFC4F82FD6748EC3429F /* ImageBinder.swift in Sources */ = {isa = PBXBuildFile; fileRef = 79AB56ECFE81336CFFB52ADF927D8A7C /* ImageBinder.swift */; }; + EEFF0A57765CB734CF01868904F56DA7 /* HandyJSON.h in Headers */ = {isa = PBXBuildFile; fileRef = 1710DBE3C7151B8AB47F7A9F74055B64 /* HandyJSON.h */; settings = {ATTRIBUTES = (Public, ); }; }; + EF21586EC3DFF6097A58EEC87376A0C1 /* ConstraintLayoutGuideDSL.swift in Sources */ = {isa = PBXBuildFile; fileRef = 6EBE2A5988B01C477AFF1CE3128EE8AF /* ConstraintLayoutGuideDSL.swift */; }; + EF6DD06709E5EFD67031FF9B5901A827 /* RxTableViewDelegateProxy.swift in Sources */ = {isa = PBXBuildFile; fileRef = 8807FF18BB93251158B72386A622E490 /* RxTableViewDelegateProxy.swift */; }; + F006EB7A9EF6612EE871EBBF1EE4655B /* ObservableConvertibleType.swift in Sources */ = {isa = PBXBuildFile; fileRef = A2FB155675AB0F9CD4391CE05510152D /* ObservableConvertibleType.swift */; }; + F038D81F7ABAA15CF03246AD4BF334F7 /* Alamofire-umbrella.h in Headers */ = {isa = PBXBuildFile; fileRef = 166CB5B3B91C1FF4370249653FD8320D /* Alamofire-umbrella.h */; settings = {ATTRIBUTES = (Public, ); }; }; + F0483870DE1B0E2DD94DAAA7287E46AD /* Infallible+Concurrency.swift in Sources */ = {isa = PBXBuildFile; fileRef = E4AD07036A83707DD229318C03B6CE81 /* Infallible+Concurrency.swift */; }; + F07878596C474719C556096025C2E9E4 /* Zip+Collection.swift in Sources */ = {isa = PBXBuildFile; fileRef = CC92DDE2881965C74B23F6A422B435B3 /* Zip+Collection.swift */; }; + F0D6C540C0CAEFE51A29FC9C5867096E /* GroupBy.swift in Sources */ = {isa = PBXBuildFile; fileRef = 22B9AC50C1A66CFB12BF81596173CD39 /* GroupBy.swift */; }; + F16D0BB1231D60CBF7B3AE25B92D0D74 /* EnumTransform.swift in Sources */ = {isa = PBXBuildFile; fileRef = 9D3BCD1EA3553D12354FD5FA1FAE15CC /* EnumTransform.swift */; }; + F2415AE8678DE2698B7AD7D88B1A5C0F /* AlamofireExtended.swift in Sources */ = {isa = PBXBuildFile; fileRef = A3F6B5834C04BE54692EFEF14936348F /* AlamofireExtended.swift */; }; + F2B61F23B613A4D92CE8459C4BE431BE /* AnyObserver.swift in Sources */ = {isa = PBXBuildFile; fileRef = 692E3C85CC1223B95D6A9605B661FA68 /* AnyObserver.swift */; }; + F2DDF679DF721DDA14A53744DD540092 /* NSSlider+Rx.swift in Sources */ = {isa = PBXBuildFile; fileRef = 7B6C73A34CCB4FCB54A17345BD0051FC /* NSSlider+Rx.swift */; }; + F2EF471EA98AA31CA53CEE65F76F151E /* Merge.swift in Sources */ = {isa = PBXBuildFile; fileRef = F45DCBE864FA17C68B639547AEB93B03 /* Merge.swift */; }; + F3617B01FE1D713C9E39D57E32C905AE /* NibLoadable.swift in Sources */ = {isa = PBXBuildFile; fileRef = 2B48BE2A6404DB81C7324A3CE9177FCA /* NibLoadable.swift */; }; + F3B4A826460EF6A9B19849D1E7AF6A52 /* ControlEvent+Signal.swift in Sources */ = {isa = PBXBuildFile; fileRef = 9A2C43D00EDD3B8E5B6D1AC17B1E48E1 /* ControlEvent+Signal.swift */; }; + F3ED4CDEB88F2CFB6AE17AEB4C59F210 /* RetryWhen.swift in Sources */ = {isa = PBXBuildFile; fileRef = 29305731B01CF8E4A32561061D6EA1AE /* RetryWhen.swift */; }; + F575822C8B7F17129429E00A9081ECA2 /* SessionDelegate.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5A549727CCD5C1657E53A8BAE5E58145 /* SessionDelegate.swift */; }; + F5AF27692F3A5C9087F015B5C40A35E7 /* RxTarget.swift in Sources */ = {isa = PBXBuildFile; fileRef = C526294611337A8D4EF5C3D3D571C77B /* RxTarget.swift */; }; + F60E2B85B28D1E27FD52F9B0D62A50C8 /* _RXKVOObserver.m in Sources */ = {isa = PBXBuildFile; fileRef = 3B45D252945E879A3B88C8989E5C2CC6 /* _RXKVOObserver.m */; }; + F66CC47AD425C8D57BD149AFD09C2AFE /* HTTPMethod.swift in Sources */ = {isa = PBXBuildFile; fileRef = 6E269149DE9BA1B81C3504720A668420 /* HTTPMethod.swift */; }; + F6E94E8EE1CE35F49B9091BE8748587B /* Result+Alamofire.swift in Sources */ = {isa = PBXBuildFile; fileRef = A0CB4A2B49E071E7012FEE7D28B8B467 /* Result+Alamofire.swift */; }; + F7425A58E24926CCAC413F85D403B9FA /* FieldDescriptor.swift in Sources */ = {isa = PBXBuildFile; fileRef = 6438C8BA15E4054D7ACA1E3DFF2066DB /* FieldDescriptor.swift */; }; + F7774F70F3F7CD7E11F01BD8B62FFF15 /* URLSession+Rx.swift in Sources */ = {isa = PBXBuildFile; fileRef = 69B3A5BB96CFA43786C0ACFCF6162F46 /* URLSession+Rx.swift */; }; + F79760816256C3B04E54319DA3A105E2 /* ElementAt.swift in Sources */ = {isa = PBXBuildFile; fileRef = EC50DBE03FF22FAAF1D4BE41AAFB9A8A /* ElementAt.swift */; }; + F7C0960CEEB8F0C18F4503B405EAC08F /* ConstraintMultiplierTarget.swift in Sources */ = {isa = PBXBuildFile; fileRef = ADE256164152BE966B102C5F104FC06F /* ConstraintMultiplierTarget.swift */; }; + F953AA9104BFE0C2DAD639EA60104A75 /* ConstraintView+Extensions.swift in Sources */ = {isa = PBXBuildFile; fileRef = FAC78FA49D7FB72A1D9081306F499298 /* ConstraintView+Extensions.swift */; }; + F97840AF9065A123E8B1DABA7D95BB9D /* Runtime.swift in Sources */ = {isa = PBXBuildFile; fileRef = 4A9962A1E3D931E363F3C4D48522361B /* Runtime.swift */; }; + F9821B669566BA01F845426DC6834E76 /* Observable+Bind.swift in Sources */ = {isa = PBXBuildFile; fileRef = 645BF6563AFCDBF6A94CF2E1A387FA8C /* Observable+Bind.swift */; }; + F98E3202B0021DC8B2DB77256FBE5DD3 /* ISO8601DateTransform.swift in Sources */ = {isa = PBXBuildFile; fileRef = C8B337D475349119A9023DB9A04FAED7 /* ISO8601DateTransform.swift */; }; + FA823A5BF5E118ADBC89B7CCD6B433A3 /* Disposable.swift in Sources */ = {isa = PBXBuildFile; fileRef = 7AD5F75086AF715FAD56BDDA5876EA2B /* Disposable.swift */; }; + FAB03959C2357E325B19E08BC4775DAB /* ConstraintMaker.swift in Sources */ = {isa = PBXBuildFile; fileRef = A35CA8960849EFAC715838CF15CFD05D /* ConstraintMaker.swift */; }; + FAF7C9C4F9B6AE2CE9F5866B210D9275 /* SharedSequence+Operators.swift in Sources */ = {isa = PBXBuildFile; fileRef = E520F3EC8458D3F1E6174E0EC460E79B /* SharedSequence+Operators.swift */; }; + FBBA4924C2C83A3715D6F04B1E6E64C4 /* Response.swift in Sources */ = {isa = PBXBuildFile; fileRef = C2265CF40B5E3E71870047392079AF16 /* Response.swift */; }; + FC44FD753ECE619F3F635F28B1221DEF /* Foundation.framework in Frameworks */ = {isa = PBXBuildFile; fileRef = 6A1970A14C2672638850C555C17ADE89 /* Foundation.framework */; }; + FC4568452A01ACA7090C8B78CF6FFF5A /* Storage.swift in Sources */ = {isa = PBXBuildFile; fileRef = 2AE83D49E82297DF5D76F3A85D2DBEF1 /* Storage.swift */; }; + FCA5D79BFD9CAE6F09CF2D9E4CCB7C9B /* InfiniteSequence.swift in Sources */ = {isa = PBXBuildFile; fileRef = E20F55B135E3C24173DF453318747D59 /* InfiniteSequence.swift */; }; + FCD9660A73D7E00EA19E2F2295876E04 /* NSTextView+Rx.swift in Sources */ = {isa = PBXBuildFile; fileRef = 0CA26D23785504CD85C0BA05F5263AB7 /* NSTextView+Rx.swift */; }; + FDBC11E754B3FD24CE89D3587C34793D /* DisposeBag.swift in Sources */ = {isa = PBXBuildFile; fileRef = D5405426B1D820B97554FFA85005A6A7 /* DisposeBag.swift */; }; + FDE4F53FC806778F0FEE26810D359D79 /* Debug.swift in Sources */ = {isa = PBXBuildFile; fileRef = 99155CE8434026F99E70418FAEF41EEA /* Debug.swift */; }; + FE9261A1344AF922C1EFCB457B938425 /* BehaviorRelay+Driver.swift in Sources */ = {isa = PBXBuildFile; fileRef = 48BEA0546BD26740F65A619717216925 /* BehaviorRelay+Driver.swift */; }; + FFEA28FE74753ABA9BDD87EDB46E5910 /* Platform.Linux.swift in Sources */ = {isa = PBXBuildFile; fileRef = 14F206D32E3EFDDDBDCA5B559448999B /* Platform.Linux.swift */; }; +/* End PBXBuildFile section */ + +/* Begin PBXContainerItemProxy section */ + 1658A2BFA314B61B2A73634AD62CE881 /* PBXContainerItemProxy */ = { + isa = PBXContainerItemProxy; + containerPortal = BFDFE7DC352907FC980B868725387E98 /* Project object */; + proxyType = 1; + remoteGlobalIDString = 17F9141D333DA1A7BE5937F227221070; + remoteInfo = Moya; + }; + 2945BE7CD469F91A2F51C450AFA05666 /* PBXContainerItemProxy */ = { + isa = PBXContainerItemProxy; + containerPortal = BFDFE7DC352907FC980B868725387E98 /* Project object */; + proxyType = 1; + remoteGlobalIDString = 82B0A41D3031FF27D78E17B0A9A46FB0; + remoteInfo = MBProgressHUD; + }; + 304B703E396722BB916969650EE3ECE3 /* PBXContainerItemProxy */ = { + isa = PBXContainerItemProxy; + containerPortal = BFDFE7DC352907FC980B868725387E98 /* Project object */; + proxyType = 1; + remoteGlobalIDString = 4622BFEF3DC16E8BD15EEFC30D4D0084; + remoteInfo = RxRelay; + }; + 355C8F2CEBF2108145CF958E67525E6C /* PBXContainerItemProxy */ = { + isa = PBXContainerItemProxy; + containerPortal = BFDFE7DC352907FC980B868725387E98 /* Project object */; + proxyType = 1; + remoteGlobalIDString = 542460E7CDF2A9D5B2ECB5F8CE549E34; + remoteInfo = Reusable; + }; + 374C7A97590E5FE0A51BFBBD65FB78D1 /* PBXContainerItemProxy */ = { + isa = PBXContainerItemProxy; + containerPortal = BFDFE7DC352907FC980B868725387E98 /* Project object */; + proxyType = 1; + remoteGlobalIDString = 7AD0C6DCDC9CEC8A3C7C10C7FEE07BE6; + remoteInfo = RxCocoa; + }; + 4C27EC4B5188F89173A9C29D169E0032 /* PBXContainerItemProxy */ = { + isa = PBXContainerItemProxy; + containerPortal = BFDFE7DC352907FC980B868725387E98 /* Project object */; + proxyType = 1; + remoteGlobalIDString = EA9EA43B3B503823EE36C60D9C8A865F; + remoteInfo = RxSwift; + }; + 6FE4ADF80639F6BB7A8166750DAACBCB /* PBXContainerItemProxy */ = { + isa = PBXContainerItemProxy; + containerPortal = BFDFE7DC352907FC980B868725387E98 /* Project object */; + proxyType = 1; + remoteGlobalIDString = 19622742EBA51E823D6DAE3F8CDBFAD4; + remoteInfo = SnapKit; + }; + 72174616F0F2B6A658A39627B9B3AB27 /* PBXContainerItemProxy */ = { + isa = PBXContainerItemProxy; + containerPortal = BFDFE7DC352907FC980B868725387E98 /* Project object */; + proxyType = 1; + remoteGlobalIDString = EAAA1AD3A8A1B59AB91319EE40752C6D; + remoteInfo = Alamofire; + }; + 9453D1A2DED6629FB2E6B2F47B5861EC /* PBXContainerItemProxy */ = { + isa = PBXContainerItemProxy; + containerPortal = BFDFE7DC352907FC980B868725387E98 /* Project object */; + proxyType = 1; + remoteGlobalIDString = EA9EA43B3B503823EE36C60D9C8A865F; + remoteInfo = RxSwift; + }; + A699C0A386EEF6602AED63A3F0386D29 /* PBXContainerItemProxy */ = { + isa = PBXContainerItemProxy; + containerPortal = BFDFE7DC352907FC980B868725387E98 /* Project object */; + proxyType = 1; + remoteGlobalIDString = 9828BBC09E9FB1238624113D7456E59E; + remoteInfo = "Kingfisher-Kingfisher"; + }; + B250CBDA21743BA7F971FA3FFEF57DAA /* PBXContainerItemProxy */ = { + isa = PBXContainerItemProxy; + containerPortal = BFDFE7DC352907FC980B868725387E98 /* Project object */; + proxyType = 1; + remoteGlobalIDString = EA9EA43B3B503823EE36C60D9C8A865F; + remoteInfo = RxSwift; + }; + D55789695C0CB9279A0E694653D0BE12 /* PBXContainerItemProxy */ = { + isa = PBXContainerItemProxy; + containerPortal = BFDFE7DC352907FC980B868725387E98 /* Project object */; + proxyType = 1; + remoteGlobalIDString = E8022D22FAA6690B5E1C379C1BCE1491; + remoteInfo = Kingfisher; + }; + D7630C5D5DEF74799EEF3A89A7518F08 /* PBXContainerItemProxy */ = { + isa = PBXContainerItemProxy; + containerPortal = BFDFE7DC352907FC980B868725387E98 /* Project object */; + proxyType = 1; + remoteGlobalIDString = EAAA1AD3A8A1B59AB91319EE40752C6D; + remoteInfo = Alamofire; + }; + DB1DC5BEA8CCBF1B3FD2396BBBEC7A93 /* PBXContainerItemProxy */ = { + isa = PBXContainerItemProxy; + containerPortal = BFDFE7DC352907FC980B868725387E98 /* Project object */; + proxyType = 1; + remoteGlobalIDString = 4622BFEF3DC16E8BD15EEFC30D4D0084; + remoteInfo = RxRelay; + }; + FF15280D6E3817C68943D4D47FCE6488 /* PBXContainerItemProxy */ = { + isa = PBXContainerItemProxy; + containerPortal = BFDFE7DC352907FC980B868725387E98 /* Project object */; + proxyType = 1; + remoteGlobalIDString = 10D88C24864319FF583AD6D156896F32; + remoteInfo = HandyJSON; + }; +/* End PBXContainerItemProxy section */ + +/* Begin PBXFileReference section */ + 002ED0D813882532198DEB9328551828 /* Image.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = Image.swift; path = Sources/Moya/Image.swift; sourceTree = ""; }; + 005B0AA170372B033FC09D4E58FBAC9A /* ImageDataProvider.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = ImageDataProvider.swift; path = Sources/General/ImageSource/ImageDataProvider.swift; sourceTree = ""; }; + 013009926D6AF27C596929D48AB266B6 /* Moya-prefix.pch */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.h; path = "Moya-prefix.pch"; sourceTree = ""; }; + 016AA1ECBFE5BEF6D881059F1B2DD9BC /* UICollectionView+Reusable.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = "UICollectionView+Reusable.swift"; path = "Sources/View/UICollectionView+Reusable.swift"; sourceTree = ""; }; + 017CB031F08EF999D20BCEE492444892 /* Reusable-prefix.pch */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.h; path = "Reusable-prefix.pch"; sourceTree = ""; }; + 0292DCF642DD7EA1D1116B8623A8C599 /* KingfisherManager.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = KingfisherManager.swift; path = Sources/General/KingfisherManager.swift; sourceTree = ""; }; + 02F4A94A543B7090414D2D11E1C5F3A2 /* CombineLatest.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = CombineLatest.swift; path = RxSwift/Observables/CombineLatest.swift; sourceTree = ""; }; + 03480C2AB8FE1C2C40314057985B0228 /* RxCocoa-Info.plist */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = text.plist.xml; path = "RxCocoa-Info.plist"; sourceTree = ""; }; + 03B41EBBD593C680744DAD960E245F91 /* Reusable.debug.xcconfig */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = text.xcconfig; path = Reusable.debug.xcconfig; sourceTree = ""; }; + 045D5D90782798F36E8E8F973DAC5B28 /* AnyEncodable.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = AnyEncodable.swift; path = Sources/Moya/AnyEncodable.swift; sourceTree = ""; }; + 04860F824879B09726E0E71EE19968C8 /* SnapKit-umbrella.h */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.h; path = "SnapKit-umbrella.h"; sourceTree = ""; }; + 0487859709F230146392D21D1B192DC0 /* Switch.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = Switch.swift; path = RxSwift/Observables/Switch.swift; sourceTree = ""; }; + 057D6C489248FFA4166DD24D93435763 /* RxCocoa.h */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.h; name = RxCocoa.h; path = RxCocoa/RxCocoa.h; sourceTree = ""; }; + 05C2B32ED7987DD94725453C00328CE3 /* Notifications.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = Notifications.swift; path = Source/Notifications.swift; sourceTree = ""; }; + 065A74676EEAD75E1F49A21AACEAF349 /* PrimitiveSequence.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = PrimitiveSequence.swift; path = RxSwift/Traits/PrimitiveSequence/PrimitiveSequence.swift; sourceTree = ""; }; + 06FAB48DA0C18A3EE1754D953DB58E96 /* Platform.Linux.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = Platform.Linux.swift; path = Platform/Platform.Linux.swift; sourceTree = ""; }; + 0705C992AE1A7F2F2FF703DD1338C3F7 /* TakeLast.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = TakeLast.swift; path = RxSwift/Observables/TakeLast.swift; sourceTree = ""; }; + 07360B313B37C9A5C5310D3E0442D54B /* Plugin.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = Plugin.swift; path = Sources/Moya/Plugin.swift; sourceTree = ""; }; + 0764DAF106A0E6A03874313AD80FDDB7 /* MoyaProvider+Internal.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = "MoyaProvider+Internal.swift"; path = "Sources/Moya/MoyaProvider+Internal.swift"; sourceTree = ""; }; + 08095C11257E23D25E208304881B3A90 /* Decode.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = Decode.swift; path = RxSwift/Observables/Decode.swift; sourceTree = ""; }; + 086CC48512270C1C4BB20AE3B7A179F9 /* HistoricalScheduler.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = HistoricalScheduler.swift; path = RxSwift/Schedulers/HistoricalScheduler.swift; sourceTree = ""; }; + 089F4ED85F7C9FD8E053CA99D41D3132 /* UITextView+Rx.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = "UITextView+Rx.swift"; path = "RxCocoa/iOS/UITextView+Rx.swift"; sourceTree = ""; }; + 09071625C0D4ED0715EBF9938CAB0C6B /* RecursiveScheduler.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = RecursiveScheduler.swift; path = RxSwift/Schedulers/RecursiveScheduler.swift; sourceTree = ""; }; + 0A4ABF00795A4D24AA39AE0648DAAFF8 /* NibOwnerLoadable.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = NibOwnerLoadable.swift; path = Sources/View/NibOwnerLoadable.swift; sourceTree = ""; }; + 0A998D586FC04E7F45D15D9E8E02E70B /* AtomicInt.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = AtomicInt.swift; path = Platform/AtomicInt.swift; sourceTree = ""; }; + 0AA9F81ECF26C389EB0017F3D63D208A /* SnapKit-Info.plist */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = text.plist.xml; path = "SnapKit-Info.plist"; sourceTree = ""; }; + 0BBE9868390C0ACA219A59A1F61C4F09 /* DispatchQueue+Extensions.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = "DispatchQueue+Extensions.swift"; path = "Platform/DispatchQueue+Extensions.swift"; sourceTree = ""; }; + 0CA26D23785504CD85C0BA05F5263AB7 /* NSTextView+Rx.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = "NSTextView+Rx.swift"; path = "RxCocoa/macOS/NSTextView+Rx.swift"; sourceTree = ""; }; + 0D0D830BAD1F66163C68EB9A1BA9E147 /* ConstraintView.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = ConstraintView.swift; path = Sources/ConstraintView.swift; sourceTree = ""; }; + 0D5B6D4F9F8CF76D040623D82B12D15E /* _RX.m */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.objc; name = _RX.m; path = RxCocoa/Runtime/_RX.m; sourceTree = ""; }; + 0D924D0F2142E1C7FED799E98F5B5A2C /* Reusable.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = Reusable.swift; path = Sources/View/Reusable.swift; sourceTree = ""; }; + 0DD70DADAD30E2F4D27E3DD7A1EAC006 /* String+MD5.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = "String+MD5.swift"; path = "Sources/Utility/String+MD5.swift"; sourceTree = ""; }; + 0E6A6730169419E002FF07C1AE880F77 /* ConstraintMakerFinalizable.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = ConstraintMakerFinalizable.swift; path = Sources/ConstraintMakerFinalizable.swift; sourceTree = ""; }; + 0F1253A739AF193B8223BE13ABA2A2BE /* UISearchBar+Rx.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = "UISearchBar+Rx.swift"; path = "RxCocoa/iOS/UISearchBar+Rx.swift"; sourceTree = ""; }; + 0F2F174FA9B884D41464BD84265273E9 /* StoryboardBased.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = StoryboardBased.swift; path = Sources/Storyboard/StoryboardBased.swift; sourceTree = ""; }; + 0F964475871A4284F485DC930EB7FE0D /* ImageContext.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = ImageContext.swift; path = Sources/SwiftUI/ImageContext.swift; sourceTree = ""; }; + 0FE18AD6C78E4D9C1E9EDB83E8763861 /* URLEncodedFormEncoder.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = URLEncodedFormEncoder.swift; path = Source/URLEncodedFormEncoder.swift; sourceTree = ""; }; + 105DC924B68D07DCCA5F7BBD13103F15 /* KF.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = KF.swift; path = Sources/General/KF.swift; sourceTree = ""; }; + 107549C133EE5267BA358393A90EF059 /* MBProgressHUD-prefix.pch */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.h; path = "MBProgressHUD-prefix.pch"; sourceTree = ""; }; + 10D600B6F7169DFD7E81912260743F3F /* ObservableConvertibleType+Infallible.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = "ObservableConvertibleType+Infallible.swift"; path = "RxSwift/Traits/Infallible/ObservableConvertibleType+Infallible.swift"; sourceTree = ""; }; + 10DF3559568462A634A6F7EE6FFBCA00 /* Observable+Concurrency.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = "Observable+Concurrency.swift"; path = "RxSwift/Observable+Concurrency.swift"; sourceTree = ""; }; + 11D7747447E5C511F9D8307F10E5168C /* KFImageRenderer.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = KFImageRenderer.swift; path = Sources/SwiftUI/KFImageRenderer.swift; sourceTree = ""; }; + 126D7923B95B1B893763329F065ECC1C /* Moya-umbrella.h */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.h; path = "Moya-umbrella.h"; sourceTree = ""; }; + 14F206D32E3EFDDDBDCA5B559448999B /* Platform.Linux.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = Platform.Linux.swift; path = Platform/Platform.Linux.swift; sourceTree = ""; }; + 1517F2B568C0846F286EF269D17902A5 /* Optional.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = Optional.swift; path = RxSwift/Observables/Optional.swift; sourceTree = ""; }; + 154835255F9916E0769C0D71A8A3267C /* SerialDispatchQueueScheduler.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = SerialDispatchQueueScheduler.swift; path = RxSwift/Schedulers/SerialDispatchQueueScheduler.swift; sourceTree = ""; }; + 160D2BDCA79733E1BBB01B00F9404132 /* UISlider+Rx.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = "UISlider+Rx.swift"; path = "RxCocoa/iOS/UISlider+Rx.swift"; sourceTree = ""; }; + 165629B479649391782C794AE7C8E435 /* RxScrollViewDelegateProxy.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = RxScrollViewDelegateProxy.swift; path = RxCocoa/iOS/Proxies/RxScrollViewDelegateProxy.swift; sourceTree = ""; }; + 166CB5B3B91C1FF4370249653FD8320D /* Alamofire-umbrella.h */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.h; path = "Alamofire-umbrella.h"; sourceTree = ""; }; + 16B897EE9E0FB539D6DCE44EC4FE5968 /* BuiltInBasicType.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = BuiltInBasicType.swift; path = Source/BuiltInBasicType.swift; sourceTree = ""; }; + 1710DBE3C7151B8AB47F7A9F74055B64 /* HandyJSON.h */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.h; name = HandyJSON.h; path = Source/HandyJSON.h; sourceTree = ""; }; + 17D5BC96435F4DD211BCF227E506B92E /* TVMonogramView+Kingfisher.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = "TVMonogramView+Kingfisher.swift"; path = "Sources/Extensions/TVMonogramView+Kingfisher.swift"; sourceTree = ""; }; + 17D7B878065E9387C23C43CFACC3A867 /* SubjectType.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = SubjectType.swift; path = RxSwift/Subjects/SubjectType.swift; sourceTree = ""; }; + 1828EE850F0785BEBBEEB6381406536B /* Box.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = Box.swift; path = Sources/Utility/Box.swift; sourceTree = ""; }; + 18C45484AE9F211603671E126686D88F /* CurrentThreadScheduler.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = CurrentThreadScheduler.swift; path = RxSwift/Schedulers/CurrentThreadScheduler.swift; sourceTree = ""; }; + 191A401108B388D3700F7B69157F58FA /* SharedSequence+Concurrency.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = "SharedSequence+Concurrency.swift"; path = "RxCocoa/Traits/SharedSequence/SharedSequence+Concurrency.swift"; sourceTree = ""; }; + 192C6CC3B7F6F517C4D157448480ECF7 /* RxSearchControllerDelegateProxy.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = RxSearchControllerDelegateProxy.swift; path = RxCocoa/iOS/Proxies/RxSearchControllerDelegateProxy.swift; sourceTree = ""; }; + 19B406112800825F5B01A0BBED47F0BE /* Driver+Subscription.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = "Driver+Subscription.swift"; path = "RxCocoa/Traits/Driver/Driver+Subscription.swift"; sourceTree = ""; }; + 19B712EE8F117D2EC35F9A295028959B /* RxSwift.release.xcconfig */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = text.xcconfig; path = RxSwift.release.xcconfig; sourceTree = ""; }; + 19D15B6F087615D6E6964610E2461AAD /* Alamofire.debug.xcconfig */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = text.xcconfig; path = Alamofire.debug.xcconfig; sourceTree = ""; }; + 1A5104776E2AD589EF6B4A0B49E9EB80 /* Pods-yinmeng-ios-frameworks.sh */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = text.script.sh; path = "Pods-yinmeng-ios-frameworks.sh"; sourceTree = ""; }; + 1A5F64B79665DAAF7330A9B901B15EFF /* UINavigationController+Rx.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = "UINavigationController+Rx.swift"; path = "RxCocoa/iOS/UINavigationController+Rx.swift"; sourceTree = ""; }; + 1A9CF67CD4186CDC93B9439A7C72E036 /* HandyJSON.release.xcconfig */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = text.xcconfig; path = HandyJSON.release.xcconfig; sourceTree = ""; }; + 1B2863E7FB03DAF37957D8B19A20FAF5 /* ContextDescriptorType.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = ContextDescriptorType.swift; path = Source/ContextDescriptorType.swift; sourceTree = ""; }; + 1BBD7BC93FC22FBD9C79EAB4AC435A7E /* Pods-yinmeng-ios-dummy.m */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.objc; path = "Pods-yinmeng-ios-dummy.m"; sourceTree = ""; }; + 1BBE63969630CA64CDD14AE518F9ED70 /* HelpingMapper.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = HelpingMapper.swift; path = Source/HelpingMapper.swift; sourceTree = ""; }; + 1BC8BE591A383FB0802A1161825B227F /* Source.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = Source.swift; path = Sources/General/ImageSource/Source.swift; sourceTree = ""; }; + 1C7BAB5978403A78EBF174C01FF8C71E /* Event.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = Event.swift; path = RxSwift/Event.swift; sourceTree = ""; }; + 1CCA1BCCD3C2E9007F3F56C9E8AC6398 /* DisposeBase.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = DisposeBase.swift; path = RxSwift/Disposables/DisposeBase.swift; sourceTree = ""; }; + 1CEDEE8EE3D758478549E54DB2D8CB8D /* TransformType.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = TransformType.swift; path = Source/TransformType.swift; sourceTree = ""; }; + 1D524DB6FB9E645710C7B04B107FB333 /* MultiTarget.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = MultiTarget.swift; path = Sources/Moya/MultiTarget.swift; sourceTree = ""; }; + 1DCDE799B9543F90237D7DA862252A2B /* ConstraintOffsetTarget.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = ConstraintOffsetTarget.swift; path = Sources/ConstraintOffsetTarget.swift; sourceTree = ""; }; + 1DDD0126DBB77C7B793703E3B7918072 /* Transformable.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = Transformable.swift; path = Source/Transformable.swift; sourceTree = ""; }; + 1E088C67BD72950301BB89F16F31469A /* BooleanDisposable.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = BooleanDisposable.swift; path = RxSwift/Disposables/BooleanDisposable.swift; sourceTree = ""; }; + 1E14FBC686914E2AF7C4383BFAA062B5 /* Repeat.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = Repeat.swift; path = RxSwift/Observables/Repeat.swift; sourceTree = ""; }; + 1E818ED04F94422CB5C8B2554572826C /* Errors.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = Errors.swift; path = RxSwift/Errors.swift; sourceTree = ""; }; + 1EF2CDD729DADF5969E617BB9AD37B87 /* Typealiases.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = Typealiases.swift; path = Sources/Typealiases.swift; sourceTree = ""; }; + 1FCF2D3324E392803C9EFBB38E7A9ABA /* RxTableViewDataSourcePrefetchingProxy.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = RxTableViewDataSourcePrefetchingProxy.swift; path = RxCocoa/iOS/Proxies/RxTableViewDataSourcePrefetchingProxy.swift; sourceTree = ""; }; + 207583CD61F84971AE55DE2ACF2B29A9 /* ObserverBase.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = ObserverBase.swift; path = RxSwift/Observers/ObserverBase.swift; sourceTree = ""; }; + 20B0FF4D5789DB2CC388939C196538A9 /* Kingfisher-prefix.pch */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.h; path = "Kingfisher-prefix.pch"; sourceTree = ""; }; + 215B8518AD4396707F88E578B313121F /* MultipartFormData.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = MultipartFormData.swift; path = Source/MultipartFormData.swift; sourceTree = ""; }; + 21E4BE15EF64CDD45908BF2A541F2A66 /* AsSingle.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = AsSingle.swift; path = RxSwift/Observables/AsSingle.swift; sourceTree = ""; }; + 220B3F8A303994576980CB9C15199150 /* Alamofire.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = Alamofire.swift; path = Source/Alamofire.swift; sourceTree = ""; }; + 22B9AC50C1A66CFB12BF81596173CD39 /* GroupBy.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = GroupBy.swift; path = RxSwift/Observables/GroupBy.swift; sourceTree = ""; }; + 236F15BC43D0758FE90E506F41ABBD36 /* Pods-yinmeng-ios-acknowledgements.markdown */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = text; path = "Pods-yinmeng-ios-acknowledgements.markdown"; sourceTree = ""; }; + 239DDF3AEECE822C3281639FD6546369 /* SwiftSupport.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = SwiftSupport.swift; path = RxSwift/SwiftSupport/SwiftSupport.swift; sourceTree = ""; }; + 24119F92E2DB0B0C6650DEA1131020F3 /* DispatchQueue+Extensions.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = "DispatchQueue+Extensions.swift"; path = "Platform/DispatchQueue+Extensions.swift"; sourceTree = ""; }; + 259AF82D05F6D3AF5D26FB0CCF6354E5 /* Lock.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = Lock.swift; path = RxSwift/Concurrency/Lock.swift; sourceTree = ""; }; + 25CF572152EDEF89E43D914242F08BE0 /* Empty.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = Empty.swift; path = RxSwift/Observables/Empty.swift; sourceTree = ""; }; + 2686E2F30E71D302C7EC46BF9AC726BE /* ImageTransition.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = ImageTransition.swift; path = Sources/Image/ImageTransition.swift; sourceTree = ""; }; + 26A2F37034623F4E9BF155F2042659EF /* RxTableViewDataSourceType.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = RxTableViewDataSourceType.swift; path = RxCocoa/iOS/Protocols/RxTableViewDataSourceType.swift; sourceTree = ""; }; + 27459C8DF241339CDE5DD49FB1C25C8D /* CacheSerializer.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = CacheSerializer.swift; path = Sources/Cache/CacheSerializer.swift; sourceTree = ""; }; + 2868D931558DCC05627934B9EF6362E6 /* ReplayRelay.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = ReplayRelay.swift; path = RxRelay/ReplayRelay.swift; sourceTree = ""; }; + 28E9D0CEE48F6310B3A68093744A1146 /* SerialDisposable.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = SerialDisposable.swift; path = RxSwift/Disposables/SerialDisposable.swift; sourceTree = ""; }; + 29305731B01CF8E4A32561061D6EA1AE /* RetryWhen.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = RetryWhen.swift; path = RxSwift/Observables/RetryWhen.swift; sourceTree = ""; }; + 29CBD6F8B67F5629CFB1D1326F23E28A /* Queue.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = Queue.swift; path = Platform/DataStructures/Queue.swift; sourceTree = ""; }; + 29D71D26A754963F763183793E0737A6 /* RxTextViewDelegateProxy.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = RxTextViewDelegateProxy.swift; path = RxCocoa/iOS/Proxies/RxTextViewDelegateProxy.swift; sourceTree = ""; }; + 2A1E8C07BD53C5A3B5242F95A74991F9 /* RxSwift-Info.plist */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = text.plist.xml; path = "RxSwift-Info.plist"; sourceTree = ""; }; + 2A271DE0F470E6D6B4CF963A21854DEA /* RetryPolicy.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = RetryPolicy.swift; path = Source/RetryPolicy.swift; sourceTree = ""; }; + 2A36E5193632E241668CBF9B7B2CB7D5 /* Enumerated.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = Enumerated.swift; path = RxSwift/Observables/Enumerated.swift; sourceTree = ""; }; + 2A8DE9D85F9B8D23A00C6EDE272AAE8D /* MangledName.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = MangledName.swift; path = Source/MangledName.swift; sourceTree = ""; }; + 2AE83D49E82297DF5D76F3A85D2DBEF1 /* Storage.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = Storage.swift; path = Sources/Cache/Storage.swift; sourceTree = ""; }; + 2AEBE0DF14984ECC53D005ED92A73024 /* WKInterfaceImage+Kingfisher.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = "WKInterfaceImage+Kingfisher.swift"; path = "Sources/Extensions/WKInterfaceImage+Kingfisher.swift"; sourceTree = ""; }; + 2B46D1FBCE62A21E03DAB229F57AD114 /* SharedSequence.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = SharedSequence.swift; path = RxCocoa/Traits/SharedSequence/SharedSequence.swift; sourceTree = ""; }; + 2B48BE2A6404DB81C7324A3CE9177FCA /* NibLoadable.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = NibLoadable.swift; path = Sources/View/NibLoadable.swift; sourceTree = ""; }; + 2B71FB79E7C0B7102E8EF89E2C326862 /* UISegmentedControl+Rx.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = "UISegmentedControl+Rx.swift"; path = "RxCocoa/iOS/UISegmentedControl+Rx.swift"; sourceTree = ""; }; + 2BAC1650A187C2915C972E5571EE0B96 /* RxCocoa-prefix.pch */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.h; path = "RxCocoa-prefix.pch"; sourceTree = ""; }; + 2C4725814B303164AE7425543FDA788C /* URLTransform.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = URLTransform.swift; path = Source/URLTransform.swift; sourceTree = ""; }; + 2C97BCD706DEE807EF3868F37A8ECCA1 /* HandyJSON-dummy.m */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.objc; path = "HandyJSON-dummy.m"; sourceTree = ""; }; + 2CB6A627D9F759981FF9B741C57D0E1D /* RxSwift.modulemap */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.module; path = RxSwift.modulemap; sourceTree = ""; }; + 2CCCFEF676D5297ACAAB23C1A5CB7CAE /* Moya-dummy.m */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.objc; path = "Moya-dummy.m"; sourceTree = ""; }; + 2D85DF2E1C33DB9B470D4EFFB7F4A1FC /* EventMonitor.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = EventMonitor.swift; path = Source/EventMonitor.swift; sourceTree = ""; }; + 2DAB2159DEB43FA519F6B8254AF5728E /* ObserverType.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = ObserverType.swift; path = RxSwift/ObserverType.swift; sourceTree = ""; }; + 2DAD506D24AC12D48E8C572B4C5B8674 /* Debounce.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = Debounce.swift; path = RxSwift/Observables/Debounce.swift; sourceTree = ""; }; + 2E6CA143EB6F64C9E9AD81EF8A9D3820 /* RxPickerViewAdapter.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = RxPickerViewAdapter.swift; path = RxCocoa/iOS/DataSources/RxPickerViewAdapter.swift; sourceTree = ""; }; + 2E78E508B94164D9227009C03D41986A /* ParameterEncoding.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = ParameterEncoding.swift; path = Source/ParameterEncoding.swift; sourceTree = ""; }; + 304C3471BD45700A1BFEFC1877E24B5A /* RxNavigationControllerDelegateProxy.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = RxNavigationControllerDelegateProxy.swift; path = RxCocoa/iOS/Proxies/RxNavigationControllerDelegateProxy.swift; sourceTree = ""; }; + 30F3EE79D4A82DDA5FBAD0C2C8D6753A /* AnonymousDisposable.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = AnonymousDisposable.swift; path = RxSwift/Disposables/AnonymousDisposable.swift; sourceTree = ""; }; + 31BB5D3806E36F2811C5F7E9C7E0A00B /* Indicator.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = Indicator.swift; path = Sources/Views/Indicator.swift; sourceTree = ""; }; + 32639E8193F95CA5F554F746CA3F05AD /* ConstraintMakerRelatable.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = ConstraintMakerRelatable.swift; path = Sources/ConstraintMakerRelatable.swift; sourceTree = ""; }; + 326857EAC596FAC2DD9D5071A5B96D15 /* RxCocoa.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = RxCocoa.swift; path = RxCocoa/RxCocoa.swift; sourceTree = ""; }; + 33055FA32252223B1AB3116721D6096B /* SingleAsync.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = SingleAsync.swift; path = RxSwift/Observables/SingleAsync.swift; sourceTree = ""; }; + 3397E4A82849848801375ABF4E7B4080 /* UIKit.framework */ = {isa = PBXFileReference; lastKnownFileType = wrapper.framework; name = UIKit.framework; path = Platforms/iPhoneOS.platform/Developer/SDKs/iPhoneOS14.0.sdk/System/Library/Frameworks/UIKit.framework; sourceTree = DEVELOPER_DIR; }; + 33B4FAC947A0378CAAD60F6A6B4DBCC6 /* DelegateProxy.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = DelegateProxy.swift; path = RxCocoa/Common/DelegateProxy.swift; sourceTree = ""; }; + 3497648C5E7B80D2ABC218A50A6CA389 /* UIButton+Rx.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = "UIButton+Rx.swift"; path = "RxCocoa/iOS/UIButton+Rx.swift"; sourceTree = ""; }; + 35651FD3900CCCFFCDA6DD8ECE470B93 /* _RXObjCRuntime.h */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.h; name = _RXObjCRuntime.h; path = RxCocoa/Runtime/include/_RXObjCRuntime.h; sourceTree = ""; }; + 3602398BB4B83B59240F9614C1DF5EA4 /* StartWith.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = StartWith.swift; path = RxSwift/Observables/StartWith.swift; sourceTree = ""; }; + 36683A54CDD175D2798404369B19387A /* ObservableType+PrimitiveSequence.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = "ObservableType+PrimitiveSequence.swift"; path = "RxSwift/Traits/PrimitiveSequence/ObservableType+PrimitiveSequence.swift"; sourceTree = ""; }; + 36DFFD75B7479E1705FAC0F110CE34DC /* Alamofire.release.xcconfig */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = text.xcconfig; path = Alamofire.release.xcconfig; sourceTree = ""; }; + 3756A9BBE41ABEE8DCBF5BCA6972C4DA /* Moya */ = {isa = PBXFileReference; explicitFileType = wrapper.framework; includeInIndex = 0; name = Moya; path = Moya.framework; sourceTree = BUILT_PRODUCTS_DIR; }; + 37706A10928DD59317F2AABB995786F0 /* SynchronizedOnType.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = SynchronizedOnType.swift; path = RxSwift/Concurrency/SynchronizedOnType.swift; sourceTree = ""; }; + 383C3B11450462CA845076D5A31455A7 /* Validation.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = Validation.swift; path = Source/Validation.swift; sourceTree = ""; }; + 394A07B9CD7A0E87C54639C7326B5B28 /* Infallible+Bind.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = "Infallible+Bind.swift"; path = "RxCocoa/Common/Infallible+Bind.swift"; sourceTree = ""; }; + 3956A13898BA7AE3AD6AED0406907F52 /* DispatchQueueConfiguration.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = DispatchQueueConfiguration.swift; path = RxSwift/Schedulers/Internal/DispatchQueueConfiguration.swift; sourceTree = ""; }; + 39D0F77A76D1B9C8043ACA2A518B4709 /* Pods-yinmeng-ios.modulemap */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.module; path = "Pods-yinmeng-ios.modulemap"; sourceTree = ""; }; + 3AF54C9D06FA26EEFB4A6D8DDB4C6C83 /* PrimitiveSequence+Concurrency.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = "PrimitiveSequence+Concurrency.swift"; path = "RxSwift/Traits/PrimitiveSequence/PrimitiveSequence+Concurrency.swift"; sourceTree = ""; }; + 3B45D252945E879A3B88C8989E5C2CC6 /* _RXKVOObserver.m */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.objc; name = _RXKVOObserver.m; path = RxCocoa/Runtime/_RXKVOObserver.m; sourceTree = ""; }; + 3B6E3E1498C003DB8CBD3643CD2AD2A6 /* HandyJSON-prefix.pch */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.h; path = "HandyJSON-prefix.pch"; sourceTree = ""; }; + 3C27EB2E04E045DFB79BE6AAA63A7EA2 /* ImageDownloader.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = ImageDownloader.swift; path = Sources/Networking/ImageDownloader.swift; sourceTree = ""; }; + 3DF97E8D675384337BA22ED93D008910 /* Kingfisher.modulemap */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.module; path = Kingfisher.modulemap; sourceTree = ""; }; + 3F5105C63B26C8CD36ECD3E4D25A4DFC /* RxSearchBarDelegateProxy.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = RxSearchBarDelegateProxy.swift; path = RxCocoa/iOS/Proxies/RxSearchBarDelegateProxy.swift; sourceTree = ""; }; + 3F6E79FDA2485804EB4B20DAEDA26366 /* DelaySubscription.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = DelaySubscription.swift; path = RxSwift/Observables/DelaySubscription.swift; sourceTree = ""; }; + 402F4EF7983996E485AA8AD6E305B46D /* Bag+Rx.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = "Bag+Rx.swift"; path = "RxSwift/Extensions/Bag+Rx.swift"; sourceTree = ""; }; + 4189EEA5194A0B67B0929125B7D8F3B9 /* MoyaProvider+Defaults.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = "MoyaProvider+Defaults.swift"; path = "Sources/Moya/MoyaProvider+Defaults.swift"; sourceTree = ""; }; + 418F325839254785FCE40E01EC615D42 /* Logger.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = Logger.swift; path = Source/Logger.swift; sourceTree = ""; }; + 41FE8293A6AF96E011A77F789193CD99 /* Reusable-Info.plist */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = text.plist.xml; path = "Reusable-Info.plist"; sourceTree = ""; }; + 420DDEA65A2C63C6CA966D994E696D54 /* AVAssetImageDataProvider.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = AVAssetImageDataProvider.swift; path = Sources/General/ImageSource/AVAssetImageDataProvider.swift; sourceTree = ""; }; + 42D446B359AD540FA2AEFD87D7ABE15C /* RxCollectionViewDataSourceProxy.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = RxCollectionViewDataSourceProxy.swift; path = RxCocoa/iOS/Proxies/RxCollectionViewDataSourceProxy.swift; sourceTree = ""; }; + 42F715AC86D9585FC5BB7F7C07DD7DAC /* ScheduledDisposable.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = ScheduledDisposable.swift; path = RxSwift/Disposables/ScheduledDisposable.swift; sourceTree = ""; }; + 43090D0C397209BB21ADF13605474623 /* Moya-Info.plist */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = text.plist.xml; path = "Moya-Info.plist"; sourceTree = ""; }; + 43A9212FF806B13E885C7019E059D160 /* Kingfisher.debug.xcconfig */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = text.xcconfig; path = Kingfisher.debug.xcconfig; sourceTree = ""; }; + 44142825DF6D5162BCAC2FEFBF148BED /* RequestTaskMap.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = RequestTaskMap.swift; path = Source/RequestTaskMap.swift; sourceTree = ""; }; + 443CA8C627022D8C1934F8F42533236E /* AFError.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = AFError.swift; path = Source/AFError.swift; sourceTree = ""; }; + 445854BBB677492BEB10430E549CF31D /* Delay.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = Delay.swift; path = RxSwift/Observables/Delay.swift; sourceTree = ""; }; + 4488B560629B5C88A5E9FF2ED9FCDFD5 /* RxWKNavigationDelegateProxy.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = RxWKNavigationDelegateProxy.swift; path = RxCocoa/iOS/Proxies/RxWKNavigationDelegateProxy.swift; sourceTree = ""; }; + 4529DBA9667227E1B099ADC681AB5850 /* Observable.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = Observable.swift; path = RxSwift/Observable.swift; sourceTree = ""; }; + 45E1E6ADB66DF96376E308D63F6B71D8 /* HandyJSON.debug.xcconfig */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = text.xcconfig; path = HandyJSON.debug.xcconfig; sourceTree = ""; }; + 45FEC9077C3B5C14B02AB4E46F22E157 /* ConstraintInsetTarget.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = ConstraintInsetTarget.swift; path = Sources/ConstraintInsetTarget.swift; sourceTree = ""; }; + 46CE5C282594AAB0BC74E3DE1A773F2B /* AsyncSubject.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = AsyncSubject.swift; path = RxSwift/Subjects/AsyncSubject.swift; sourceTree = ""; }; + 47110AC6AA4D44E8FCEB9552C18577A1 /* SnapKit-prefix.pch */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.h; path = "SnapKit-prefix.pch"; sourceTree = ""; }; + 477447EAA52D7E8C1E3C05F2DD47F9B1 /* PropertyInfo.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = PropertyInfo.swift; path = Source/PropertyInfo.swift; sourceTree = ""; }; + 48252905C19EDB8DCAE2BE4BE7B68A85 /* ImageCache.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = ImageCache.swift; path = Sources/Cache/ImageCache.swift; sourceTree = ""; }; + 48BEA0546BD26740F65A619717216925 /* BehaviorRelay+Driver.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = "BehaviorRelay+Driver.swift"; path = "RxCocoa/Traits/Driver/BehaviorRelay+Driver.swift"; sourceTree = ""; }; + 4917FB9D005872281B22F006F7001E9E /* NetworkReachabilityManager.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = NetworkReachabilityManager.swift; path = Source/NetworkReachabilityManager.swift; sourceTree = ""; }; + 495812E6EEB9BFC5FBAD933FB325C0BE /* SchedulerType+SharedSequence.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = "SchedulerType+SharedSequence.swift"; path = "RxCocoa/Traits/SharedSequence/SchedulerType+SharedSequence.swift"; sourceTree = ""; }; + 4A9962A1E3D931E363F3C4D48522361B /* Runtime.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = Runtime.swift; path = Sources/Utility/Runtime.swift; sourceTree = ""; }; + 4B2092F7A452FCAC892734476E6676E3 /* Concurrency.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = Concurrency.swift; path = Source/Concurrency.swift; sourceTree = ""; }; + 4B32547DF2C9A9E64087A593AC3EE911 /* SkipWhile.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = SkipWhile.swift; path = RxSwift/Observables/SkipWhile.swift; sourceTree = ""; }; + 4B40027C27CE4E459A38C1D87C106545 /* Catch.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = Catch.swift; path = RxSwift/Observables/Catch.swift; sourceTree = ""; }; + 4D43B9A8506661F18ED1E7EDF570932D /* SnapKit.modulemap */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.module; path = SnapKit.modulemap; sourceTree = ""; }; + 4DB0FE9FA272BBF1E359F79E2FE6B469 /* Image.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = Image.swift; path = Sources/Image/Image.swift; sourceTree = ""; }; + 4DB8E452090D235990597C3AB1BE8E11 /* Single.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = Single.swift; path = RxSwift/Traits/PrimitiveSequence/Single.swift; sourceTree = ""; }; + 4E71EDCC1B6F580E01E54903C36737EB /* SubscriptionDisposable.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = SubscriptionDisposable.swift; path = RxSwift/Disposables/SubscriptionDisposable.swift; sourceTree = ""; }; + 4ED914EA5EE1E5DAC87E75CFEEEBE002 /* UIControl+Rx.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = "UIControl+Rx.swift"; path = "RxCocoa/iOS/UIControl+Rx.swift"; sourceTree = ""; }; + 4F5800717EBB5879045C06670DA4C8AC /* Never.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = Never.swift; path = RxSwift/Observables/Never.swift; sourceTree = ""; }; + 4FE70A655C85EA7C91C24E5B3457D9B0 /* Kingfisher-umbrella.h */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.h; path = "Kingfisher-umbrella.h"; sourceTree = ""; }; + 501CF92DCF5E2F25FE033F445BAA7A3A /* ExtensionHelpers.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = ExtensionHelpers.swift; path = Sources/Utility/ExtensionHelpers.swift; sourceTree = ""; }; + 5096A43515DC7129C76B0F73FC4B6049 /* ExtendCustomModelType.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = ExtendCustomModelType.swift; path = Source/ExtendCustomModelType.swift; sourceTree = ""; }; + 516DBB0CADC2C6DBC5C12C20E9C7DFE4 /* RequestCompression.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = RequestCompression.swift; path = Source/RequestCompression.swift; sourceTree = ""; }; + 518597BD67B90E044EDCA15142FA2D54 /* Protected.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = Protected.swift; path = Source/Protected.swift; sourceTree = ""; }; + 5254AF871AE5D79369426F1E9DFD4BFB /* Session.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = Session.swift; path = Source/Session.swift; sourceTree = ""; }; + 5264BE1108D40329A508922AD0245365 /* HandyJSON.modulemap */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.module; path = HandyJSON.modulemap; sourceTree = ""; }; + 52F042037CA28D5A455E060DD097C638 /* PublishRelay.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = PublishRelay.swift; path = RxRelay/PublishRelay.swift; sourceTree = ""; }; + 5318EE8340C75CB1C311FB0C5C0035CE /* AsyncLock.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = AsyncLock.swift; path = RxSwift/Concurrency/AsyncLock.swift; sourceTree = ""; }; + 537B39F9D626350F9BD4A28C6DF455B6 /* RxSwift.debug.xcconfig */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = text.xcconfig; path = RxSwift.debug.xcconfig; sourceTree = ""; }; + 537DF163C75C79892595630BC3CBA09F /* SynchronizedDisposeType.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = SynchronizedDisposeType.swift; path = RxSwift/Concurrency/SynchronizedDisposeType.swift; sourceTree = ""; }; + 544D687E21BDD58B48D554A5709A7901 /* DelegateProxyType.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = DelegateProxyType.swift; path = RxCocoa/Common/DelegateProxyType.swift; sourceTree = ""; }; + 54C7D8C91C6BD127E758FD153F5CAE2A /* CachedResponseHandler.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = CachedResponseHandler.swift; path = Source/CachedResponseHandler.swift; sourceTree = ""; }; + 553E529F93F751DF0489E958694F11D8 /* RetryStrategy.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = RetryStrategy.swift; path = Sources/Networking/RetryStrategy.swift; sourceTree = ""; }; + 55D10B797A89889598E86DF39D020451 /* UIActivityIndicatorView+Rx.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = "UIActivityIndicatorView+Rx.swift"; path = "RxCocoa/iOS/UIActivityIndicatorView+Rx.swift"; sourceTree = ""; }; + 56969AC68B2EED540B9FBF1E0D237B8D /* MBProgressHUD.m */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.objc; path = MBProgressHUD.m; sourceTree = ""; }; + 56D520627040A3B6D58DF009393C985E /* Disposables.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = Disposables.swift; path = RxSwift/Disposables/Disposables.swift; sourceTree = ""; }; + 57BE0C87BBB0A537606F16CD108FAECF /* Cancellable.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = Cancellable.swift; path = Sources/Moya/Cancellable.swift; sourceTree = ""; }; + 57C844D869CA97E3BCD995BAE39B0811 /* Moya.modulemap */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.module; path = Moya.modulemap; sourceTree = ""; }; + 5859599DB876A373ACA4D7088EA30151 /* URLRequest+Encoding.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = "URLRequest+Encoding.swift"; path = "Sources/Moya/URLRequest+Encoding.swift"; sourceTree = ""; }; + 588185259F665B2270B61BC5EEEDB105 /* ControlProperty.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = ControlProperty.swift; path = RxCocoa/Traits/ControlProperty.swift; sourceTree = ""; }; + 590615ED68A80BD1EF1DBF8F477F1B12 /* Filter.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = Filter.swift; path = Sources/Image/Filter.swift; sourceTree = ""; }; + 591861115B56C34EE893545E4F44ECE0 /* Generate.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = Generate.swift; path = RxSwift/Observables/Generate.swift; sourceTree = ""; }; + 594A5F9AE55C8EAD11AFE74EE0DAC3C7 /* ConstraintLayoutGuide.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = ConstraintLayoutGuide.swift; path = Sources/ConstraintLayoutGuide.swift; sourceTree = ""; }; + 5A549727CCD5C1657E53A8BAE5E58145 /* SessionDelegate.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = SessionDelegate.swift; path = Sources/Networking/SessionDelegate.swift; sourceTree = ""; }; + 5BBD217833E818303FFD2DD7E1DD6817 /* NopDisposable.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = NopDisposable.swift; path = RxSwift/Disposables/NopDisposable.swift; sourceTree = ""; }; + 5C17122D9169B76E0AB08E43B215523C /* Filter.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = Filter.swift; path = RxSwift/Observables/Filter.swift; sourceTree = ""; }; + 5D797E9A5C5782CE845840781FA1CC81 /* Alamofire */ = {isa = PBXFileReference; explicitFileType = wrapper.framework; includeInIndex = 0; name = Alamofire; path = Alamofire.framework; sourceTree = BUILT_PRODUCTS_DIR; }; + 5DC90B70DB4293C27D4B5733F05EC3CC /* InvocableScheduledItem.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = InvocableScheduledItem.swift; path = RxSwift/Schedulers/Internal/InvocableScheduledItem.swift; sourceTree = ""; }; + 5DE5F4C9535F3ECFDE536AF77F583A78 /* MemoryStorage.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = MemoryStorage.swift; path = Sources/Cache/MemoryStorage.swift; sourceTree = ""; }; + 5EC0523BF8CA0D3FF2934609B979DBED /* Date+Dispatch.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = "Date+Dispatch.swift"; path = "RxSwift/Date+Dispatch.swift"; sourceTree = ""; }; + 6009157C9973464C53AFA7E068E984F7 /* Export.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = Export.swift; path = Source/Export.swift; sourceTree = ""; }; + 60A3141E90976A3DD62256D0A73B9572 /* EnumType.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = EnumType.swift; path = Source/EnumType.swift; sourceTree = ""; }; + 615C9F76DEEA89A8A3638328942C191B /* NetworkActivityPlugin.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = NetworkActivityPlugin.swift; path = Sources/Moya/Plugins/NetworkActivityPlugin.swift; sourceTree = ""; }; + 61ADA54F40A6900545707A222D69889B /* ShareReplayScope.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = ShareReplayScope.swift; path = RxSwift/Observables/ShareReplayScope.swift; sourceTree = ""; }; + 628E93CA5921A8FC116E3929C680A27B /* RxRelay-Info.plist */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = text.plist.xml; path = "RxRelay-Info.plist"; sourceTree = ""; }; + 634E359FC76F57C6E032A112422B8130 /* VirtualTimeConverterType.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = VirtualTimeConverterType.swift; path = RxSwift/Schedulers/VirtualTimeConverterType.swift; sourceTree = ""; }; + 63CF3F8FFB207D7C17E8DB9CB93EDA1E /* RxCocoa.release.xcconfig */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = text.xcconfig; path = RxCocoa.release.xcconfig; sourceTree = ""; }; + 6438C8BA15E4054D7ACA1E3DFF2066DB /* FieldDescriptor.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = FieldDescriptor.swift; path = Source/FieldDescriptor.swift; sourceTree = ""; }; + 64576C6FC886A417A4683A9816DA5D4F /* TailRecursiveSink.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = TailRecursiveSink.swift; path = RxSwift/Observers/TailRecursiveSink.swift; sourceTree = ""; }; + 645BF6563AFCDBF6A94CF2E1A387FA8C /* Observable+Bind.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = "Observable+Bind.swift"; path = "RxCocoa/Common/Observable+Bind.swift"; sourceTree = ""; }; + 64854FC0AC6AFE7ACB68D2C7BEAAE398 /* DateTransform.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = DateTransform.swift; path = Source/DateTransform.swift; sourceTree = ""; }; + 649D2F79A4B50006D2A9D93E21022944 /* Moya.release.xcconfig */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = text.xcconfig; path = Moya.release.xcconfig; sourceTree = ""; }; + 64F516F56589A2470DFA0E30E85DBB80 /* ConstraintDescription.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = ConstraintDescription.swift; path = Sources/ConstraintDescription.swift; sourceTree = ""; }; + 64FA3F6B350E532395A97AB96530BE97 /* NSObject+Rx.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = "NSObject+Rx.swift"; path = "RxCocoa/Foundation/NSObject+Rx.swift"; sourceTree = ""; }; + 654DEBE109ACCEE862E7F084EE7ED13C /* Timeout.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = Timeout.swift; path = RxSwift/Observables/Timeout.swift; sourceTree = ""; }; + 65C3DEA44C88982D1639BC1D3AE788E5 /* RxCocoa.modulemap */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.module; path = RxCocoa.modulemap; sourceTree = ""; }; + 6673F5D40ED1C9BF12C1C9864D29C16B /* Maybe.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = Maybe.swift; path = RxSwift/Traits/PrimitiveSequence/Maybe.swift; sourceTree = ""; }; + 66BCA8A6AE43B359068161172075AD29 /* MainScheduler.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = MainScheduler.swift; path = RxSwift/Schedulers/MainScheduler.swift; sourceTree = ""; }; + 66EAB16FAAFDFDFF614A83B83544F60A /* RxCocoa-umbrella.h */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.h; path = "RxCocoa-umbrella.h"; sourceTree = ""; }; + 67C143D7E7508931CFD2E2398C7BA9F0 /* RxTableViewDataSourceProxy.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = RxTableViewDataSourceProxy.swift; path = RxCocoa/iOS/Proxies/RxTableViewDataSourceProxy.swift; sourceTree = ""; }; + 692E3C85CC1223B95D6A9605B661FA68 /* AnyObserver.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = AnyObserver.swift; path = RxSwift/AnyObserver.swift; sourceTree = ""; }; + 69B3A5BB96CFA43786C0ACFCF6162F46 /* URLSession+Rx.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = "URLSession+Rx.swift"; path = "RxCocoa/Foundation/URLSession+Rx.swift"; sourceTree = ""; }; + 69C17E66AE494BF8C88740E1EDB36891 /* RefCountDisposable.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = RefCountDisposable.swift; path = RxSwift/Disposables/RefCountDisposable.swift; sourceTree = ""; }; + 69D940AC28230A45C640E32E10438178 /* SchedulerType.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = SchedulerType.swift; path = RxSwift/SchedulerType.swift; sourceTree = ""; }; + 6A1970A14C2672638850C555C17ADE89 /* Foundation.framework */ = {isa = PBXFileReference; lastKnownFileType = wrapper.framework; name = Foundation.framework; path = Platforms/iPhoneOS.platform/Developer/SDKs/iPhoneOS14.0.sdk/System/Library/Frameworks/Foundation.framework; sourceTree = DEVELOPER_DIR; }; + 6AB41D31B155EAB764A9C053A0DE59CD /* PointerType.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = PointerType.swift; path = Source/PointerType.swift; sourceTree = ""; }; + 6BC184BD2886B5395146315871D4F629 /* Sample.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = Sample.swift; path = RxSwift/Observables/Sample.swift; sourceTree = ""; }; + 6C198ADB3A802CC083707D46D42F735C /* Endpoint.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = Endpoint.swift; path = Sources/Moya/Endpoint.swift; sourceTree = ""; }; + 6C4649E78A32C230E03D17B80A888076 /* Alamofire-prefix.pch */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.h; path = "Alamofire-prefix.pch"; sourceTree = ""; }; + 6C4BAD710FAA4AE5F73353998A04A650 /* Pods-yinmeng-ios.release.xcconfig */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = text.xcconfig; path = "Pods-yinmeng-ios.release.xcconfig"; sourceTree = ""; }; + 6D060D2BB92C878FBC76760B8F99D911 /* RxSwift-prefix.pch */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.h; path = "RxSwift-prefix.pch"; sourceTree = ""; }; + 6D74FF06CA5AE8F2F5D48301BE439D32 /* CFNetwork.framework */ = {isa = PBXFileReference; lastKnownFileType = wrapper.framework; name = CFNetwork.framework; path = Platforms/iPhoneOS.platform/Developer/SDKs/iPhoneOS14.0.sdk/System/Library/Frameworks/CFNetwork.framework; sourceTree = DEVELOPER_DIR; }; + 6DEEF0A78457ED9D46DBF84E913E83F6 /* RxRelay-umbrella.h */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.h; path = "RxRelay-umbrella.h"; sourceTree = ""; }; + 6E0F4988883481C19FAFF403697872DD /* Kingfisher.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = Kingfisher.swift; path = Sources/General/Kingfisher.swift; sourceTree = ""; }; + 6E269149DE9BA1B81C3504720A668420 /* HTTPMethod.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = HTTPMethod.swift; path = Source/HTTPMethod.swift; sourceTree = ""; }; + 6EA8E69F4FC1AD4BC47B9FAA09D391D1 /* MoyaProvider.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = MoyaProvider.swift; path = Sources/Moya/MoyaProvider.swift; sourceTree = ""; }; + 6EBE2A5988B01C477AFF1CE3128EE8AF /* ConstraintLayoutGuideDSL.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = ConstraintLayoutGuideDSL.swift; path = Sources/ConstraintLayoutGuideDSL.swift; sourceTree = ""; }; + 6F85D9716CFD2A169AB2FC3954F8916B /* Create.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = Create.swift; path = RxSwift/Observables/Create.swift; sourceTree = ""; }; + 6FE1258734CD0D5DE5C0C1545F096DAF /* StringEncoding+Alamofire.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = "StringEncoding+Alamofire.swift"; path = "Source/StringEncoding+Alamofire.swift"; sourceTree = ""; }; + 70933FA1D55CE70EA5A4110C98DEC09D /* PublishSubject.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = PublishSubject.swift; path = RxSwift/Subjects/PublishSubject.swift; sourceTree = ""; }; + 70B306F880D3FA0554EF152D25916163 /* GraphicsContext.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = GraphicsContext.swift; path = Sources/Image/GraphicsContext.swift; sourceTree = ""; }; + 7160612C75B8C873D77B5AEDED76632B /* CoreGraphics.framework */ = {isa = PBXFileReference; lastKnownFileType = wrapper.framework; name = CoreGraphics.framework; path = Platforms/iPhoneOS.platform/Developer/SDKs/iPhoneOS14.0.sdk/System/Library/Frameworks/CoreGraphics.framework; sourceTree = DEVELOPER_DIR; }; + 71A22E298D1E26A25192B7D79CB9C7BE /* _RX.h */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.h; name = _RX.h; path = RxCocoa/Runtime/include/_RX.h; sourceTree = ""; }; + 720BE3DE6F24DCF57D71D73928C99C2B /* _RXKVOObserver.h */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.h; name = _RXKVOObserver.h; path = RxCocoa/Runtime/include/_RXKVOObserver.h; sourceTree = ""; }; + 728E3C167CE3ED7F8123F48D5A84771E /* ConcurrentMainScheduler.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = ConcurrentMainScheduler.swift; path = RxSwift/Schedulers/ConcurrentMainScheduler.swift; sourceTree = ""; }; + 739CDDE742C44BA839AD3DA536BDD57F /* RedirectHandler.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = RedirectHandler.swift; path = Sources/Networking/RedirectHandler.swift; sourceTree = ""; }; + 7430E48DEB35987DD064EE0D7363953F /* Configuration.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = Configuration.swift; path = Source/Configuration.swift; sourceTree = ""; }; + 74A65654283AE2CF4A3DFA265199F1C5 /* SnapKit.release.xcconfig */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = text.xcconfig; path = SnapKit.release.xcconfig; sourceTree = ""; }; + 74E7B0CB0BD4C32719550BAEE7471ABC /* UITabBar+Rx.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = "UITabBar+Rx.swift"; path = "RxCocoa/iOS/UITabBar+Rx.swift"; sourceTree = ""; }; + 74F603E9DCC9F74E70AC2EEF9A832481 /* RxTabBarDelegateProxy.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = RxTabBarDelegateProxy.swift; path = RxCocoa/iOS/Proxies/RxTabBarDelegateProxy.swift; sourceTree = ""; }; + 7572072A13A12227DE23BD58E99E7B41 /* AuthenticationChallengeResponsable.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = AuthenticationChallengeResponsable.swift; path = Sources/Networking/AuthenticationChallengeResponsable.swift; sourceTree = ""; }; + 75C831D0F3B6ECF5593AC202900F9B4F /* CallbackQueue.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = CallbackQueue.swift; path = Sources/Utility/CallbackQueue.swift; sourceTree = ""; }; + 75FFF56047C4C60A6E7F1E572172AC93 /* Materialize.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = Materialize.swift; path = RxSwift/Observables/Materialize.swift; sourceTree = ""; }; + 763C57CB99AAF692D5804D56D94FE7EA /* ConstraintMakerRelatable+Extensions.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = "ConstraintMakerRelatable+Extensions.swift"; path = "Sources/ConstraintMakerRelatable+Extensions.swift"; sourceTree = ""; }; + 765D531DF5050A417659B07DDB7A51B1 /* BinaryDisposable.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = BinaryDisposable.swift; path = RxSwift/Disposables/BinaryDisposable.swift; sourceTree = ""; }; + 7867FF4FE4FF1D6345613A45E339635D /* CompositeDisposable.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = CompositeDisposable.swift; path = RxSwift/Disposables/CompositeDisposable.swift; sourceTree = ""; }; + 78F5BA1E49C1B6FE56A4B5323CD9AFF8 /* Alamofire-dummy.m */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.objc; path = "Alamofire-dummy.m"; sourceTree = ""; }; + 7965E10A5058A7FDC743C628B6A209E4 /* ImageFormat.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = ImageFormat.swift; path = Sources/Image/ImageFormat.swift; sourceTree = ""; }; + 79A0A26C9F36ABCC4EB50D474EC8DA4D /* SubscribeOn.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = SubscribeOn.swift; path = RxSwift/Observables/SubscribeOn.swift; sourceTree = ""; }; + 79AB56ECFE81336CFFB52ADF927D8A7C /* ImageBinder.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = ImageBinder.swift; path = Sources/SwiftUI/ImageBinder.swift; sourceTree = ""; }; + 7A6CCF2E51B64ED58E9F5F6BC18C4500 /* UISearchController+Rx.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = "UISearchController+Rx.swift"; path = "RxCocoa/iOS/UISearchController+Rx.swift"; sourceTree = ""; }; + 7AD5F75086AF715FAD56BDDA5876EA2B /* Disposable.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = Disposable.swift; path = RxSwift/Disposable.swift; sourceTree = ""; }; + 7B6C73A34CCB4FCB54A17345BD0051FC /* NSSlider+Rx.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = "NSSlider+Rx.swift"; path = "RxCocoa/macOS/NSSlider+Rx.swift"; sourceTree = ""; }; + 7B953B1CDFABA00A04E6AC9124999CF9 /* KVORepresentable+Swift.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = "KVORepresentable+Swift.swift"; path = "RxCocoa/Foundation/KVORepresentable+Swift.swift"; sourceTree = ""; }; + 7C161168F47BE22BA1D8157F0A37F4C2 /* Timer.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = Timer.swift; path = RxSwift/Observables/Timer.swift; sourceTree = ""; }; + 7CDE2F9CE2B04EA6687EE664E9B1F447 /* ConstraintMakerExtendable.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = ConstraintMakerExtendable.swift; path = Sources/ConstraintMakerExtendable.swift; sourceTree = ""; }; + 7CFEE4BC9AEF52579A20AF4717B3205C /* MultipartUpload.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = MultipartUpload.swift; path = Source/MultipartUpload.swift; sourceTree = ""; }; + 7D131FE518C0CECBEA619AA8A5490197 /* Infallible+CombineLatest+arity.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = "Infallible+CombineLatest+arity.swift"; path = "RxSwift/Traits/Infallible/Infallible+CombineLatest+arity.swift"; sourceTree = ""; }; + 7E97E1D4DF8BFA3FE2C603D6B934D9D2 /* DispatchQueue+Alamofire.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = "DispatchQueue+Alamofire.swift"; path = "Source/DispatchQueue+Alamofire.swift"; sourceTree = ""; }; + 7FA5EF7CC85AF8D7A9C4307E6247274B /* Using.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = Using.swift; path = RxSwift/Observables/Using.swift; sourceTree = ""; }; + 8051259FDEC630E944D8CD2114B0226B /* WKWebView+Rx.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = "WKWebView+Rx.swift"; path = "RxCocoa/iOS/WKWebView+Rx.swift"; sourceTree = ""; }; + 809C5FAB588354C9BA37DC3EAB8CB45C /* RxSwift */ = {isa = PBXFileReference; explicitFileType = wrapper.framework; includeInIndex = 0; name = RxSwift; path = RxSwift.framework; sourceTree = BUILT_PRODUCTS_DIR; }; + 80E741ED9F7CB291A4CA8068F3FE04F2 /* MBProgressHUD.debug.xcconfig */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = text.xcconfig; path = MBProgressHUD.debug.xcconfig; sourceTree = ""; }; + 81B176F830BCA2FC63200329DE776384 /* CompactMap.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = CompactMap.swift; path = RxSwift/Observables/CompactMap.swift; sourceTree = ""; }; + 82EEBDF2AE2F00B7933D6A5DF8FDF0AD /* ObservableType.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = ObservableType.swift; path = RxSwift/ObservableType.swift; sourceTree = ""; }; + 834ED77A734859A8A9236980263E4AF4 /* ConstraintPriority.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = ConstraintPriority.swift; path = Sources/ConstraintPriority.swift; sourceTree = ""; }; + 840E59B83C8C092BD38138A7D44A473E /* SizeExtensions.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = SizeExtensions.swift; path = Sources/Utility/SizeExtensions.swift; sourceTree = ""; }; + 8472FB3724242C375626B5D19B004A36 /* Placeholder.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = Placeholder.swift; path = Sources/Image/Placeholder.swift; sourceTree = ""; }; + 84E7CDD4F491C19202D78BD1D18EA01E /* Measuable.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = Measuable.swift; path = Source/Measuable.swift; sourceTree = ""; }; + 8770E250C6062015540FA168FD612B2B /* GroupedObservable.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = GroupedObservable.swift; path = RxSwift/GroupedObservable.swift; sourceTree = ""; }; + 87AAF208F89B5776787B00ED7C4139D0 /* RequestInterceptor.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = RequestInterceptor.swift; path = Source/RequestInterceptor.swift; sourceTree = ""; }; + 87AD720C8F2A51587F1C491E884DB664 /* URL+Moya.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = "URL+Moya.swift"; path = "Sources/Moya/URL+Moya.swift"; sourceTree = ""; }; + 8807FF18BB93251158B72386A622E490 /* RxTableViewDelegateProxy.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = RxTableViewDelegateProxy.swift; path = RxCocoa/iOS/Proxies/RxTableViewDelegateProxy.swift; sourceTree = ""; }; + 88195126F4E96A3774802B0BA8877C77 /* Combine.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = Combine.swift; path = Source/Combine.swift; sourceTree = ""; }; + 881FD56231A6918A0EAD0806FB1D9A18 /* RxTabBarControllerDelegateProxy.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = RxTabBarControllerDelegateProxy.swift; path = RxCocoa/iOS/Proxies/RxTabBarControllerDelegateProxy.swift; sourceTree = ""; }; + 8898277C74B39B8C2709D3BDFF6C793E /* RxCollectionViewDataSourceType.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = RxCollectionViewDataSourceType.swift; path = RxCocoa/iOS/Protocols/RxCollectionViewDataSourceType.swift; sourceTree = ""; }; + 8A18BCB5C7FD8D506C4D66B8A1BE5B63 /* ConstraintDirectionalInsets.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = ConstraintDirectionalInsets.swift; path = Sources/ConstraintDirectionalInsets.swift; sourceTree = ""; }; + 8A3398D47F647EC9C9854F30FAA9A225 /* RxCocoa-dummy.m */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.objc; path = "RxCocoa-dummy.m"; sourceTree = ""; }; + 8A9425DD88305B16CADE1573B70E7D7C /* UIDatePicker+Rx.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = "UIDatePicker+Rx.swift"; path = "RxCocoa/iOS/UIDatePicker+Rx.swift"; sourceTree = ""; }; + 8AD039748141FD7199964AF985765430 /* MultipartFormData.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = MultipartFormData.swift; path = Sources/Moya/MultipartFormData.swift; sourceTree = ""; }; + 8B3F60740202D2919EAB02088A75C6DE /* ConstraintAttributes.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = ConstraintAttributes.swift; path = Sources/ConstraintAttributes.swift; sourceTree = ""; }; + 8B776E2E2FACA7C1A7173E403F37910F /* PrivacyInfo.xcprivacy */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = text.xml; name = PrivacyInfo.xcprivacy; path = Sources/PrivacyInfo.xcprivacy; sourceTree = ""; }; + 8B8FAB0D627B17EDE1366984278705D9 /* MBProgressHUD.framework */ = {isa = PBXFileReference; explicitFileType = wrapper.framework; includeInIndex = 0; path = MBProgressHUD.framework; sourceTree = BUILT_PRODUCTS_DIR; }; + 8C1E768C4764D3F7B03199D967453517 /* Rx.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = Rx.swift; path = RxSwift/Rx.swift; sourceTree = ""; }; + 8CDAEEA9FC477033FF5344F6CBE85CB2 /* DiskStorage.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = DiskStorage.swift; path = Sources/Cache/DiskStorage.swift; sourceTree = ""; }; + 8CDDAB158F06801DD368BFA93A07800C /* Debugging.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = Debugging.swift; path = Sources/Debugging.swift; sourceTree = ""; }; + 8D02F219043B80DB62FA686E85C09B35 /* RxCollectionViewDataSourcePrefetchingProxy.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = RxCollectionViewDataSourcePrefetchingProxy.swift; path = RxCocoa/iOS/Proxies/RxCollectionViewDataSourcePrefetchingProxy.swift; sourceTree = ""; }; + 8D0507B1E2AB4B8A447354D000FEF414 /* KVORepresentable+CoreGraphics.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = "KVORepresentable+CoreGraphics.swift"; path = "RxCocoa/Foundation/KVORepresentable+CoreGraphics.swift"; sourceTree = ""; }; + 8DA1B7070D9B7E6489E50762BA7CC29B /* TransformOf.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = TransformOf.swift; path = Source/TransformOf.swift; sourceTree = ""; }; + 8DCA321A43CEC56664AD41086F8B7141 /* UISwitch+Rx.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = "UISwitch+Rx.swift"; path = "RxCocoa/iOS/UISwitch+Rx.swift"; sourceTree = ""; }; + 8DD8CAC74ECCE5DF13BE36C29354F6B3 /* PriorityQueue.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = PriorityQueue.swift; path = Platform/DataStructures/PriorityQueue.swift; sourceTree = ""; }; + 8FC8131B3030B737FB4BE9DBCBAB4C9E /* Infallible+Operators.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = "Infallible+Operators.swift"; path = "RxSwift/Traits/Infallible/Infallible+Operators.swift"; sourceTree = ""; }; + 8FF51600836B6E9C1393D1B32AE0409F /* Constraint.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = Constraint.swift; path = Sources/Constraint.swift; sourceTree = ""; }; + 90028E4B472E1FCD0B7A391D37BC0C80 /* RxCollectionViewDelegateProxy.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = RxCollectionViewDelegateProxy.swift; path = RxCocoa/iOS/Proxies/RxCollectionViewDelegateProxy.swift; sourceTree = ""; }; + 913295D3902A731E0FEF7891F2DFFD66 /* HistoricalSchedulerTimeConverter.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = HistoricalSchedulerTimeConverter.swift; path = RxSwift/Schedulers/HistoricalSchedulerTimeConverter.swift; sourceTree = ""; }; + 917C955DCF6B29BABB9B623BE0758691 /* CombineLatest+Collection.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = "CombineLatest+Collection.swift"; path = "RxSwift/Observables/CombineLatest+Collection.swift"; sourceTree = ""; }; + 91834F0831C28901ECD936CE6E242605 /* TargetType.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = TargetType.swift; path = Sources/Moya/TargetType.swift; sourceTree = ""; }; + 91B4895A5E4828D58DFE315830059A72 /* ImageDrawing.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = ImageDrawing.swift; path = Sources/Image/ImageDrawing.swift; sourceTree = ""; }; + 92037C313E25E9C5B1ECD6B53CF18C6C /* ScheduledItemType.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = ScheduledItemType.swift; path = RxSwift/Schedulers/Internal/ScheduledItemType.swift; sourceTree = ""; }; + 924E596CD9FDC9E228B02FD51DF48901 /* ResourceBundle-Kingfisher-Kingfisher-Info.plist */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = text.plist.xml; path = "ResourceBundle-Kingfisher-Kingfisher-Info.plist"; sourceTree = ""; }; + 932FF7024616D8D82633AB22546C7DC0 /* NSTextStorage+Rx.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = "NSTextStorage+Rx.swift"; path = "RxCocoa/iOS/NSTextStorage+Rx.swift"; sourceTree = ""; }; + 9382A27EEA32D49627659BC72C56FCBF /* BehaviorRelay.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = BehaviorRelay.swift; path = RxRelay/BehaviorRelay.swift; sourceTree = ""; }; + 93BD071E578B69235CCADBFBE9FBAA1B /* Kingfisher.release.xcconfig */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = text.xcconfig; path = Kingfisher.release.xcconfig; sourceTree = ""; }; + 947FCB4637962EF20818268291E26E85 /* Zip.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = Zip.swift; path = RxSwift/Observables/Zip.swift; sourceTree = ""; }; + 94B8075CA095FDBA9AE87F86A21B0C30 /* Resource.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = Resource.swift; path = Sources/General/ImageSource/Resource.swift; sourceTree = ""; }; + 94C392D9062D4196B340E6F77067B6F2 /* Queue.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = Queue.swift; path = Platform/DataStructures/Queue.swift; sourceTree = ""; }; + 94CA369E5A9E7E47E7DBCAAD6F63D296 /* Infallible+Create.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = "Infallible+Create.swift"; path = "RxSwift/Traits/Infallible/Infallible+Create.swift"; sourceTree = ""; }; + 9541ABA1A2C54DE7EED55370247C46AA /* ControlEvent.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = ControlEvent.swift; path = RxCocoa/Traits/ControlEvent.swift; sourceTree = ""; }; + 95509362358E1B4F96EED27DC01B1C24 /* WithUnretained.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = WithUnretained.swift; path = RxSwift/Observables/WithUnretained.swift; sourceTree = ""; }; + 95AF3FFD5DA43879FFD1FEF529C36275 /* Result.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = Result.swift; path = Sources/Utility/Result.swift; sourceTree = ""; }; + 95D551A418E6BD3AAE54051EE0A0129C /* Signal+Subscription.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = "Signal+Subscription.swift"; path = "RxCocoa/Traits/Signal/Signal+Subscription.swift"; sourceTree = ""; }; + 95F799040C1A70E136CAE7A41476545C /* UITableView+Reusable.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = "UITableView+Reusable.swift"; path = "Sources/View/UITableView+Reusable.swift"; sourceTree = ""; }; + 960152331447046185D9888B4AED166C /* Infallible+Zip+arity.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = "Infallible+Zip+arity.swift"; path = "RxSwift/Traits/Infallible/Infallible+Zip+arity.swift"; sourceTree = ""; }; + 96DB504A50F1E4FBCD16D5BC49EFCF0C /* UIPickerView+Rx.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = "UIPickerView+Rx.swift"; path = "RxCocoa/iOS/UIPickerView+Rx.swift"; sourceTree = ""; }; + 96EB1FBABEA3906F0EF58EE47E45A83B /* ConstraintLayoutGuide+Extensions.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = "ConstraintLayoutGuide+Extensions.swift"; path = "Sources/ConstraintLayoutGuide+Extensions.swift"; sourceTree = ""; }; + 972FCFDB49C8D15767A6488B65F2999B /* Deserializer.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = Deserializer.swift; path = Source/Deserializer.swift; sourceTree = ""; }; + 97360AE19AF07AC87B391E1E0C708F18 /* LayoutConstraintItem.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = LayoutConstraintItem.swift; path = Sources/LayoutConstraintItem.swift; sourceTree = ""; }; + 979486118B3E90C08386079D57962701 /* SnapKit */ = {isa = PBXFileReference; explicitFileType = wrapper.framework; includeInIndex = 0; name = SnapKit; path = SnapKit.framework; sourceTree = BUILT_PRODUCTS_DIR; }; + 97E745BB2E59AE041727B826B1E61BBB /* ControlEvent+Driver.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = "ControlEvent+Driver.swift"; path = "RxCocoa/Traits/Driver/ControlEvent+Driver.swift"; sourceTree = ""; }; + 98358BCC95E6655702825CEE45C0C8FA /* Reactive.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = Reactive.swift; path = RxSwift/Reactive.swift; sourceTree = ""; }; + 983A6B351A04E8A201ECBA3C765A4B43 /* MBProgressHUD-Info.plist */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = text.plist.xml; path = "MBProgressHUD-Info.plist"; sourceTree = ""; }; + 9895F4D070396F9D33D6C602E53C0D77 /* ReplaySubject.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = ReplaySubject.swift; path = RxSwift/Subjects/ReplaySubject.swift; sourceTree = ""; }; + 98AC09B0DB090CDE2D7CC82E1811FA69 /* RxRelay.release.xcconfig */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = text.xcconfig; path = RxRelay.release.xcconfig; sourceTree = ""; }; + 99155CE8434026F99E70418FAEF41EEA /* Debug.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = Debug.swift; path = RxSwift/Observables/Debug.swift; sourceTree = ""; }; + 9A2C43D00EDD3B8E5B6D1AC17B1E48E1 /* ControlEvent+Signal.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = "ControlEvent+Signal.swift"; path = "RxCocoa/Traits/Signal/ControlEvent+Signal.swift"; sourceTree = ""; }; + 9B09861BBDC46C3D1F767E4F57F0FCD6 /* RequestTypeWrapper.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = RequestTypeWrapper.swift; path = Sources/Moya/RequestTypeWrapper.swift; sourceTree = ""; }; + 9B3AF9BB0F7EB5558031DD21AD2F86CC /* Pods-yinmeng-ios-umbrella.h */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.h; path = "Pods-yinmeng-ios-umbrella.h"; sourceTree = ""; }; + 9BAC09FA3F4AA34E2FD9045902942CE8 /* KFImage.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = KFImage.swift; path = Sources/SwiftUI/KFImage.swift; sourceTree = ""; }; + 9BC03DDC341E7F14C1F96A0C0F826FD3 /* Pods-yinmeng-ios */ = {isa = PBXFileReference; explicitFileType = wrapper.framework; includeInIndex = 0; name = "Pods-yinmeng-ios"; path = Pods_yinmeng_ios.framework; sourceTree = BUILT_PRODUCTS_DIR; }; + 9BF394511EEFCC9854970C278A4EEFAB /* TakeWithPredicate.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = TakeWithPredicate.swift; path = RxSwift/Observables/TakeWithPredicate.swift; sourceTree = ""; }; + 9BFCC48A5DBF6A66F64E5ACE27854985 /* ResponseSerialization.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = ResponseSerialization.swift; path = Source/ResponseSerialization.swift; sourceTree = ""; }; + 9C6E055D8D9B83521DB2D0B74D91A032 /* UITableView+Rx.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = "UITableView+Rx.swift"; path = "RxCocoa/iOS/UITableView+Rx.swift"; sourceTree = ""; }; + 9D3BCD1EA3553D12354FD5FA1FAE15CC /* EnumTransform.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = EnumTransform.swift; path = Source/EnumTransform.swift; sourceTree = ""; }; + 9D4D5FD14129673A9CDB7002DBABE33E /* Skip.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = Skip.swift; path = RxSwift/Observables/Skip.swift; sourceTree = ""; }; + 9D5553E70A731CAE3CC0589428DF9FFA /* Error.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = Error.swift; path = RxSwift/Observables/Error.swift; sourceTree = ""; }; + 9D5A16599059CA238869B241131BA02D /* AccessTokenPlugin.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = AccessTokenPlugin.swift; path = Sources/Moya/Plugins/AccessTokenPlugin.swift; sourceTree = ""; }; + 9D73294AC7AF8EC9156DBA588DC9CE3D /* GIFAnimatedImage.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = GIFAnimatedImage.swift; path = Sources/Image/GIFAnimatedImage.swift; sourceTree = ""; }; + 9D940727FF8FB9C785EB98E56350EF41 /* Podfile */ = {isa = PBXFileReference; explicitFileType = text.script.ruby; includeInIndex = 1; indentWidth = 2; name = Podfile; path = ../Podfile; sourceTree = SOURCE_ROOT; tabWidth = 2; xcLanguageSpecificationIdentifier = xcode.lang.ruby; }; + 9DBF24BFBDEDD9C43BB60E43954D93C9 /* KFImageProtocol.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = KFImageProtocol.swift; path = Sources/SwiftUI/KFImageProtocol.swift; sourceTree = ""; }; + 9FC9415FA1C1593D995CF4413F86119E /* UIRefreshControl+Rx.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = "UIRefreshControl+Rx.swift"; path = "RxCocoa/iOS/UIRefreshControl+Rx.swift"; sourceTree = ""; }; + 9FE80A6E04D0DEC038F7B01D95633AE8 /* Atomic.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = Atomic.swift; path = Sources/Moya/Atomic.swift; sourceTree = ""; }; + 9FE96E6FECBEF720CD9DD849F12E6D61 /* ToArray.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = ToArray.swift; path = RxSwift/Observables/ToArray.swift; sourceTree = ""; }; + A0989B49F85763612695C610DDE3995F /* Serializer.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = Serializer.swift; path = Source/Serializer.swift; sourceTree = ""; }; + A0ABA07B4D48354ED3F51C2D6AF5426B /* Reusable */ = {isa = PBXFileReference; explicitFileType = wrapper.framework; includeInIndex = 0; name = Reusable; path = Reusable.framework; sourceTree = BUILT_PRODUCTS_DIR; }; + A0CB4A2B49E071E7012FEE7D28B8B467 /* Result+Alamofire.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = "Result+Alamofire.swift"; path = "Source/Result+Alamofire.swift"; sourceTree = ""; }; + A124A76CB3B2F5D7198358B2E123B564 /* PublishRelay+Signal.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = "PublishRelay+Signal.swift"; path = "RxCocoa/Traits/Signal/PublishRelay+Signal.swift"; sourceTree = ""; }; + A208FBE87421B2ABC0142F6A07D0B553 /* _RXObjCRuntime.m */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.objc; name = _RXObjCRuntime.m; path = RxCocoa/Runtime/_RXObjCRuntime.m; sourceTree = ""; }; + A296A412119288A86A5336E1C181E566 /* ImageDownloaderDelegate.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = ImageDownloaderDelegate.swift; path = Sources/Networking/ImageDownloaderDelegate.swift; sourceTree = ""; }; + A2D58F2F6C7CC4D368CE0D57F40CD27B /* Completable+AndThen.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = "Completable+AndThen.swift"; path = "RxSwift/Traits/PrimitiveSequence/Completable+AndThen.swift"; sourceTree = ""; }; + A2FB155675AB0F9CD4391CE05510152D /* ObservableConvertibleType.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = ObservableConvertibleType.swift; path = RxSwift/ObservableConvertibleType.swift; sourceTree = ""; }; + A3340A012067886751EC877DE2A085FB /* KFAnimatedImage.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = KFAnimatedImage.swift; path = Sources/SwiftUI/KFAnimatedImage.swift; sourceTree = ""; }; + A35CA8960849EFAC715838CF15CFD05D /* ConstraintMaker.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = ConstraintMaker.swift; path = Sources/ConstraintMaker.swift; sourceTree = ""; }; + A378747D62E5A19E664AE2A6B7A2ADA6 /* RxRelay.modulemap */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.module; path = RxRelay.modulemap; sourceTree = ""; }; + A3821293C89F3E60BD6231B1E48974A1 /* Properties.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = Properties.swift; path = Source/Properties.swift; sourceTree = ""; }; + A3CC4FE478601A48919D7092CBFF414A /* MoyaError.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = MoyaError.swift; path = Sources/Moya/MoyaError.swift; sourceTree = ""; }; + A3F6B5834C04BE54692EFEF14936348F /* AlamofireExtended.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = AlamofireExtended.swift; path = Source/AlamofireExtended.swift; sourceTree = ""; }; + A4A885E79A8DF08471834BA9D0D31ED3 /* UIApplication+Rx.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = "UIApplication+Rx.swift"; path = "RxCocoa/iOS/UIApplication+Rx.swift"; sourceTree = ""; }; + A4DBD0A365804120DBE621B87A954E25 /* RxCocoaObjCRuntimeError+Extensions.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = "RxCocoaObjCRuntimeError+Extensions.swift"; path = "RxCocoa/Common/RxCocoaObjCRuntimeError+Extensions.swift"; sourceTree = ""; }; + A4E676ABA267DB49404DD1A3CCB33F17 /* WithLatestFrom.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = WithLatestFrom.swift; path = RxSwift/Observables/WithLatestFrom.swift; sourceTree = ""; }; + A52935DC312F87728290A3ACA2167BCD /* ConstraintPriorityTarget.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = ConstraintPriorityTarget.swift; path = Sources/ConstraintPriorityTarget.swift; sourceTree = ""; }; + A54253F4F6876CCFC845DA722D6C8CE8 /* Concat.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = Concat.swift; path = RxSwift/Observables/Concat.swift; sourceTree = ""; }; + A5C55ED5BE5E14115CFDB19FC0330C46 /* UIScrollView+Rx.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = "UIScrollView+Rx.swift"; path = "RxCocoa/iOS/UIScrollView+Rx.swift"; sourceTree = ""; }; + A612F6D773EF0336F7EEA1B142F733F1 /* RxSwift-dummy.m */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.objc; path = "RxSwift-dummy.m"; sourceTree = ""; }; + A6785DD60F3F01E17A54F423E8397E23 /* LayoutConstraint.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = LayoutConstraint.swift; path = Sources/LayoutConstraint.swift; sourceTree = ""; }; + A69562BE3DD6D05DD80BAD1460F44C4C /* Platform.Darwin.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = Platform.Darwin.swift; path = Platform/Platform.Darwin.swift; sourceTree = ""; }; + A69D2E9F349C5F6AC3EC7F70DB0CCFDD /* RxCocoaRuntime.h */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.h; name = RxCocoaRuntime.h; path = RxCocoa/Runtime/include/RxCocoaRuntime.h; sourceTree = ""; }; + A6A3220A212C0BC4ABE0058268E8FAA6 /* Infallible.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = Infallible.swift; path = RxSwift/Traits/Infallible/Infallible.swift; sourceTree = ""; }; + A79AD749EBBF7C8E00F924437B94E568 /* ReflectionHelper.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = ReflectionHelper.swift; path = Source/ReflectionHelper.swift; sourceTree = ""; }; + A8A0F224AF15F0E14442ECFCC641E624 /* MBProgressHUD.h */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.h; path = MBProgressHUD.h; sourceTree = ""; }; + A8D08D8E537F6EC253D8EBE79FC6542A /* UIButton+Kingfisher.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = "UIButton+Kingfisher.swift"; path = "Sources/Extensions/UIButton+Kingfisher.swift"; sourceTree = ""; }; + A91E7B0C850AC3EB49D57C2F5AC657BA /* AddRef.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = AddRef.swift; path = RxSwift/Observables/AddRef.swift; sourceTree = ""; }; + AA050A692C8C8C04436B0CB1E5317D3A /* SnapKit.debug.xcconfig */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = text.xcconfig; path = SnapKit.debug.xcconfig; sourceTree = ""; }; + AA4C20251B8F62BF6DC2548854609658 /* ConstraintMakerEditable.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = ConstraintMakerEditable.swift; path = Sources/ConstraintMakerEditable.swift; sourceTree = ""; }; + AAC31C95D09575257C31EB192272C7C2 /* _RXDelegateProxy.h */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.h; name = _RXDelegateProxy.h; path = RxCocoa/Runtime/include/_RXDelegateProxy.h; sourceTree = ""; }; + AAD6332E824227FDE29BB9A1CB1E6DA4 /* NSDecimalNumberTransform.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = NSDecimalNumberTransform.swift; path = Source/NSDecimalNumberTransform.swift; sourceTree = ""; }; + AB1550C20B92B5D8CBB8484C4660BE90 /* Throttle.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = Throttle.swift; path = RxSwift/Observables/Throttle.swift; sourceTree = ""; }; + AB1E15FD768D00EEFADE79898DA43AA2 /* Metadata.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = Metadata.swift; path = Source/Metadata.swift; sourceTree = ""; }; + AB501C06BD3310ADAA40217FA862D851 /* Deferred.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = Deferred.swift; path = RxSwift/Observables/Deferred.swift; sourceTree = ""; }; + AB870D83096A800ECB5E56E7E76FC933 /* Pods-yinmeng-ios-acknowledgements.plist */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = text.plist.xml; path = "Pods-yinmeng-ios-acknowledgements.plist"; sourceTree = ""; }; + AB91063BFA0B85155CE39C26F80044C5 /* StoryboardSceneBased.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = StoryboardSceneBased.swift; path = Sources/Storyboard/StoryboardSceneBased.swift; sourceTree = ""; }; + ABF8C3D769C418801ABB2905159428B8 /* URLSessionConfiguration+Alamofire.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = "URLSessionConfiguration+Alamofire.swift"; path = "Source/URLSessionConfiguration+Alamofire.swift"; sourceTree = ""; }; + AC6F737678C4E112EBB6476E99F02B44 /* NSButton+Rx.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = "NSButton+Rx.swift"; path = "RxCocoa/macOS/NSButton+Rx.swift"; sourceTree = ""; }; + AD3FD403D8E30A8001D1F494B36EFA49 /* Multicast.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = Multicast.swift; path = RxSwift/Observables/Multicast.swift; sourceTree = ""; }; + ADE256164152BE966B102C5F104FC06F /* ConstraintMultiplierTarget.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = ConstraintMultiplierTarget.swift; path = Sources/ConstraintMultiplierTarget.swift; sourceTree = ""; }; + AEE012945F1ACD7D860DD82B208D5D32 /* HexColorTransform.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = HexColorTransform.swift; path = Source/HexColorTransform.swift; sourceTree = ""; }; + AEEBA06C08ECDC8AA5CCA71C013759FA /* Do.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = Do.swift; path = RxSwift/Observables/Do.swift; sourceTree = ""; }; + AFF9C7F95915AA09C2220E7711A63B74 /* Dematerialize.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = Dematerialize.swift; path = RxSwift/Observables/Dematerialize.swift; sourceTree = ""; }; + B00EB68258A05718515A533A9F917D11 /* ImmediateSchedulerType.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = ImmediateSchedulerType.swift; path = RxSwift/ImmediateSchedulerType.swift; sourceTree = ""; }; + B089112AF8A786152A4CFA32042AA817 /* UIGestureRecognizer+Rx.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = "UIGestureRecognizer+Rx.swift"; path = "RxCocoa/iOS/UIGestureRecognizer+Rx.swift"; sourceTree = ""; }; + B0D85CAD20866F6833A22BDA6668ECB1 /* Cancelable.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = Cancelable.swift; path = RxSwift/Cancelable.swift; sourceTree = ""; }; + B2301559B216DC943D96B6C3EA6187EE /* Take.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = Take.swift; path = RxSwift/Observables/Take.swift; sourceTree = ""; }; + B2679DB8FCA54DDF8E7DA3AC4A11488F /* CredentialsPlugin.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = CredentialsPlugin.swift; path = Sources/Moya/Plugins/CredentialsPlugin.swift; sourceTree = ""; }; + B2958A0E6033229331C79C4CD02FB145 /* SessionDataTask.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = SessionDataTask.swift; path = Sources/Networking/SessionDataTask.swift; sourceTree = ""; }; + B3492495BDAA3EE808EBA7E27B444532 /* Scan.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = Scan.swift; path = RxSwift/Observables/Scan.swift; sourceTree = ""; }; + B35DC4FCD2EEF00AF73453F41872FF54 /* ImageView+Kingfisher.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = "ImageView+Kingfisher.swift"; path = "Sources/Extensions/ImageView+Kingfisher.swift"; sourceTree = ""; }; + B43B6B9F0AC1A3B441577C4268863C3B /* KingfisherOptionsInfo.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = KingfisherOptionsInfo.swift; path = Sources/General/KingfisherOptionsInfo.swift; sourceTree = ""; }; + B4C8D32181C1DD0673EF71FC021C399D /* Just.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = Just.swift; path = RxSwift/Observables/Just.swift; sourceTree = ""; }; + B4F8C603320BB82716CEBA31405BB25A /* RxPickerViewDelegateProxy.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = RxPickerViewDelegateProxy.swift; path = RxCocoa/iOS/Proxies/RxPickerViewDelegateProxy.swift; sourceTree = ""; }; + B4FAC3BE27572FE3185D20211224395A /* Kingfisher-dummy.m */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.objc; path = "Kingfisher-dummy.m"; sourceTree = ""; }; + B5077D9342A7330872B9A75748BED92D /* RxRelay.debug.xcconfig */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = text.xcconfig; path = RxRelay.debug.xcconfig; sourceTree = ""; }; + B725764E388DB9D2EF9D7D8EA6A0B1D3 /* MBProgressHUD.modulemap */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.module; path = MBProgressHUD.modulemap; sourceTree = ""; }; + B90F3E609D4D31B9CE6BA0937072B8DB /* ConstraintDSL.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = ConstraintDSL.swift; path = Sources/ConstraintDSL.swift; sourceTree = ""; }; + BA8EAB6201729627D3C7299F26D4EE54 /* RxRelay-dummy.m */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.objc; path = "RxRelay-dummy.m"; sourceTree = ""; }; + BBE5FECC28B966616BA85A7C62F7FA40 /* AnonymousObserver.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = AnonymousObserver.swift; path = RxSwift/Observers/AnonymousObserver.swift; sourceTree = ""; }; + BC12D927E7A7FFE4391A073866062EF0 /* ObserveOn.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = ObserveOn.swift; path = RxSwift/Observables/ObserveOn.swift; sourceTree = ""; }; + BC432FD48A5932251F1CAFBC4BF74894 /* RxCocoa */ = {isa = PBXFileReference; explicitFileType = wrapper.framework; includeInIndex = 0; name = RxCocoa; path = RxCocoa.framework; sourceTree = BUILT_PRODUCTS_DIR; }; + BDC9E1192B2CBB200B902E65C687D558 /* NetworkLoggerPlugin.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = NetworkLoggerPlugin.swift; path = Sources/Moya/Plugins/NetworkLoggerPlugin.swift; sourceTree = ""; }; + BE3D4635725BE29F6866D4B1964447A8 /* KFImageOptions.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = KFImageOptions.swift; path = Sources/SwiftUI/KFImageOptions.swift; sourceTree = ""; }; + BE8D91CD998AB1AE8E676FD3F36C8F2D /* UITextField+Rx.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = "UITextField+Rx.swift"; path = "RxCocoa/iOS/UITextField+Rx.swift"; sourceTree = ""; }; + BF481B014D924D41F0FDE7089D3263B0 /* Range.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = Range.swift; path = RxSwift/Observables/Range.swift; sourceTree = ""; }; + C019E68F4B2DE55C5FD2493950035664 /* ConstraintRelatableTarget.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = ConstraintRelatableTarget.swift; path = Sources/ConstraintRelatableTarget.swift; sourceTree = ""; }; + C0F94D368DE622488019CFFA18E34262 /* RedirectHandler.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = RedirectHandler.swift; path = Source/RedirectHandler.swift; sourceTree = ""; }; + C1706327EA78CAEFF1336CC5568AD36C /* NotificationCenter+Rx.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = "NotificationCenter+Rx.swift"; path = "RxCocoa/Foundation/NotificationCenter+Rx.swift"; sourceTree = ""; }; + C22601C0B2814C78512F594A7731DE19 /* SharedSequence+Operators+arity.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = "SharedSequence+Operators+arity.swift"; path = "RxCocoa/Traits/SharedSequence/SharedSequence+Operators+arity.swift"; sourceTree = ""; }; + C2265CF40B5E3E71870047392079AF16 /* Response.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = Response.swift; path = Sources/Moya/Response.swift; sourceTree = ""; }; + C298ABB78D9B05529B89D8322DB2E7B0 /* Kingfisher-Kingfisher */ = {isa = PBXFileReference; explicitFileType = wrapper.cfbundle; includeInIndex = 0; name = "Kingfisher-Kingfisher"; path = Kingfisher.bundle; sourceTree = BUILT_PRODUCTS_DIR; }; + C32614C0F923CC34E7C2BE3F692976AB /* SectionedViewDataSourceType.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = SectionedViewDataSourceType.swift; path = RxCocoa/Common/SectionedViewDataSourceType.swift; sourceTree = ""; }; + C33F711F76B40DF65DA404994ED241BA /* PriorityQueue.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = PriorityQueue.swift; path = Platform/DataStructures/PriorityQueue.swift; sourceTree = ""; }; + C3ABFDAE24AACD8E1EEE68793DE9803B /* MBProgressHUD-umbrella.h */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.h; path = "MBProgressHUD-umbrella.h"; sourceTree = ""; }; + C3D7C8B8CB5663108F150E48EB940FDF /* ExtendCustomBasicType.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = ExtendCustomBasicType.swift; path = Source/ExtendCustomBasicType.swift; sourceTree = ""; }; + C3F44C782D64D7EB20B61CE3844EBFAD /* Kingfisher */ = {isa = PBXFileReference; explicitFileType = wrapper.framework; includeInIndex = 0; name = Kingfisher; path = Kingfisher.framework; sourceTree = BUILT_PRODUCTS_DIR; }; + C4166DF44E4B7DCF69575608F281517C /* MBProgressHUD-dummy.m */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.objc; path = "MBProgressHUD-dummy.m"; sourceTree = ""; }; + C426FFC0480ABDFDDC457EE5FE191E5E /* DefaultIfEmpty.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = DefaultIfEmpty.swift; path = RxSwift/Observables/DefaultIfEmpty.swift; sourceTree = ""; }; + C45FE00D96FB11A4BF6998884E30C879 /* Reduce.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = Reduce.swift; path = RxSwift/Observables/Reduce.swift; sourceTree = ""; }; + C4E611CCA47B1AFF3C1E57F8C2965B0C /* URLRequest+Alamofire.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = "URLRequest+Alamofire.swift"; path = "Source/URLRequest+Alamofire.swift"; sourceTree = ""; }; + C4E6211C49C3ADB158FA16A1751D5E34 /* InvocableType.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = InvocableType.swift; path = RxSwift/Schedulers/Internal/InvocableType.swift; sourceTree = ""; }; + C526294611337A8D4EF5C3D3D571C77B /* RxTarget.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = RxTarget.swift; path = RxCocoa/Common/RxTarget.swift; sourceTree = ""; }; + C599239C5C9502586FE95F6C59479D15 /* AnyExtensions.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = AnyExtensions.swift; path = Source/AnyExtensions.swift; sourceTree = ""; }; + C689E3BB4983E6D479A62F1211506E90 /* BehaviorSubject.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = BehaviorSubject.swift; path = RxSwift/Subjects/BehaviorSubject.swift; sourceTree = ""; }; + C6D030CA131DAC625D4D9FDC5FD000E3 /* Request.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = Request.swift; path = Source/Request.swift; sourceTree = ""; }; + C71988E85D3858110A6CEEF81B0B0CBE /* Reusable.release.xcconfig */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = text.xcconfig; path = Reusable.release.xcconfig; sourceTree = ""; }; + C7CE4D7E07321EBA8053DBEF4867408A /* Pods-yinmeng-ios.debug.xcconfig */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = text.xcconfig; path = "Pods-yinmeng-ios.debug.xcconfig"; sourceTree = ""; }; + C807A9D8CD9D55D1BD98345635AE1623 /* ValidationType.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = ValidationType.swift; path = Sources/Moya/ValidationType.swift; sourceTree = ""; }; + C8B337D475349119A9023DB9A04FAED7 /* ISO8601DateTransform.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = ISO8601DateTransform.swift; path = Source/ISO8601DateTransform.swift; sourceTree = ""; }; + C8B66F25D7F18C08892764CAD99E025D /* KFOptionsSetter.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = KFOptionsSetter.swift; path = Sources/General/KFOptionsSetter.swift; sourceTree = ""; }; + C909B32972D2D22DB9AE521E98C47040 /* OperationQueueScheduler.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = OperationQueueScheduler.swift; path = RxSwift/Schedulers/OperationQueueScheduler.swift; sourceTree = ""; }; + C963DD2091D258FD11B459ACF20AF09A /* CPListItem+Kingfisher.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = "CPListItem+Kingfisher.swift"; path = "Sources/Extensions/CPListItem+Kingfisher.swift"; sourceTree = ""; }; + CA138CAED2178679471A0C1994A53ADD /* UIStepper+Rx.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = "UIStepper+Rx.swift"; path = "RxCocoa/iOS/UIStepper+Rx.swift"; sourceTree = ""; }; + CA8EB7DF526B4C2F17EB0BBE0F8760CC /* ParameterEncoder.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = ParameterEncoder.swift; path = Source/ParameterEncoder.swift; sourceTree = ""; }; + CBB2733EB8602C8BA1DE249204349BBB /* ConstraintDirectionalInsetTarget.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = ConstraintDirectionalInsetTarget.swift; path = Sources/ConstraintDirectionalInsetTarget.swift; sourceTree = ""; }; + CBFCE48108EA5B7391D309F207FA3E5A /* Reusable-umbrella.h */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.h; path = "Reusable-umbrella.h"; sourceTree = ""; }; + CC92DDE2881965C74B23F6A422B435B3 /* Zip+Collection.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = "Zip+Collection.swift"; path = "RxSwift/Observables/Zip+Collection.swift"; sourceTree = ""; }; + CCB3459EBA17D69CB52198314FF7186C /* Response.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = Response.swift; path = Source/Response.swift; sourceTree = ""; }; + CCF0B72B35A6BCD96CBC1A3F6A6ED7B4 /* ServerTrustEvaluation.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = ServerTrustEvaluation.swift; path = Source/ServerTrustEvaluation.swift; sourceTree = ""; }; + CD4F149DBFD18F4A20A4320599D8CC19 /* KingfisherError.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = KingfisherError.swift; path = Sources/General/KingfisherError.swift; sourceTree = ""; }; + CD54121DDA84872534168702B5F92950 /* HandyJSON.framework */ = {isa = PBXFileReference; explicitFileType = wrapper.framework; includeInIndex = 0; path = HandyJSON.framework; sourceTree = BUILT_PRODUCTS_DIR; }; + CD8E57ECFD6B142763B5C63323162920 /* ObservableType+Extensions.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = "ObservableType+Extensions.swift"; path = "RxSwift/ObservableType+Extensions.swift"; sourceTree = ""; }; + CE1FB66738FC326A45E13D4A2F9039DC /* Reusable.modulemap */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.module; path = Reusable.modulemap; sourceTree = ""; }; + CF107C4AC5643080B30C4DC1AD3CA088 /* Binder.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = Binder.swift; path = RxSwift/Binder.swift; sourceTree = ""; }; + CF2909F5D4495CA4ADC352EEF99AA4EC /* Signal.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = Signal.swift; path = RxCocoa/Traits/Signal/Signal.swift; sourceTree = ""; }; + CF309802F2CAB75940F49AD77E8DFA05 /* _RXDelegateProxy.m */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.objc; name = _RXDelegateProxy.m; path = RxCocoa/Runtime/_RXDelegateProxy.m; sourceTree = ""; }; + CFD438AE9A13700F3A27158491EDF9CD /* DistinctUntilChanged.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = DistinctUntilChanged.swift; path = RxSwift/Observables/DistinctUntilChanged.swift; sourceTree = ""; }; + D05C01883F0A989F4169EA75A319E4CE /* NSObject+Rx+KVORepresentable.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = "NSObject+Rx+KVORepresentable.swift"; path = "RxCocoa/Foundation/NSObject+Rx+KVORepresentable.swift"; sourceTree = ""; }; + D1336AFDB9F472B9E17B6861880F66FA /* Accelerate.framework */ = {isa = PBXFileReference; lastKnownFileType = wrapper.framework; name = Accelerate.framework; path = Platforms/iPhoneOS.platform/Developer/SDKs/iPhoneOS14.0.sdk/System/Library/Frameworks/Accelerate.framework; sourceTree = DEVELOPER_DIR; }; + D205770569FAE2C81B52F154322D2563 /* Reusable-dummy.m */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.objc; path = "Reusable-dummy.m"; sourceTree = ""; }; + D247DB9583EC8A9EA2396FEEE9A0BEBC /* Window.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = Window.swift; path = RxSwift/Observables/Window.swift; sourceTree = ""; }; + D37B24A95EEF2249678FBE363925D312 /* UICollectionView+Rx.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = "UICollectionView+Rx.swift"; path = "RxCocoa/iOS/UICollectionView+Rx.swift"; sourceTree = ""; }; + D389385F88DD239B71595D6B278BC5EA /* Sink.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = Sink.swift; path = RxSwift/Observables/Sink.swift; sourceTree = ""; }; + D38B8AB8BAF2B28F16F577931098B969 /* ConcurrentDispatchQueueScheduler.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = ConcurrentDispatchQueueScheduler.swift; path = RxSwift/Schedulers/ConcurrentDispatchQueueScheduler.swift; sourceTree = ""; }; + D3D2E46D8BE94722DCF2428829BFE1C4 /* Moya+Alamofire.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = "Moya+Alamofire.swift"; path = "Sources/Moya/Moya+Alamofire.swift"; sourceTree = ""; }; + D4F121F8F3564995DB1C8EEF45128BEC /* RxCocoa.debug.xcconfig */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = text.xcconfig; path = RxCocoa.debug.xcconfig; sourceTree = ""; }; + D5405426B1D820B97554FFA85005A6A7 /* DisposeBag.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = DisposeBag.swift; path = RxSwift/Disposables/DisposeBag.swift; sourceTree = ""; }; + D5773666DA885BF217F31523BE08FD6B /* ConstraintViewDSL.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = ConstraintViewDSL.swift; path = Sources/ConstraintViewDSL.swift; sourceTree = ""; }; + D6575A7C92CAA45BC7CAAB15672122A1 /* SkipUntil.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = SkipUntil.swift; path = RxSwift/Observables/SkipUntil.swift; sourceTree = ""; }; + D6D6C3517EAD559475BB89B3A07F826D /* ConstraintConfig.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = ConstraintConfig.swift; path = Sources/ConstraintConfig.swift; sourceTree = ""; }; + D741ADECEE7BA668846D15DEE1332031 /* CustomDateFormatTransform.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = CustomDateFormatTransform.swift; path = Source/CustomDateFormatTransform.swift; sourceTree = ""; }; + D88811C8F2904BE3EDD7B26CE505C673 /* RecursiveLock.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = RecursiveLock.swift; path = Platform/RecursiveLock.swift; sourceTree = ""; }; + D9244D2668F560CE0CB0F0065186F8EB /* Observable+Bind.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = "Observable+Bind.swift"; path = "RxRelay/Observable+Bind.swift"; sourceTree = ""; }; + D9278F439B7C4235C53C200B17F84E46 /* ConstraintLayoutSupportDSL.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = ConstraintLayoutSupportDSL.swift; path = Sources/ConstraintLayoutSupportDSL.swift; sourceTree = ""; }; + D93E22C14E699039A509F617FA39695B /* NSButton+Kingfisher.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = "NSButton+Kingfisher.swift"; path = "Sources/Extensions/NSButton+Kingfisher.swift"; sourceTree = ""; }; + DA05AFE5E1E48A41436B4A70147E660C /* CombineLatest+arity.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = "CombineLatest+arity.swift"; path = "RxSwift/Observables/CombineLatest+arity.swift"; sourceTree = ""; }; + DA54EB4CF78AC3516E9E65506DE207FB /* VirtualTimeScheduler.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = VirtualTimeScheduler.swift; path = RxSwift/Schedulers/VirtualTimeScheduler.swift; sourceTree = ""; }; + DB2C7BCF3EA896AC2BAD9CAD275BB460 /* AnimatedImageView.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = AnimatedImageView.swift; path = Sources/Views/AnimatedImageView.swift; sourceTree = ""; }; + DB9D0DFFB1AA39DDF8B49325F07BEBD1 /* AuthenticationInterceptor.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = AuthenticationInterceptor.swift; path = Source/AuthenticationInterceptor.swift; sourceTree = ""; }; + DCD283B934B4346CF12CEB62458A829D /* ImagePrefetcher.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = ImagePrefetcher.swift; path = Sources/Networking/ImagePrefetcher.swift; sourceTree = ""; }; + DCE9ED04C9F6410492A87A2B8BC43451 /* Zip+arity.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = "Zip+arity.swift"; path = "RxSwift/Observables/Zip+arity.swift"; sourceTree = ""; }; + DCEC2DBF8E26969A4BB2B54F2B1EA8A7 /* NSControl+Rx.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = "NSControl+Rx.swift"; path = "RxCocoa/macOS/NSControl+Rx.swift"; sourceTree = ""; }; + DDB4D4AEF2A47181ABD692BE53C6DF1A /* Bag.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = Bag.swift; path = Platform/DataStructures/Bag.swift; sourceTree = ""; }; + DEA1B032D5AF107EC317CDAE847D3CE5 /* RxMutableBox.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = RxMutableBox.swift; path = RxSwift/RxMutableBox.swift; sourceTree = ""; }; + DEA6B630488DF0930202C22D36F757CB /* DateFormatterTransform.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = DateFormatterTransform.swift; path = Source/DateFormatterTransform.swift; sourceTree = ""; }; + DEBFD271D48A85EF07F3B6731D534416 /* InfiniteSequence.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = InfiniteSequence.swift; path = Platform/DataStructures/InfiniteSequence.swift; sourceTree = ""; }; + DF2E2C729461BB0F5D730E63F64A5F23 /* RxPickerViewDataSourceType.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = RxPickerViewDataSourceType.swift; path = RxCocoa/iOS/Protocols/RxPickerViewDataSourceType.swift; sourceTree = ""; }; + DF65591BAA77BD5923D4083691EB5F0F /* URLConvertible+URLRequestConvertible.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = "URLConvertible+URLRequestConvertible.swift"; path = "Source/URLConvertible+URLRequestConvertible.swift"; sourceTree = ""; }; + DFBC5B2993997B725D364216FE7C3DF6 /* ImageModifier.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = ImageModifier.swift; path = Sources/Networking/ImageModifier.swift; sourceTree = ""; }; + DFCC95E9F5590674CB559C0596A2DC4A /* ItemEvents.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = ItemEvents.swift; path = RxCocoa/iOS/Events/ItemEvents.swift; sourceTree = ""; }; + DFDBA24A5039ED5E5456D2E8FC495205 /* Completable.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = Completable.swift; path = RxSwift/Traits/PrimitiveSequence/Completable.swift; sourceTree = ""; }; + E0231B13AFD942D7715BD4A70ABFE808 /* ConstraintMakerPrioritizable.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = ConstraintMakerPrioritizable.swift; path = Sources/ConstraintMakerPrioritizable.swift; sourceTree = ""; }; + E02AEC6F043CC7E4CACFA5D1EFD6EB27 /* Driver.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = Driver.swift; path = RxCocoa/Traits/Driver/Driver.swift; sourceTree = ""; }; + E08F77D6D513C32F418E1FC2AE7AD85A /* AsMaybe.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = AsMaybe.swift; path = RxSwift/Observables/AsMaybe.swift; sourceTree = ""; }; + E1876E647F0F13D8AD9A41FED3B7C6C2 /* Producer.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = Producer.swift; path = RxSwift/Observables/Producer.swift; sourceTree = ""; }; + E20F55B135E3C24173DF453318747D59 /* InfiniteSequence.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = InfiniteSequence.swift; path = Platform/DataStructures/InfiniteSequence.swift; sourceTree = ""; }; + E2CC1F55AB1BB43F87FEC4D4CD10D1FE /* CBridge.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = CBridge.swift; path = Source/CBridge.swift; sourceTree = ""; }; + E3A080F230A46B8C0F73FF8AA678A95A /* Pods-yinmeng-ios-Info.plist */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = text.plist.xml; path = "Pods-yinmeng-ios-Info.plist"; sourceTree = ""; }; + E3F3D140901AD39649AC074216CAC836 /* RxPickerViewDataSourceProxy.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = RxPickerViewDataSourceProxy.swift; path = RxCocoa/iOS/Proxies/RxPickerViewDataSourceProxy.swift; sourceTree = ""; }; + E4AD07036A83707DD229318C03B6CE81 /* Infallible+Concurrency.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = "Infallible+Concurrency.swift"; path = "RxSwift/Traits/Infallible/Infallible+Concurrency.swift"; sourceTree = ""; }; + E4E95E8B077E462C80766715ADCA4CF0 /* Map.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = Map.swift; path = RxSwift/Observables/Map.swift; sourceTree = ""; }; + E520F3EC8458D3F1E6174E0EC460E79B /* SharedSequence+Operators.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = "SharedSequence+Operators.swift"; path = "RxCocoa/Traits/SharedSequence/SharedSequence+Operators.swift"; sourceTree = ""; }; + E52F3E93B1A3D47F523D83D8473237C0 /* RxCollectionViewReactiveArrayDataSource.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = RxCollectionViewReactiveArrayDataSource.swift; path = RxCocoa/iOS/DataSources/RxCollectionViewReactiveArrayDataSource.swift; sourceTree = ""; }; + E597FA331BDE835D4356BA91AC2EE05B /* SessionDelegate.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = SessionDelegate.swift; path = Source/SessionDelegate.swift; sourceTree = ""; }; + E60F8ED3C26A4DFE0400C21FB2BE072B /* ConstraintLayoutSupport.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = ConstraintLayoutSupport.swift; path = Sources/ConstraintLayoutSupport.swift; sourceTree = ""; }; + E68CB21AF7E7B8C4BFF5A00B209D9666 /* Sequence.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = Sequence.swift; path = RxSwift/Observables/Sequence.swift; sourceTree = ""; }; + E6EA7642AC0A935140B695C8DE1F91B1 /* HandyJSON-umbrella.h */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.h; path = "HandyJSON-umbrella.h"; sourceTree = ""; }; + E727269035DBECA74CF6FA02E1B24B09 /* UITabBarController+Rx.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = "UITabBarController+Rx.swift"; path = "RxCocoa/iOS/UITabBarController+Rx.swift"; sourceTree = ""; }; + E743F2C861099DDED46F43D21958AD4E /* Moya.debug.xcconfig */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = text.xcconfig; path = Moya.debug.xcconfig; sourceTree = ""; }; + E76B1466F3C89ABD081A805991109083 /* RxTextStorageDelegateProxy.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = RxTextStorageDelegateProxy.swift; path = RxCocoa/iOS/Proxies/RxTextStorageDelegateProxy.swift; sourceTree = ""; }; + E78DB89A84C09AD3FA55F3FEF697370C /* SchedulerServices+Emulation.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = "SchedulerServices+Emulation.swift"; path = "RxSwift/Schedulers/SchedulerServices+Emulation.swift"; sourceTree = ""; }; + E7B65070F724AC357CCEA7DBCA350373 /* ConstraintConstantTarget.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = ConstraintConstantTarget.swift; path = Sources/ConstraintConstantTarget.swift; sourceTree = ""; }; + E83D56D118A8CD729AB9F4DD106214B6 /* SwitchIfEmpty.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = SwitchIfEmpty.swift; path = RxSwift/Observables/SwitchIfEmpty.swift; sourceTree = ""; }; + E8A3665F113C176C699C4A60D6739452 /* KVORepresentable.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = KVORepresentable.swift; path = RxCocoa/Foundation/KVORepresentable.swift; sourceTree = ""; }; + E8FC0222908D1595E407695DD27A15FB /* NSObject+Rx+RawRepresentable.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = "NSObject+Rx+RawRepresentable.swift"; path = "RxCocoa/Foundation/NSObject+Rx+RawRepresentable.swift"; sourceTree = ""; }; + EAEC2944E172B383CBFA48D2746EFFEC /* Alamofire-Info.plist */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = text.plist.xml; path = "Alamofire-Info.plist"; sourceTree = ""; }; + EB54968F135513C686F7D4461CD71248 /* Kingfisher-Info.plist */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = text.plist.xml; path = "Kingfisher-Info.plist"; sourceTree = ""; }; + EC50DBE03FF22FAAF1D4BE41AAFB9A8A /* ElementAt.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = ElementAt.swift; path = RxSwift/Observables/ElementAt.swift; sourceTree = ""; }; + ECAC747BA8670ABD37A0C5AA715875AF /* SnapKit-dummy.m */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.objc; path = "SnapKit-dummy.m"; sourceTree = ""; }; + ECBD12025121C746DDEB9B44E608E3E6 /* Utils.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = Utils.swift; path = RxRelay/Utils.swift; sourceTree = ""; }; + ED35C12CB343C92F81259E4F33B299B5 /* Amb.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = Amb.swift; path = RxSwift/Observables/Amb.swift; sourceTree = ""; }; + ED443DD7A5B81CF799FF1A9B14CA60C8 /* First.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = First.swift; path = RxSwift/Observables/First.swift; sourceTree = ""; }; + ED806FA43E5458BB64EB1B488B5B6772 /* ScheduledItem.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = ScheduledItem.swift; path = RxSwift/Schedulers/Internal/ScheduledItem.swift; sourceTree = ""; }; + EDB3853E94E387C7E2F1D43C468ED500 /* OtherExtension.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = OtherExtension.swift; path = Source/OtherExtension.swift; sourceTree = ""; }; + EE92ADF7F5D694CD90670878273D0E22 /* ConstraintInsets.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = ConstraintInsets.swift; path = Sources/ConstraintInsets.swift; sourceTree = ""; }; + EEB214E2E4C3D3FB6CA0C4109D2F0FF6 /* RxTableViewReactiveArrayDataSource.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = RxTableViewReactiveArrayDataSource.swift; path = RxCocoa/iOS/DataSources/RxTableViewReactiveArrayDataSource.swift; sourceTree = ""; }; + EF183BEFE853EAAC18B3D0F5E20DE4C9 /* RxRelay-prefix.pch */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.h; path = "RxRelay-prefix.pch"; sourceTree = ""; }; + EF5F5DC6C61E0C786AA3BA02874662A1 /* ControlTarget.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = ControlTarget.swift; path = RxCocoa/Common/ControlTarget.swift; sourceTree = ""; }; + EF820E238AB6C626388D71E7F83DD362 /* UILayoutSupport+Extensions.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = "UILayoutSupport+Extensions.swift"; path = "Sources/UILayoutSupport+Extensions.swift"; sourceTree = ""; }; + EFC734B57692B8F617FD03908D932F63 /* ObservableConvertibleType+Driver.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = "ObservableConvertibleType+Driver.swift"; path = "RxCocoa/Traits/Driver/ObservableConvertibleType+Driver.swift"; sourceTree = ""; }; + EFD03F6EF61FF91A6224DD8CF8BF2FCE /* ObservableConvertibleType+Signal.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = "ObservableConvertibleType+Signal.swift"; path = "RxCocoa/Traits/Signal/ObservableConvertibleType+Signal.swift"; sourceTree = ""; }; + F02A17D4EB2C620CA1EDD34E9934989F /* Task.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = Task.swift; path = Sources/Moya/Task.swift; sourceTree = ""; }; + F035F0F1D2D858918B6C937E1F71A98E /* ObservableConvertibleType+SharedSequence.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = "ObservableConvertibleType+SharedSequence.swift"; path = "RxCocoa/Traits/SharedSequence/ObservableConvertibleType+SharedSequence.swift"; sourceTree = ""; }; + F0933F5FD3BA39AA382ECC963D6550B8 /* HTTPHeaders.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = HTTPHeaders.swift; path = Source/HTTPHeaders.swift; sourceTree = ""; }; + F098DF51276D641070E6E01539D4B986 /* NSTextAttachment+Kingfisher.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = "NSTextAttachment+Kingfisher.swift"; path = "Sources/Extensions/NSTextAttachment+Kingfisher.swift"; sourceTree = ""; }; + F0A41DDDA8CABBF8754FE1EE9942B51A /* DataTransform.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = DataTransform.swift; path = Source/DataTransform.swift; sourceTree = ""; }; + F1A40D020BF4C65249FEA2EDF53B89F5 /* RxSwift-umbrella.h */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.h; path = "RxSwift-umbrella.h"; sourceTree = ""; }; + F2D487B9F0F6B5545D5A1715E39B9BCA /* Buffer.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = Buffer.swift; path = RxSwift/Observables/Buffer.swift; sourceTree = ""; }; + F306E6A5D3D559D9E47C8FF351159D2B /* TextInput.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = TextInput.swift; path = RxCocoa/Common/TextInput.swift; sourceTree = ""; }; + F329A03B4D1A8412BFD9F49535A2D291 /* ImageProgressive.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = ImageProgressive.swift; path = Sources/Image/ImageProgressive.swift; sourceTree = ""; }; + F3C1412570858A4A38DEC91D9865AC1F /* Alamofire.modulemap */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.module; path = Alamofire.modulemap; sourceTree = ""; }; + F3DA46923ADA705C392069960BB60E9A /* SingleAssignmentDisposable.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = SingleAssignmentDisposable.swift; path = RxSwift/Disposables/SingleAssignmentDisposable.swift; sourceTree = ""; }; + F3EF76F454F323E3B71A0221AFFC8238 /* NSTextField+Rx.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = "NSTextField+Rx.swift"; path = "RxCocoa/macOS/NSTextField+Rx.swift"; sourceTree = ""; }; + F4457E12C3F2B5AADAA643E6B0F5C555 /* BuiltInBridgeType.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = BuiltInBridgeType.swift; path = Source/BuiltInBridgeType.swift; sourceTree = ""; }; + F45DCBE864FA17C68B639547AEB93B03 /* Merge.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = Merge.swift; path = RxSwift/Observables/Merge.swift; sourceTree = ""; }; + F52EC1967CD22048EB37327070C47EB5 /* ConstraintRelation.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = ConstraintRelation.swift; path = Sources/ConstraintRelation.swift; sourceTree = ""; }; + F63084A32C04D39192F17E5B2082033C /* OperationQueue+Alamofire.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = "OperationQueue+Alamofire.swift"; path = "Source/OperationQueue+Alamofire.swift"; sourceTree = ""; }; + F75DD06A2A169049C9A0D1E77A6D13EA /* UIBarButtonItem+Rx.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = "UIBarButtonItem+Rx.swift"; path = "RxCocoa/iOS/UIBarButtonItem+Rx.swift"; sourceTree = ""; }; + F7B5707C4DB109E219C5031257DCD1F3 /* ControlProperty+Driver.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = "ControlProperty+Driver.swift"; path = "RxCocoa/Traits/Driver/ControlProperty+Driver.swift"; sourceTree = ""; }; + F9E3641046F777BA820AB2055AA51792 /* RequestModifier.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = RequestModifier.swift; path = Sources/Networking/RequestModifier.swift; sourceTree = ""; }; + F9F013D28FC8ECBAF33DF99272DEC729 /* Delegate.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = Delegate.swift; path = Sources/Utility/Delegate.swift; sourceTree = ""; }; + FA5485B4C3E504F337F2AD065ABAEF76 /* ConnectableObservableType.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = ConnectableObservableType.swift; path = RxSwift/ConnectableObservableType.swift; sourceTree = ""; }; + FA5D56DE5D48CA926F73DF626BACA99D /* SynchronizedUnsubscribeType.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = SynchronizedUnsubscribeType.swift; path = RxSwift/Concurrency/SynchronizedUnsubscribeType.swift; sourceTree = ""; }; + FA88BA483915DE8B6B9D5D7B9A4AAE90 /* Platform.Darwin.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = Platform.Darwin.swift; path = Platform/Platform.Darwin.swift; sourceTree = ""; }; + FA92B06C831BE63EC9C993A1217E090D /* MBProgressHUD.release.xcconfig */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = text.xcconfig; path = MBProgressHUD.release.xcconfig; sourceTree = ""; }; + FAC78FA49D7FB72A1D9081306F499298 /* ConstraintView+Extensions.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = "ConstraintView+Extensions.swift"; path = "Sources/ConstraintView+Extensions.swift"; sourceTree = ""; }; + FB540682DA51451BDAD851F89E558DD5 /* QuartzCore.framework */ = {isa = PBXFileReference; lastKnownFileType = wrapper.framework; name = QuartzCore.framework; path = Platforms/iPhoneOS.platform/Developer/SDKs/iPhoneOS14.0.sdk/System/Library/Frameworks/QuartzCore.framework; sourceTree = DEVELOPER_DIR; }; + FB5DD901158FEFCA27ADE24D3A8E12FA /* ImageDataProcessor.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = ImageDataProcessor.swift; path = Sources/Networking/ImageDataProcessor.swift; sourceTree = ""; }; + FBA54F39E869CCC3D040A46FA1737ED1 /* HandyJSON-Info.plist */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = text.plist.xml; path = "HandyJSON-Info.plist"; sourceTree = ""; }; + FBD270BC6C902DDBA8971425BF78B4A3 /* RecursiveLock.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = RecursiveLock.swift; path = Platform/RecursiveLock.swift; sourceTree = ""; }; + FBD96A9F6932FA01432273082AB94D9C /* LockOwnerType.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = LockOwnerType.swift; path = RxSwift/Concurrency/LockOwnerType.swift; sourceTree = ""; }; + FBDDA0D117F42E4FE226978800527457 /* FormatIndicatedCacheSerializer.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = FormatIndicatedCacheSerializer.swift; path = Sources/Cache/FormatIndicatedCacheSerializer.swift; sourceTree = ""; }; + FC28EF831FDDD06091CC7AB0416845FC /* PrimitiveSequence+Zip+arity.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = "PrimitiveSequence+Zip+arity.swift"; path = "RxSwift/Traits/PrimitiveSequence/PrimitiveSequence+Zip+arity.swift"; sourceTree = ""; }; + FE06975BE3E77F3DFD642DD868FE617D /* NSView+Rx.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = "NSView+Rx.swift"; path = "RxCocoa/macOS/NSView+Rx.swift"; sourceTree = ""; }; + FE2C700E88155AD2A39178D87B6644F5 /* ImageProcessor.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = ImageProcessor.swift; path = Sources/Image/ImageProcessor.swift; sourceTree = ""; }; + FE77747AB7C6876DC80B43C5DCE4ABF0 /* ConstraintItem.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = ConstraintItem.swift; path = Sources/ConstraintItem.swift; sourceTree = ""; }; + FEDFCFC90E99F4AD01D5647DF4CB5FB4 /* Bag.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = Bag.swift; path = Platform/DataStructures/Bag.swift; sourceTree = ""; }; + FF8B264DFE802855D5D67E7CDDABFC3C /* RxRelay */ = {isa = PBXFileReference; explicitFileType = wrapper.framework; includeInIndex = 0; name = RxRelay; path = RxRelay.framework; sourceTree = BUILT_PRODUCTS_DIR; }; +/* End PBXFileReference section */ + +/* Begin PBXFrameworksBuildPhase section */ + 022CF4B8BBD5C8D34A275928347518C5 /* Frameworks */ = { + isa = PBXFrameworksBuildPhase; + buildActionMask = 2147483647; + files = ( + 71E6B1C3D8711A083F76B6D3C0D561B6 /* Foundation.framework in Frameworks */, + ); + runOnlyForDeploymentPostprocessing = 0; + }; + 41444FC6B9FA2D386D58EF06093B5C77 /* Frameworks */ = { + isa = PBXFrameworksBuildPhase; + buildActionMask = 2147483647; + files = ( + E7123AB366D99D42043E352B1A128369 /* Foundation.framework in Frameworks */, + ); + runOnlyForDeploymentPostprocessing = 0; + }; + 5BF6E64D3157435E5797A5278584A4DC /* Frameworks */ = { + isa = PBXFrameworksBuildPhase; + buildActionMask = 2147483647; + files = ( + D7BCBE1EB4A638403C265CE2199EFF1B /* CFNetwork.framework in Frameworks */, + 8E85763AE29BEF0A46EE875B8F069E8E /* Foundation.framework in Frameworks */, + ); + runOnlyForDeploymentPostprocessing = 0; + }; + 5BFADEC849BD22C6CD97E83544F3E6C1 /* Frameworks */ = { + isa = PBXFrameworksBuildPhase; + buildActionMask = 2147483647; + files = ( + 5CCB87A1A86D7C03A5D678B262B37071 /* Foundation.framework in Frameworks */, + ); + runOnlyForDeploymentPostprocessing = 0; + }; + 5FE88477180E51E6261C299B8858B2F2 /* Frameworks */ = { + isa = PBXFrameworksBuildPhase; + buildActionMask = 2147483647; + files = ( + 52DD330B3BED8407E4EFED176F0B4DBA /* Foundation.framework in Frameworks */, + 533F06C629B5676D3E165946F1CAB400 /* UIKit.framework in Frameworks */, + ); + runOnlyForDeploymentPostprocessing = 0; + }; + 69E41FE1C983D4504EF52D46E5289EA7 /* Frameworks */ = { + isa = PBXFrameworksBuildPhase; + buildActionMask = 2147483647; + files = ( + A77BC5063F494F8F4F92644B6A8C93E0 /* Foundation.framework in Frameworks */, + ); + runOnlyForDeploymentPostprocessing = 0; + }; + 7384B674865A3735705993DE278F24FB /* Frameworks */ = { + isa = PBXFrameworksBuildPhase; + buildActionMask = 2147483647; + files = ( + ); + runOnlyForDeploymentPostprocessing = 0; + }; + 7B0303768C22ED77186E9DAE044BDE14 /* Frameworks */ = { + isa = PBXFrameworksBuildPhase; + buildActionMask = 2147483647; + files = ( + A3F2B57A7C28E3362A8E55F1B015D9C8 /* Accelerate.framework in Frameworks */, + D33F8516AAC7AC1435DCB095BCE65681 /* CFNetwork.framework in Frameworks */, + FC44FD753ECE619F3F635F28B1221DEF /* Foundation.framework in Frameworks */, + ); + runOnlyForDeploymentPostprocessing = 0; + }; + AB4F7BDEBC13070575FC00805E8C810B /* Frameworks */ = { + isa = PBXFrameworksBuildPhase; + buildActionMask = 2147483647; + files = ( + C549FDEDD8E7F6D7AE0B15C125D183A8 /* Foundation.framework in Frameworks */, + ); + runOnlyForDeploymentPostprocessing = 0; + }; + D6DC8F0C2894774845C1DD2E7CA07B0C /* Frameworks */ = { + isa = PBXFrameworksBuildPhase; + buildActionMask = 2147483647; + files = ( + AFAC1D4EBD53A048346210536741DF13 /* CoreGraphics.framework in Frameworks */, + 0AA33EBB857A5205F87C09CCB99EAC74 /* Foundation.framework in Frameworks */, + B52177FF72FDAC3EDB7195DE98F5501E /* QuartzCore.framework in Frameworks */, + ); + runOnlyForDeploymentPostprocessing = 0; + }; + E877FC0D3719519B688F3E17FF0228B2 /* Frameworks */ = { + isa = PBXFrameworksBuildPhase; + buildActionMask = 2147483647; + files = ( + 2987A730911012C32AF6695D7B54E35C /* Foundation.framework in Frameworks */, + ); + runOnlyForDeploymentPostprocessing = 0; + }; + E8E4E7CE8309D3EF7B7476AC57986BE9 /* Frameworks */ = { + isa = PBXFrameworksBuildPhase; + buildActionMask = 2147483647; + files = ( + 0833E66E7F19849322305D67777B77DB /* Foundation.framework in Frameworks */, + ); + runOnlyForDeploymentPostprocessing = 0; + }; +/* End PBXFrameworksBuildPhase section */ + +/* Begin PBXGroup section */ + 087868B262FF2BC66129825C09A683E4 /* Support Files */ = { + isa = PBXGroup; + children = ( + 4D43B9A8506661F18ED1E7EDF570932D /* SnapKit.modulemap */, + ECAC747BA8670ABD37A0C5AA715875AF /* SnapKit-dummy.m */, + 0AA9F81ECF26C389EB0017F3D63D208A /* SnapKit-Info.plist */, + 47110AC6AA4D44E8FCEB9552C18577A1 /* SnapKit-prefix.pch */, + 04860F824879B09726E0E71EE19968C8 /* SnapKit-umbrella.h */, + AA050A692C8C8C04436B0CB1E5317D3A /* SnapKit.debug.xcconfig */, + 74A65654283AE2CF4A3DFA265199F1C5 /* SnapKit.release.xcconfig */, + ); + name = "Support Files"; + path = "../Target Support Files/SnapKit"; + sourceTree = ""; + }; + 0ACF7A29FEB8DF4457DE6C976823731D /* Support Files */ = { + isa = PBXGroup; + children = ( + F3C1412570858A4A38DEC91D9865AC1F /* Alamofire.modulemap */, + 78F5BA1E49C1B6FE56A4B5323CD9AFF8 /* Alamofire-dummy.m */, + EAEC2944E172B383CBFA48D2746EFFEC /* Alamofire-Info.plist */, + 6C4649E78A32C230E03D17B80A888076 /* Alamofire-prefix.pch */, + 166CB5B3B91C1FF4370249653FD8320D /* Alamofire-umbrella.h */, + 19D15B6F087615D6E6964610E2461AAD /* Alamofire.debug.xcconfig */, + 36DFFD75B7479E1705FAC0F110CE34DC /* Alamofire.release.xcconfig */, + ); + name = "Support Files"; + path = "../Target Support Files/Alamofire"; + sourceTree = ""; + }; + 0F9BCF6B6B1C3846EB3915D29498BD08 /* Resources */ = { + isa = PBXGroup; + children = ( + 8B776E2E2FACA7C1A7173E403F37910F /* PrivacyInfo.xcprivacy */, + ); + name = Resources; + sourceTree = ""; + }; + 208D83938308FFB539726DDAF4BDAAC5 /* Targets Support Files */ = { + isa = PBXGroup; + children = ( + AA82EC4AF35A3C8A786A5503BE530EF2 /* Pods-yinmeng-ios */, + ); + name = "Targets Support Files"; + sourceTree = ""; + }; + 295AFD80C44BCD5AE0CFE5ED66C0EF6D /* Support Files */ = { + isa = PBXGroup; + children = ( + 65C3DEA44C88982D1639BC1D3AE788E5 /* RxCocoa.modulemap */, + 8A3398D47F647EC9C9854F30FAA9A225 /* RxCocoa-dummy.m */, + 03480C2AB8FE1C2C40314057985B0228 /* RxCocoa-Info.plist */, + 2BAC1650A187C2915C972E5571EE0B96 /* RxCocoa-prefix.pch */, + 66EAB16FAAFDFDFF614A83B83544F60A /* RxCocoa-umbrella.h */, + D4F121F8F3564995DB1C8EEF45128BEC /* RxCocoa.debug.xcconfig */, + 63CF3F8FFB207D7C17E8DB9CB93EDA1E /* RxCocoa.release.xcconfig */, + ); + name = "Support Files"; + path = "../Target Support Files/RxCocoa"; + sourceTree = ""; + }; + 34329BC0E5C3F008BA4775286EF55C4E /* Support Files */ = { + isa = PBXGroup; + children = ( + A378747D62E5A19E664AE2A6B7A2ADA6 /* RxRelay.modulemap */, + BA8EAB6201729627D3C7299F26D4EE54 /* RxRelay-dummy.m */, + 628E93CA5921A8FC116E3929C680A27B /* RxRelay-Info.plist */, + EF183BEFE853EAAC18B3D0F5E20DE4C9 /* RxRelay-prefix.pch */, + 6DEEF0A78457ED9D46DBF84E913E83F6 /* RxRelay-umbrella.h */, + B5077D9342A7330872B9A75748BED92D /* RxRelay.debug.xcconfig */, + 98AC09B0DB090CDE2D7CC82E1811FA69 /* RxRelay.release.xcconfig */, + ); + name = "Support Files"; + path = "../Target Support Files/RxRelay"; + sourceTree = ""; + }; + 3B5E9879778791C70F44EA9C986AAAF4 /* HandyJSON */ = { + isa = PBXGroup; + children = ( + C599239C5C9502586FE95F6C59479D15 /* AnyExtensions.swift */, + 16B897EE9E0FB539D6DCE44EC4FE5968 /* BuiltInBasicType.swift */, + F4457E12C3F2B5AADAA643E6B0F5C555 /* BuiltInBridgeType.swift */, + E2CC1F55AB1BB43F87FEC4D4CD10D1FE /* CBridge.swift */, + 7430E48DEB35987DD064EE0D7363953F /* Configuration.swift */, + 1B2863E7FB03DAF37957D8B19A20FAF5 /* ContextDescriptorType.swift */, + D741ADECEE7BA668846D15DEE1332031 /* CustomDateFormatTransform.swift */, + F0A41DDDA8CABBF8754FE1EE9942B51A /* DataTransform.swift */, + DEA6B630488DF0930202C22D36F757CB /* DateFormatterTransform.swift */, + 64854FC0AC6AFE7ACB68D2C7BEAAE398 /* DateTransform.swift */, + 972FCFDB49C8D15767A6488B65F2999B /* Deserializer.swift */, + 9D3BCD1EA3553D12354FD5FA1FAE15CC /* EnumTransform.swift */, + 60A3141E90976A3DD62256D0A73B9572 /* EnumType.swift */, + 6009157C9973464C53AFA7E068E984F7 /* Export.swift */, + C3D7C8B8CB5663108F150E48EB940FDF /* ExtendCustomBasicType.swift */, + 5096A43515DC7129C76B0F73FC4B6049 /* ExtendCustomModelType.swift */, + 6438C8BA15E4054D7ACA1E3DFF2066DB /* FieldDescriptor.swift */, + 1710DBE3C7151B8AB47F7A9F74055B64 /* HandyJSON.h */, + 1BBE63969630CA64CDD14AE518F9ED70 /* HelpingMapper.swift */, + AEE012945F1ACD7D860DD82B208D5D32 /* HexColorTransform.swift */, + C8B337D475349119A9023DB9A04FAED7 /* ISO8601DateTransform.swift */, + 418F325839254785FCE40E01EC615D42 /* Logger.swift */, + 2A8DE9D85F9B8D23A00C6EDE272AAE8D /* MangledName.swift */, + 84E7CDD4F491C19202D78BD1D18EA01E /* Measuable.swift */, + AB1E15FD768D00EEFADE79898DA43AA2 /* Metadata.swift */, + AAD6332E824227FDE29BB9A1CB1E6DA4 /* NSDecimalNumberTransform.swift */, + EDB3853E94E387C7E2F1D43C468ED500 /* OtherExtension.swift */, + 6AB41D31B155EAB764A9C053A0DE59CD /* PointerType.swift */, + A3821293C89F3E60BD6231B1E48974A1 /* Properties.swift */, + 477447EAA52D7E8C1E3C05F2DD47F9B1 /* PropertyInfo.swift */, + A79AD749EBBF7C8E00F924437B94E568 /* ReflectionHelper.swift */, + A0989B49F85763612695C610DDE3995F /* Serializer.swift */, + 1DDD0126DBB77C7B793703E3B7918072 /* Transformable.swift */, + 8DA1B7070D9B7E6489E50762BA7CC29B /* TransformOf.swift */, + 1CEDEE8EE3D758478549E54DB2D8CB8D /* TransformType.swift */, + 2C4725814B303164AE7425543FDA788C /* URLTransform.swift */, + 84CB1D96BB3C8A96122B486161B750D5 /* Support Files */, + ); + path = HandyJSON; + sourceTree = ""; + }; + 3FB04A789BFFEAF480028A2C5599933C /* Pods */ = { + isa = PBXGroup; + children = ( + 6648C46CB637AC25933390CFA01B6E44 /* Alamofire */, + 3B5E9879778791C70F44EA9C986AAAF4 /* HandyJSON */, + 8AACD370BEA282A3E8F4B1A30CBEE7BB /* Kingfisher */, + 472947FD3012563582985D640A1C1B89 /* MBProgressHUD */, + C08390ED8A4F067D1F1476DD6F94AEFD /* Moya */, + 6F0835F9A2B10364B21DAD66EE1AED12 /* Reusable */, + E82B7085CA7098C59B6758A4756704C2 /* RxCocoa */, + 4D443E7921FBD163086C75A4E464D0B3 /* RxRelay */, + 8C243E4EC8CAF1BD18D04A085617A090 /* RxSwift */, + BDB006AD0630C93386D9F397A4A6E3E8 /* SnapKit */, + ); + name = Pods; + sourceTree = ""; + }; + 472947FD3012563582985D640A1C1B89 /* MBProgressHUD */ = { + isa = PBXGroup; + children = ( + A8A0F224AF15F0E14442ECFCC641E624 /* MBProgressHUD.h */, + 56969AC68B2EED540B9FBF1E0D237B8D /* MBProgressHUD.m */, + 6D3627A4475DCC07A111B46FA8742810 /* Support Files */, + ); + path = MBProgressHUD; + sourceTree = ""; + }; + 4ACE8263887E88BE1B13DCD869DFFCAF /* Products */ = { + isa = PBXGroup; + children = ( + 5D797E9A5C5782CE845840781FA1CC81 /* Alamofire */, + CD54121DDA84872534168702B5F92950 /* HandyJSON.framework */, + C3F44C782D64D7EB20B61CE3844EBFAD /* Kingfisher */, + C298ABB78D9B05529B89D8322DB2E7B0 /* Kingfisher-Kingfisher */, + 8B8FAB0D627B17EDE1366984278705D9 /* MBProgressHUD.framework */, + 3756A9BBE41ABEE8DCBF5BCA6972C4DA /* Moya */, + 9BC03DDC341E7F14C1F96A0C0F826FD3 /* Pods-yinmeng-ios */, + A0ABA07B4D48354ED3F51C2D6AF5426B /* Reusable */, + BC432FD48A5932251F1CAFBC4BF74894 /* RxCocoa */, + FF8B264DFE802855D5D67E7CDDABFC3C /* RxRelay */, + 809C5FAB588354C9BA37DC3EAB8CB45C /* RxSwift */, + 979486118B3E90C08386079D57962701 /* SnapKit */, + ); + name = Products; + sourceTree = ""; + }; + 4B1B230A86A5086852705822097E9BDB /* Core */ = { + isa = PBXGroup; + children = ( + 9D5A16599059CA238869B241131BA02D /* AccessTokenPlugin.swift */, + 045D5D90782798F36E8E8F973DAC5B28 /* AnyEncodable.swift */, + 9FE80A6E04D0DEC038F7B01D95633AE8 /* Atomic.swift */, + 57BE0C87BBB0A537606F16CD108FAECF /* Cancellable.swift */, + B2679DB8FCA54DDF8E7DA3AC4A11488F /* CredentialsPlugin.swift */, + 6C198ADB3A802CC083707D46D42F735C /* Endpoint.swift */, + 002ED0D813882532198DEB9328551828 /* Image.swift */, + D3D2E46D8BE94722DCF2428829BFE1C4 /* Moya+Alamofire.swift */, + A3CC4FE478601A48919D7092CBFF414A /* MoyaError.swift */, + 6EA8E69F4FC1AD4BC47B9FAA09D391D1 /* MoyaProvider.swift */, + 4189EEA5194A0B67B0929125B7D8F3B9 /* MoyaProvider+Defaults.swift */, + 0764DAF106A0E6A03874313AD80FDDB7 /* MoyaProvider+Internal.swift */, + 8AD039748141FD7199964AF985765430 /* MultipartFormData.swift */, + 1D524DB6FB9E645710C7B04B107FB333 /* MultiTarget.swift */, + 615C9F76DEEA89A8A3638328942C191B /* NetworkActivityPlugin.swift */, + BDC9E1192B2CBB200B902E65C687D558 /* NetworkLoggerPlugin.swift */, + 07360B313B37C9A5C5310D3E0442D54B /* Plugin.swift */, + 9B09861BBDC46C3D1F767E4F57F0FCD6 /* RequestTypeWrapper.swift */, + C2265CF40B5E3E71870047392079AF16 /* Response.swift */, + 91834F0831C28901ECD936CE6E242605 /* TargetType.swift */, + F02A17D4EB2C620CA1EDD34E9934989F /* Task.swift */, + 87AD720C8F2A51587F1C491E884DB664 /* URL+Moya.swift */, + 5859599DB876A373ACA4D7088EA30151 /* URLRequest+Encoding.swift */, + C807A9D8CD9D55D1BD98345635AE1623 /* ValidationType.swift */, + ); + name = Core; + sourceTree = ""; + }; + 4D443E7921FBD163086C75A4E464D0B3 /* RxRelay */ = { + isa = PBXGroup; + children = ( + 9382A27EEA32D49627659BC72C56FCBF /* BehaviorRelay.swift */, + D9244D2668F560CE0CB0F0065186F8EB /* Observable+Bind.swift */, + 52F042037CA28D5A455E060DD097C638 /* PublishRelay.swift */, + 2868D931558DCC05627934B9EF6362E6 /* ReplayRelay.swift */, + ECBD12025121C746DDEB9B44E608E3E6 /* Utils.swift */, + 34329BC0E5C3F008BA4775286EF55C4E /* Support Files */, + ); + path = RxRelay; + sourceTree = ""; + }; + 6648C46CB637AC25933390CFA01B6E44 /* Alamofire */ = { + isa = PBXGroup; + children = ( + 443CA8C627022D8C1934F8F42533236E /* AFError.swift */, + 220B3F8A303994576980CB9C15199150 /* Alamofire.swift */, + A3F6B5834C04BE54692EFEF14936348F /* AlamofireExtended.swift */, + DB9D0DFFB1AA39DDF8B49325F07BEBD1 /* AuthenticationInterceptor.swift */, + 54C7D8C91C6BD127E758FD153F5CAE2A /* CachedResponseHandler.swift */, + 88195126F4E96A3774802B0BA8877C77 /* Combine.swift */, + 4B2092F7A452FCAC892734476E6676E3 /* Concurrency.swift */, + 7E97E1D4DF8BFA3FE2C603D6B934D9D2 /* DispatchQueue+Alamofire.swift */, + 2D85DF2E1C33DB9B470D4EFFB7F4A1FC /* EventMonitor.swift */, + F0933F5FD3BA39AA382ECC963D6550B8 /* HTTPHeaders.swift */, + 6E269149DE9BA1B81C3504720A668420 /* HTTPMethod.swift */, + 215B8518AD4396707F88E578B313121F /* MultipartFormData.swift */, + 7CFEE4BC9AEF52579A20AF4717B3205C /* MultipartUpload.swift */, + 4917FB9D005872281B22F006F7001E9E /* NetworkReachabilityManager.swift */, + 05C2B32ED7987DD94725453C00328CE3 /* Notifications.swift */, + F63084A32C04D39192F17E5B2082033C /* OperationQueue+Alamofire.swift */, + CA8EB7DF526B4C2F17EB0BBE0F8760CC /* ParameterEncoder.swift */, + 2E78E508B94164D9227009C03D41986A /* ParameterEncoding.swift */, + 518597BD67B90E044EDCA15142FA2D54 /* Protected.swift */, + C0F94D368DE622488019CFFA18E34262 /* RedirectHandler.swift */, + C6D030CA131DAC625D4D9FDC5FD000E3 /* Request.swift */, + 516DBB0CADC2C6DBC5C12C20E9C7DFE4 /* RequestCompression.swift */, + 87AAF208F89B5776787B00ED7C4139D0 /* RequestInterceptor.swift */, + 44142825DF6D5162BCAC2FEFBF148BED /* RequestTaskMap.swift */, + CCB3459EBA17D69CB52198314FF7186C /* Response.swift */, + 9BFCC48A5DBF6A66F64E5ACE27854985 /* ResponseSerialization.swift */, + A0CB4A2B49E071E7012FEE7D28B8B467 /* Result+Alamofire.swift */, + 2A271DE0F470E6D6B4CF963A21854DEA /* RetryPolicy.swift */, + CCF0B72B35A6BCD96CBC1A3F6A6ED7B4 /* ServerTrustEvaluation.swift */, + 5254AF871AE5D79369426F1E9DFD4BFB /* Session.swift */, + E597FA331BDE835D4356BA91AC2EE05B /* SessionDelegate.swift */, + 6FE1258734CD0D5DE5C0C1545F096DAF /* StringEncoding+Alamofire.swift */, + DF65591BAA77BD5923D4083691EB5F0F /* URLConvertible+URLRequestConvertible.swift */, + 0FE18AD6C78E4D9C1E9EDB83E8763861 /* URLEncodedFormEncoder.swift */, + C4E611CCA47B1AFF3C1E57F8C2965B0C /* URLRequest+Alamofire.swift */, + ABF8C3D769C418801ABB2905159428B8 /* URLSessionConfiguration+Alamofire.swift */, + 383C3B11450462CA845076D5A31455A7 /* Validation.swift */, + 0ACF7A29FEB8DF4457DE6C976823731D /* Support Files */, + ); + path = Alamofire; + sourceTree = ""; + }; + 6BD347D3775B5ECCFFF3B7129D5BF1AE /* Support Files */ = { + isa = PBXGroup; + children = ( + CE1FB66738FC326A45E13D4A2F9039DC /* Reusable.modulemap */, + D205770569FAE2C81B52F154322D2563 /* Reusable-dummy.m */, + 41FE8293A6AF96E011A77F789193CD99 /* Reusable-Info.plist */, + 017CB031F08EF999D20BCEE492444892 /* Reusable-prefix.pch */, + CBFCE48108EA5B7391D309F207FA3E5A /* Reusable-umbrella.h */, + 03B41EBBD593C680744DAD960E245F91 /* Reusable.debug.xcconfig */, + C71988E85D3858110A6CEEF81B0B0CBE /* Reusable.release.xcconfig */, + ); + name = "Support Files"; + path = "../Target Support Files/Reusable"; + sourceTree = ""; + }; + 6D3627A4475DCC07A111B46FA8742810 /* Support Files */ = { + isa = PBXGroup; + children = ( + B725764E388DB9D2EF9D7D8EA6A0B1D3 /* MBProgressHUD.modulemap */, + C4166DF44E4B7DCF69575608F281517C /* MBProgressHUD-dummy.m */, + 983A6B351A04E8A201ECBA3C765A4B43 /* MBProgressHUD-Info.plist */, + 107549C133EE5267BA358393A90EF059 /* MBProgressHUD-prefix.pch */, + C3ABFDAE24AACD8E1EEE68793DE9803B /* MBProgressHUD-umbrella.h */, + 80E741ED9F7CB291A4CA8068F3FE04F2 /* MBProgressHUD.debug.xcconfig */, + FA92B06C831BE63EC9C993A1217E090D /* MBProgressHUD.release.xcconfig */, + ); + name = "Support Files"; + path = "../Target Support Files/MBProgressHUD"; + sourceTree = ""; + }; + 6F0835F9A2B10364B21DAD66EE1AED12 /* Reusable */ = { + isa = PBXGroup; + children = ( + A6010E4A5136F149C6DDE0539B4C6D95 /* Storyboard */, + 6BD347D3775B5ECCFFF3B7129D5BF1AE /* Support Files */, + B072DDD8A4BB384ABB1652090ADD8257 /* View */, + ); + path = Reusable; + sourceTree = ""; + }; + 84CB1D96BB3C8A96122B486161B750D5 /* Support Files */ = { + isa = PBXGroup; + children = ( + 5264BE1108D40329A508922AD0245365 /* HandyJSON.modulemap */, + 2C97BCD706DEE807EF3868F37A8ECCA1 /* HandyJSON-dummy.m */, + FBA54F39E869CCC3D040A46FA1737ED1 /* HandyJSON-Info.plist */, + 3B6E3E1498C003DB8CBD3643CD2AD2A6 /* HandyJSON-prefix.pch */, + E6EA7642AC0A935140B695C8DE1F91B1 /* HandyJSON-umbrella.h */, + 45E1E6ADB66DF96376E308D63F6B71D8 /* HandyJSON.debug.xcconfig */, + 1A9CF67CD4186CDC93B9439A7C72E036 /* HandyJSON.release.xcconfig */, + ); + name = "Support Files"; + path = "../Target Support Files/HandyJSON"; + sourceTree = ""; + }; + 8AACD370BEA282A3E8F4B1A30CBEE7BB /* Kingfisher */ = { + isa = PBXGroup; + children = ( + DB2C7BCF3EA896AC2BAD9CAD275BB460 /* AnimatedImageView.swift */, + 7572072A13A12227DE23BD58E99E7B41 /* AuthenticationChallengeResponsable.swift */, + 420DDEA65A2C63C6CA966D994E696D54 /* AVAssetImageDataProvider.swift */, + 1828EE850F0785BEBBEEB6381406536B /* Box.swift */, + 27459C8DF241339CDE5DD49FB1C25C8D /* CacheSerializer.swift */, + 75C831D0F3B6ECF5593AC202900F9B4F /* CallbackQueue.swift */, + C963DD2091D258FD11B459ACF20AF09A /* CPListItem+Kingfisher.swift */, + F9F013D28FC8ECBAF33DF99272DEC729 /* Delegate.swift */, + 8CDAEEA9FC477033FF5344F6CBE85CB2 /* DiskStorage.swift */, + 501CF92DCF5E2F25FE033F445BAA7A3A /* ExtensionHelpers.swift */, + 590615ED68A80BD1EF1DBF8F477F1B12 /* Filter.swift */, + FBDDA0D117F42E4FE226978800527457 /* FormatIndicatedCacheSerializer.swift */, + 9D73294AC7AF8EC9156DBA588DC9CE3D /* GIFAnimatedImage.swift */, + 70B306F880D3FA0554EF152D25916163 /* GraphicsContext.swift */, + 4DB0FE9FA272BBF1E359F79E2FE6B469 /* Image.swift */, + 79AB56ECFE81336CFFB52ADF927D8A7C /* ImageBinder.swift */, + 48252905C19EDB8DCAE2BE4BE7B68A85 /* ImageCache.swift */, + 0F964475871A4284F485DC930EB7FE0D /* ImageContext.swift */, + FB5DD901158FEFCA27ADE24D3A8E12FA /* ImageDataProcessor.swift */, + 005B0AA170372B033FC09D4E58FBAC9A /* ImageDataProvider.swift */, + 3C27EB2E04E045DFB79BE6AAA63A7EA2 /* ImageDownloader.swift */, + A296A412119288A86A5336E1C181E566 /* ImageDownloaderDelegate.swift */, + 91B4895A5E4828D58DFE315830059A72 /* ImageDrawing.swift */, + 7965E10A5058A7FDC743C628B6A209E4 /* ImageFormat.swift */, + DFBC5B2993997B725D364216FE7C3DF6 /* ImageModifier.swift */, + DCD283B934B4346CF12CEB62458A829D /* ImagePrefetcher.swift */, + FE2C700E88155AD2A39178D87B6644F5 /* ImageProcessor.swift */, + F329A03B4D1A8412BFD9F49535A2D291 /* ImageProgressive.swift */, + 2686E2F30E71D302C7EC46BF9AC726BE /* ImageTransition.swift */, + B35DC4FCD2EEF00AF73453F41872FF54 /* ImageView+Kingfisher.swift */, + 31BB5D3806E36F2811C5F7E9C7E0A00B /* Indicator.swift */, + 105DC924B68D07DCCA5F7BBD13103F15 /* KF.swift */, + A3340A012067886751EC877DE2A085FB /* KFAnimatedImage.swift */, + 9BAC09FA3F4AA34E2FD9045902942CE8 /* KFImage.swift */, + BE3D4635725BE29F6866D4B1964447A8 /* KFImageOptions.swift */, + 9DBF24BFBDEDD9C43BB60E43954D93C9 /* KFImageProtocol.swift */, + 11D7747447E5C511F9D8307F10E5168C /* KFImageRenderer.swift */, + C8B66F25D7F18C08892764CAD99E025D /* KFOptionsSetter.swift */, + 6E0F4988883481C19FAFF403697872DD /* Kingfisher.swift */, + CD4F149DBFD18F4A20A4320599D8CC19 /* KingfisherError.swift */, + 0292DCF642DD7EA1D1116B8623A8C599 /* KingfisherManager.swift */, + B43B6B9F0AC1A3B441577C4268863C3B /* KingfisherOptionsInfo.swift */, + 5DE5F4C9535F3ECFDE536AF77F583A78 /* MemoryStorage.swift */, + D93E22C14E699039A509F617FA39695B /* NSButton+Kingfisher.swift */, + F098DF51276D641070E6E01539D4B986 /* NSTextAttachment+Kingfisher.swift */, + 8472FB3724242C375626B5D19B004A36 /* Placeholder.swift */, + 739CDDE742C44BA839AD3DA536BDD57F /* RedirectHandler.swift */, + F9E3641046F777BA820AB2055AA51792 /* RequestModifier.swift */, + 94B8075CA095FDBA9AE87F86A21B0C30 /* Resource.swift */, + 95AF3FFD5DA43879FFD1FEF529C36275 /* Result.swift */, + 553E529F93F751DF0489E958694F11D8 /* RetryStrategy.swift */, + 4A9962A1E3D931E363F3C4D48522361B /* Runtime.swift */, + B2958A0E6033229331C79C4CD02FB145 /* SessionDataTask.swift */, + 5A549727CCD5C1657E53A8BAE5E58145 /* SessionDelegate.swift */, + 840E59B83C8C092BD38138A7D44A473E /* SizeExtensions.swift */, + 1BC8BE591A383FB0802A1161825B227F /* Source.swift */, + 2AE83D49E82297DF5D76F3A85D2DBEF1 /* Storage.swift */, + 0DD70DADAD30E2F4D27E3DD7A1EAC006 /* String+MD5.swift */, + 17D5BC96435F4DD211BCF227E506B92E /* TVMonogramView+Kingfisher.swift */, + A8D08D8E537F6EC253D8EBE79FC6542A /* UIButton+Kingfisher.swift */, + 2AEBE0DF14984ECC53D005ED92A73024 /* WKInterfaceImage+Kingfisher.swift */, + 0F9BCF6B6B1C3846EB3915D29498BD08 /* Resources */, + B94B0C6561164D381BC2F291DAC4F7BA /* Support Files */, + ); + path = Kingfisher; + sourceTree = ""; + }; + 8C243E4EC8CAF1BD18D04A085617A090 /* RxSwift */ = { + isa = PBXGroup; + children = ( + A91E7B0C850AC3EB49D57C2F5AC657BA /* AddRef.swift */, + ED35C12CB343C92F81259E4F33B299B5 /* Amb.swift */, + 30F3EE79D4A82DDA5FBAD0C2C8D6753A /* AnonymousDisposable.swift */, + BBE5FECC28B966616BA85A7C62F7FA40 /* AnonymousObserver.swift */, + 692E3C85CC1223B95D6A9605B661FA68 /* AnyObserver.swift */, + E08F77D6D513C32F418E1FC2AE7AD85A /* AsMaybe.swift */, + 21E4BE15EF64CDD45908BF2A541F2A66 /* AsSingle.swift */, + 5318EE8340C75CB1C311FB0C5C0035CE /* AsyncLock.swift */, + 46CE5C282594AAB0BC74E3DE1A773F2B /* AsyncSubject.swift */, + 0A998D586FC04E7F45D15D9E8E02E70B /* AtomicInt.swift */, + FEDFCFC90E99F4AD01D5647DF4CB5FB4 /* Bag.swift */, + 402F4EF7983996E485AA8AD6E305B46D /* Bag+Rx.swift */, + C689E3BB4983E6D479A62F1211506E90 /* BehaviorSubject.swift */, + 765D531DF5050A417659B07DDB7A51B1 /* BinaryDisposable.swift */, + CF107C4AC5643080B30C4DC1AD3CA088 /* Binder.swift */, + 1E088C67BD72950301BB89F16F31469A /* BooleanDisposable.swift */, + F2D487B9F0F6B5545D5A1715E39B9BCA /* Buffer.swift */, + B0D85CAD20866F6833A22BDA6668ECB1 /* Cancelable.swift */, + 4B40027C27CE4E459A38C1D87C106545 /* Catch.swift */, + 02F4A94A543B7090414D2D11E1C5F3A2 /* CombineLatest.swift */, + DA05AFE5E1E48A41436B4A70147E660C /* CombineLatest+arity.swift */, + 917C955DCF6B29BABB9B623BE0758691 /* CombineLatest+Collection.swift */, + 81B176F830BCA2FC63200329DE776384 /* CompactMap.swift */, + DFDBA24A5039ED5E5456D2E8FC495205 /* Completable.swift */, + A2D58F2F6C7CC4D368CE0D57F40CD27B /* Completable+AndThen.swift */, + 7867FF4FE4FF1D6345613A45E339635D /* CompositeDisposable.swift */, + A54253F4F6876CCFC845DA722D6C8CE8 /* Concat.swift */, + D38B8AB8BAF2B28F16F577931098B969 /* ConcurrentDispatchQueueScheduler.swift */, + 728E3C167CE3ED7F8123F48D5A84771E /* ConcurrentMainScheduler.swift */, + FA5485B4C3E504F337F2AD065ABAEF76 /* ConnectableObservableType.swift */, + 6F85D9716CFD2A169AB2FC3954F8916B /* Create.swift */, + 18C45484AE9F211603671E126686D88F /* CurrentThreadScheduler.swift */, + 5EC0523BF8CA0D3FF2934609B979DBED /* Date+Dispatch.swift */, + 2DAD506D24AC12D48E8C572B4C5B8674 /* Debounce.swift */, + 99155CE8434026F99E70418FAEF41EEA /* Debug.swift */, + 08095C11257E23D25E208304881B3A90 /* Decode.swift */, + C426FFC0480ABDFDDC457EE5FE191E5E /* DefaultIfEmpty.swift */, + AB501C06BD3310ADAA40217FA862D851 /* Deferred.swift */, + 445854BBB677492BEB10430E549CF31D /* Delay.swift */, + 3F6E79FDA2485804EB4B20DAEDA26366 /* DelaySubscription.swift */, + AFF9C7F95915AA09C2220E7711A63B74 /* Dematerialize.swift */, + 0BBE9868390C0ACA219A59A1F61C4F09 /* DispatchQueue+Extensions.swift */, + 3956A13898BA7AE3AD6AED0406907F52 /* DispatchQueueConfiguration.swift */, + 7AD5F75086AF715FAD56BDDA5876EA2B /* Disposable.swift */, + 56D520627040A3B6D58DF009393C985E /* Disposables.swift */, + D5405426B1D820B97554FFA85005A6A7 /* DisposeBag.swift */, + 1CCA1BCCD3C2E9007F3F56C9E8AC6398 /* DisposeBase.swift */, + CFD438AE9A13700F3A27158491EDF9CD /* DistinctUntilChanged.swift */, + AEEBA06C08ECDC8AA5CCA71C013759FA /* Do.swift */, + EC50DBE03FF22FAAF1D4BE41AAFB9A8A /* ElementAt.swift */, + 25CF572152EDEF89E43D914242F08BE0 /* Empty.swift */, + 2A36E5193632E241668CBF9B7B2CB7D5 /* Enumerated.swift */, + 9D5553E70A731CAE3CC0589428DF9FFA /* Error.swift */, + 1E818ED04F94422CB5C8B2554572826C /* Errors.swift */, + 1C7BAB5978403A78EBF174C01FF8C71E /* Event.swift */, + 5C17122D9169B76E0AB08E43B215523C /* Filter.swift */, + ED443DD7A5B81CF799FF1A9B14CA60C8 /* First.swift */, + 591861115B56C34EE893545E4F44ECE0 /* Generate.swift */, + 22B9AC50C1A66CFB12BF81596173CD39 /* GroupBy.swift */, + 8770E250C6062015540FA168FD612B2B /* GroupedObservable.swift */, + 086CC48512270C1C4BB20AE3B7A179F9 /* HistoricalScheduler.swift */, + 913295D3902A731E0FEF7891F2DFFD66 /* HistoricalSchedulerTimeConverter.swift */, + B00EB68258A05718515A533A9F917D11 /* ImmediateSchedulerType.swift */, + A6A3220A212C0BC4ABE0058268E8FAA6 /* Infallible.swift */, + 7D131FE518C0CECBEA619AA8A5490197 /* Infallible+CombineLatest+arity.swift */, + E4AD07036A83707DD229318C03B6CE81 /* Infallible+Concurrency.swift */, + 94CA369E5A9E7E47E7DBCAAD6F63D296 /* Infallible+Create.swift */, + 8FC8131B3030B737FB4BE9DBCBAB4C9E /* Infallible+Operators.swift */, + 960152331447046185D9888B4AED166C /* Infallible+Zip+arity.swift */, + E20F55B135E3C24173DF453318747D59 /* InfiniteSequence.swift */, + 5DC90B70DB4293C27D4B5733F05EC3CC /* InvocableScheduledItem.swift */, + C4E6211C49C3ADB158FA16A1751D5E34 /* InvocableType.swift */, + B4C8D32181C1DD0673EF71FC021C399D /* Just.swift */, + 259AF82D05F6D3AF5D26FB0CCF6354E5 /* Lock.swift */, + FBD96A9F6932FA01432273082AB94D9C /* LockOwnerType.swift */, + 66BCA8A6AE43B359068161172075AD29 /* MainScheduler.swift */, + E4E95E8B077E462C80766715ADCA4CF0 /* Map.swift */, + 75FFF56047C4C60A6E7F1E572172AC93 /* Materialize.swift */, + 6673F5D40ED1C9BF12C1C9864D29C16B /* Maybe.swift */, + F45DCBE864FA17C68B639547AEB93B03 /* Merge.swift */, + AD3FD403D8E30A8001D1F494B36EFA49 /* Multicast.swift */, + 4F5800717EBB5879045C06670DA4C8AC /* Never.swift */, + 5BBD217833E818303FFD2DD7E1DD6817 /* NopDisposable.swift */, + 4529DBA9667227E1B099ADC681AB5850 /* Observable.swift */, + 10DF3559568462A634A6F7EE6FFBCA00 /* Observable+Concurrency.swift */, + A2FB155675AB0F9CD4391CE05510152D /* ObservableConvertibleType.swift */, + 10D600B6F7169DFD7E81912260743F3F /* ObservableConvertibleType+Infallible.swift */, + 82EEBDF2AE2F00B7933D6A5DF8FDF0AD /* ObservableType.swift */, + CD8E57ECFD6B142763B5C63323162920 /* ObservableType+Extensions.swift */, + 36683A54CDD175D2798404369B19387A /* ObservableType+PrimitiveSequence.swift */, + BC12D927E7A7FFE4391A073866062EF0 /* ObserveOn.swift */, + 207583CD61F84971AE55DE2ACF2B29A9 /* ObserverBase.swift */, + 2DAB2159DEB43FA519F6B8254AF5728E /* ObserverType.swift */, + C909B32972D2D22DB9AE521E98C47040 /* OperationQueueScheduler.swift */, + 1517F2B568C0846F286EF269D17902A5 /* Optional.swift */, + FA88BA483915DE8B6B9D5D7B9A4AAE90 /* Platform.Darwin.swift */, + 14F206D32E3EFDDDBDCA5B559448999B /* Platform.Linux.swift */, + 065A74676EEAD75E1F49A21AACEAF349 /* PrimitiveSequence.swift */, + 3AF54C9D06FA26EEFB4A6D8DDB4C6C83 /* PrimitiveSequence+Concurrency.swift */, + FC28EF831FDDD06091CC7AB0416845FC /* PrimitiveSequence+Zip+arity.swift */, + 8DD8CAC74ECCE5DF13BE36C29354F6B3 /* PriorityQueue.swift */, + E1876E647F0F13D8AD9A41FED3B7C6C2 /* Producer.swift */, + 70933FA1D55CE70EA5A4110C98DEC09D /* PublishSubject.swift */, + 94C392D9062D4196B340E6F77067B6F2 /* Queue.swift */, + BF481B014D924D41F0FDE7089D3263B0 /* Range.swift */, + 98358BCC95E6655702825CEE45C0C8FA /* Reactive.swift */, + D88811C8F2904BE3EDD7B26CE505C673 /* RecursiveLock.swift */, + 09071625C0D4ED0715EBF9938CAB0C6B /* RecursiveScheduler.swift */, + C45FE00D96FB11A4BF6998884E30C879 /* Reduce.swift */, + 69C17E66AE494BF8C88740E1EDB36891 /* RefCountDisposable.swift */, + 1E14FBC686914E2AF7C4383BFAA062B5 /* Repeat.swift */, + 9895F4D070396F9D33D6C602E53C0D77 /* ReplaySubject.swift */, + 29305731B01CF8E4A32561061D6EA1AE /* RetryWhen.swift */, + 8C1E768C4764D3F7B03199D967453517 /* Rx.swift */, + DEA1B032D5AF107EC317CDAE847D3CE5 /* RxMutableBox.swift */, + 6BC184BD2886B5395146315871D4F629 /* Sample.swift */, + B3492495BDAA3EE808EBA7E27B444532 /* Scan.swift */, + 42F715AC86D9585FC5BB7F7C07DD7DAC /* ScheduledDisposable.swift */, + ED806FA43E5458BB64EB1B488B5B6772 /* ScheduledItem.swift */, + 92037C313E25E9C5B1ECD6B53CF18C6C /* ScheduledItemType.swift */, + E78DB89A84C09AD3FA55F3FEF697370C /* SchedulerServices+Emulation.swift */, + 69D940AC28230A45C640E32E10438178 /* SchedulerType.swift */, + E68CB21AF7E7B8C4BFF5A00B209D9666 /* Sequence.swift */, + 154835255F9916E0769C0D71A8A3267C /* SerialDispatchQueueScheduler.swift */, + 28E9D0CEE48F6310B3A68093744A1146 /* SerialDisposable.swift */, + 61ADA54F40A6900545707A222D69889B /* ShareReplayScope.swift */, + 4DB8E452090D235990597C3AB1BE8E11 /* Single.swift */, + F3DA46923ADA705C392069960BB60E9A /* SingleAssignmentDisposable.swift */, + 33055FA32252223B1AB3116721D6096B /* SingleAsync.swift */, + D389385F88DD239B71595D6B278BC5EA /* Sink.swift */, + 9D4D5FD14129673A9CDB7002DBABE33E /* Skip.swift */, + D6575A7C92CAA45BC7CAAB15672122A1 /* SkipUntil.swift */, + 4B32547DF2C9A9E64087A593AC3EE911 /* SkipWhile.swift */, + 3602398BB4B83B59240F9614C1DF5EA4 /* StartWith.swift */, + 17D7B878065E9387C23C43CFACC3A867 /* SubjectType.swift */, + 79A0A26C9F36ABCC4EB50D474EC8DA4D /* SubscribeOn.swift */, + 4E71EDCC1B6F580E01E54903C36737EB /* SubscriptionDisposable.swift */, + 239DDF3AEECE822C3281639FD6546369 /* SwiftSupport.swift */, + 0487859709F230146392D21D1B192DC0 /* Switch.swift */, + E83D56D118A8CD729AB9F4DD106214B6 /* SwitchIfEmpty.swift */, + 537DF163C75C79892595630BC3CBA09F /* SynchronizedDisposeType.swift */, + 37706A10928DD59317F2AABB995786F0 /* SynchronizedOnType.swift */, + FA5D56DE5D48CA926F73DF626BACA99D /* SynchronizedUnsubscribeType.swift */, + 64576C6FC886A417A4683A9816DA5D4F /* TailRecursiveSink.swift */, + B2301559B216DC943D96B6C3EA6187EE /* Take.swift */, + 0705C992AE1A7F2F2FF703DD1338C3F7 /* TakeLast.swift */, + 9BF394511EEFCC9854970C278A4EEFAB /* TakeWithPredicate.swift */, + AB1550C20B92B5D8CBB8484C4660BE90 /* Throttle.swift */, + 654DEBE109ACCEE862E7F084EE7ED13C /* Timeout.swift */, + 7C161168F47BE22BA1D8157F0A37F4C2 /* Timer.swift */, + 9FE96E6FECBEF720CD9DD849F12E6D61 /* ToArray.swift */, + 7FA5EF7CC85AF8D7A9C4307E6247274B /* Using.swift */, + 634E359FC76F57C6E032A112422B8130 /* VirtualTimeConverterType.swift */, + DA54EB4CF78AC3516E9E65506DE207FB /* VirtualTimeScheduler.swift */, + D247DB9583EC8A9EA2396FEEE9A0BEBC /* Window.swift */, + A4E676ABA267DB49404DD1A3CCB33F17 /* WithLatestFrom.swift */, + 95509362358E1B4F96EED27DC01B1C24 /* WithUnretained.swift */, + 947FCB4637962EF20818268291E26E85 /* Zip.swift */, + DCE9ED04C9F6410492A87A2B8BC43451 /* Zip+arity.swift */, + CC92DDE2881965C74B23F6A422B435B3 /* Zip+Collection.swift */, + 9D5C3A856749DB28C0E46B808023828B /* Support Files */, + ); + path = RxSwift; + sourceTree = ""; + }; + 9D5C3A856749DB28C0E46B808023828B /* Support Files */ = { + isa = PBXGroup; + children = ( + 2CB6A627D9F759981FF9B741C57D0E1D /* RxSwift.modulemap */, + A612F6D773EF0336F7EEA1B142F733F1 /* RxSwift-dummy.m */, + 2A1E8C07BD53C5A3B5242F95A74991F9 /* RxSwift-Info.plist */, + 6D060D2BB92C878FBC76760B8F99D911 /* RxSwift-prefix.pch */, + F1A40D020BF4C65249FEA2EDF53B89F5 /* RxSwift-umbrella.h */, + 537B39F9D626350F9BD4A28C6DF455B6 /* RxSwift.debug.xcconfig */, + 19B712EE8F117D2EC35F9A295028959B /* RxSwift.release.xcconfig */, + ); + name = "Support Files"; + path = "../Target Support Files/RxSwift"; + sourceTree = ""; + }; + A6010E4A5136F149C6DDE0539B4C6D95 /* Storyboard */ = { + isa = PBXGroup; + children = ( + 0F2F174FA9B884D41464BD84265273E9 /* StoryboardBased.swift */, + AB91063BFA0B85155CE39C26F80044C5 /* StoryboardSceneBased.swift */, + ); + name = Storyboard; + sourceTree = ""; + }; + AA82EC4AF35A3C8A786A5503BE530EF2 /* Pods-yinmeng-ios */ = { + isa = PBXGroup; + children = ( + 39D0F77A76D1B9C8043ACA2A518B4709 /* Pods-yinmeng-ios.modulemap */, + 236F15BC43D0758FE90E506F41ABBD36 /* Pods-yinmeng-ios-acknowledgements.markdown */, + AB870D83096A800ECB5E56E7E76FC933 /* Pods-yinmeng-ios-acknowledgements.plist */, + 1BBD7BC93FC22FBD9C79EAB4AC435A7E /* Pods-yinmeng-ios-dummy.m */, + 1A5104776E2AD589EF6B4A0B49E9EB80 /* Pods-yinmeng-ios-frameworks.sh */, + E3A080F230A46B8C0F73FF8AA678A95A /* Pods-yinmeng-ios-Info.plist */, + 9B3AF9BB0F7EB5558031DD21AD2F86CC /* Pods-yinmeng-ios-umbrella.h */, + C7CE4D7E07321EBA8053DBEF4867408A /* Pods-yinmeng-ios.debug.xcconfig */, + 6C4BAD710FAA4AE5F73353998A04A650 /* Pods-yinmeng-ios.release.xcconfig */, + ); + name = "Pods-yinmeng-ios"; + path = "Target Support Files/Pods-yinmeng-ios"; + sourceTree = ""; + }; + B072DDD8A4BB384ABB1652090ADD8257 /* View */ = { + isa = PBXGroup; + children = ( + 2B48BE2A6404DB81C7324A3CE9177FCA /* NibLoadable.swift */, + 0A4ABF00795A4D24AA39AE0648DAAFF8 /* NibOwnerLoadable.swift */, + 0D924D0F2142E1C7FED799E98F5B5A2C /* Reusable.swift */, + 016AA1ECBFE5BEF6D881059F1B2DD9BC /* UICollectionView+Reusable.swift */, + 95F799040C1A70E136CAE7A41476545C /* UITableView+Reusable.swift */, + ); + name = View; + sourceTree = ""; + }; + B94B0C6561164D381BC2F291DAC4F7BA /* Support Files */ = { + isa = PBXGroup; + children = ( + 3DF97E8D675384337BA22ED93D008910 /* Kingfisher.modulemap */, + B4FAC3BE27572FE3185D20211224395A /* Kingfisher-dummy.m */, + EB54968F135513C686F7D4461CD71248 /* Kingfisher-Info.plist */, + 20B0FF4D5789DB2CC388939C196538A9 /* Kingfisher-prefix.pch */, + 4FE70A655C85EA7C91C24E5B3457D9B0 /* Kingfisher-umbrella.h */, + 43A9212FF806B13E885C7019E059D160 /* Kingfisher.debug.xcconfig */, + 93BD071E578B69235CCADBFBE9FBAA1B /* Kingfisher.release.xcconfig */, + 924E596CD9FDC9E228B02FD51DF48901 /* ResourceBundle-Kingfisher-Kingfisher-Info.plist */, + ); + name = "Support Files"; + path = "../Target Support Files/Kingfisher"; + sourceTree = ""; + }; + BDB006AD0630C93386D9F397A4A6E3E8 /* SnapKit */ = { + isa = PBXGroup; + children = ( + 8FF51600836B6E9C1393D1B32AE0409F /* Constraint.swift */, + 8B3F60740202D2919EAB02088A75C6DE /* ConstraintAttributes.swift */, + D6D6C3517EAD559475BB89B3A07F826D /* ConstraintConfig.swift */, + E7B65070F724AC357CCEA7DBCA350373 /* ConstraintConstantTarget.swift */, + 64F516F56589A2470DFA0E30E85DBB80 /* ConstraintDescription.swift */, + 8A18BCB5C7FD8D506C4D66B8A1BE5B63 /* ConstraintDirectionalInsets.swift */, + CBB2733EB8602C8BA1DE249204349BBB /* ConstraintDirectionalInsetTarget.swift */, + B90F3E609D4D31B9CE6BA0937072B8DB /* ConstraintDSL.swift */, + EE92ADF7F5D694CD90670878273D0E22 /* ConstraintInsets.swift */, + 45FEC9077C3B5C14B02AB4E46F22E157 /* ConstraintInsetTarget.swift */, + FE77747AB7C6876DC80B43C5DCE4ABF0 /* ConstraintItem.swift */, + 594A5F9AE55C8EAD11AFE74EE0DAC3C7 /* ConstraintLayoutGuide.swift */, + 96EB1FBABEA3906F0EF58EE47E45A83B /* ConstraintLayoutGuide+Extensions.swift */, + 6EBE2A5988B01C477AFF1CE3128EE8AF /* ConstraintLayoutGuideDSL.swift */, + E60F8ED3C26A4DFE0400C21FB2BE072B /* ConstraintLayoutSupport.swift */, + D9278F439B7C4235C53C200B17F84E46 /* ConstraintLayoutSupportDSL.swift */, + A35CA8960849EFAC715838CF15CFD05D /* ConstraintMaker.swift */, + AA4C20251B8F62BF6DC2548854609658 /* ConstraintMakerEditable.swift */, + 7CDE2F9CE2B04EA6687EE664E9B1F447 /* ConstraintMakerExtendable.swift */, + 0E6A6730169419E002FF07C1AE880F77 /* ConstraintMakerFinalizable.swift */, + E0231B13AFD942D7715BD4A70ABFE808 /* ConstraintMakerPrioritizable.swift */, + 32639E8193F95CA5F554F746CA3F05AD /* ConstraintMakerRelatable.swift */, + 763C57CB99AAF692D5804D56D94FE7EA /* ConstraintMakerRelatable+Extensions.swift */, + ADE256164152BE966B102C5F104FC06F /* ConstraintMultiplierTarget.swift */, + 1DCDE799B9543F90237D7DA862252A2B /* ConstraintOffsetTarget.swift */, + 834ED77A734859A8A9236980263E4AF4 /* ConstraintPriority.swift */, + A52935DC312F87728290A3ACA2167BCD /* ConstraintPriorityTarget.swift */, + C019E68F4B2DE55C5FD2493950035664 /* ConstraintRelatableTarget.swift */, + F52EC1967CD22048EB37327070C47EB5 /* ConstraintRelation.swift */, + 0D0D830BAD1F66163C68EB9A1BA9E147 /* ConstraintView.swift */, + FAC78FA49D7FB72A1D9081306F499298 /* ConstraintView+Extensions.swift */, + D5773666DA885BF217F31523BE08FD6B /* ConstraintViewDSL.swift */, + 8CDDAB158F06801DD368BFA93A07800C /* Debugging.swift */, + A6785DD60F3F01E17A54F423E8397E23 /* LayoutConstraint.swift */, + 97360AE19AF07AC87B391E1E0C708F18 /* LayoutConstraintItem.swift */, + 1EF2CDD729DADF5969E617BB9AD37B87 /* Typealiases.swift */, + EF820E238AB6C626388D71E7F83DD362 /* UILayoutSupport+Extensions.swift */, + 087868B262FF2BC66129825C09A683E4 /* Support Files */, + ); + path = SnapKit; + sourceTree = ""; + }; + C08390ED8A4F067D1F1476DD6F94AEFD /* Moya */ = { + isa = PBXGroup; + children = ( + 4B1B230A86A5086852705822097E9BDB /* Core */, + E07F044EFF8C1A668518642530859393 /* Support Files */, + ); + path = Moya; + sourceTree = ""; + }; + CD7CD1D695F30348342B62DC3DAD63F0 /* iOS */ = { + isa = PBXGroup; + children = ( + D1336AFDB9F472B9E17B6861880F66FA /* Accelerate.framework */, + 6D74FF06CA5AE8F2F5D48301BE439D32 /* CFNetwork.framework */, + 7160612C75B8C873D77B5AEDED76632B /* CoreGraphics.framework */, + 6A1970A14C2672638850C555C17ADE89 /* Foundation.framework */, + FB540682DA51451BDAD851F89E558DD5 /* QuartzCore.framework */, + 3397E4A82849848801375ABF4E7B4080 /* UIKit.framework */, + ); + name = iOS; + sourceTree = ""; + }; + CF1408CF629C7361332E53B88F7BD30C = { + isa = PBXGroup; + children = ( + 9D940727FF8FB9C785EB98E56350EF41 /* Podfile */, + D68CA58901FBF589D75F5E40F1EAF5BA /* Frameworks */, + 3FB04A789BFFEAF480028A2C5599933C /* Pods */, + 4ACE8263887E88BE1B13DCD869DFFCAF /* Products */, + 208D83938308FFB539726DDAF4BDAAC5 /* Targets Support Files */, + ); + sourceTree = ""; + }; + D68CA58901FBF589D75F5E40F1EAF5BA /* Frameworks */ = { + isa = PBXGroup; + children = ( + CD7CD1D695F30348342B62DC3DAD63F0 /* iOS */, + ); + name = Frameworks; + sourceTree = ""; + }; + E07F044EFF8C1A668518642530859393 /* Support Files */ = { + isa = PBXGroup; + children = ( + 57C844D869CA97E3BCD995BAE39B0811 /* Moya.modulemap */, + 2CCCFEF676D5297ACAAB23C1A5CB7CAE /* Moya-dummy.m */, + 43090D0C397209BB21ADF13605474623 /* Moya-Info.plist */, + 013009926D6AF27C596929D48AB266B6 /* Moya-prefix.pch */, + 126D7923B95B1B893763329F065ECC1C /* Moya-umbrella.h */, + E743F2C861099DDED46F43D21958AD4E /* Moya.debug.xcconfig */, + 649D2F79A4B50006D2A9D93E21022944 /* Moya.release.xcconfig */, + ); + name = "Support Files"; + path = "../Target Support Files/Moya"; + sourceTree = ""; + }; + E82B7085CA7098C59B6758A4756704C2 /* RxCocoa */ = { + isa = PBXGroup; + children = ( + 71A22E298D1E26A25192B7D79CB9C7BE /* _RX.h */, + 0D5B6D4F9F8CF76D040623D82B12D15E /* _RX.m */, + AAC31C95D09575257C31EB192272C7C2 /* _RXDelegateProxy.h */, + CF309802F2CAB75940F49AD77E8DFA05 /* _RXDelegateProxy.m */, + 720BE3DE6F24DCF57D71D73928C99C2B /* _RXKVOObserver.h */, + 3B45D252945E879A3B88C8989E5C2CC6 /* _RXKVOObserver.m */, + 35651FD3900CCCFFCDA6DD8ECE470B93 /* _RXObjCRuntime.h */, + A208FBE87421B2ABC0142F6A07D0B553 /* _RXObjCRuntime.m */, + DDB4D4AEF2A47181ABD692BE53C6DF1A /* Bag.swift */, + 48BEA0546BD26740F65A619717216925 /* BehaviorRelay+Driver.swift */, + 9541ABA1A2C54DE7EED55370247C46AA /* ControlEvent.swift */, + 97E745BB2E59AE041727B826B1E61BBB /* ControlEvent+Driver.swift */, + 9A2C43D00EDD3B8E5B6D1AC17B1E48E1 /* ControlEvent+Signal.swift */, + 588185259F665B2270B61BC5EEEDB105 /* ControlProperty.swift */, + F7B5707C4DB109E219C5031257DCD1F3 /* ControlProperty+Driver.swift */, + EF5F5DC6C61E0C786AA3BA02874662A1 /* ControlTarget.swift */, + 33B4FAC947A0378CAAD60F6A6B4DBCC6 /* DelegateProxy.swift */, + 544D687E21BDD58B48D554A5709A7901 /* DelegateProxyType.swift */, + 24119F92E2DB0B0C6650DEA1131020F3 /* DispatchQueue+Extensions.swift */, + E02AEC6F043CC7E4CACFA5D1EFD6EB27 /* Driver.swift */, + 19B406112800825F5B01A0BBED47F0BE /* Driver+Subscription.swift */, + 394A07B9CD7A0E87C54639C7326B5B28 /* Infallible+Bind.swift */, + DEBFD271D48A85EF07F3B6731D534416 /* InfiniteSequence.swift */, + DFCC95E9F5590674CB559C0596A2DC4A /* ItemEvents.swift */, + E8A3665F113C176C699C4A60D6739452 /* KVORepresentable.swift */, + 8D0507B1E2AB4B8A447354D000FEF414 /* KVORepresentable+CoreGraphics.swift */, + 7B953B1CDFABA00A04E6AC9124999CF9 /* KVORepresentable+Swift.swift */, + C1706327EA78CAEFF1336CC5568AD36C /* NotificationCenter+Rx.swift */, + AC6F737678C4E112EBB6476E99F02B44 /* NSButton+Rx.swift */, + DCEC2DBF8E26969A4BB2B54F2B1EA8A7 /* NSControl+Rx.swift */, + 64FA3F6B350E532395A97AB96530BE97 /* NSObject+Rx.swift */, + D05C01883F0A989F4169EA75A319E4CE /* NSObject+Rx+KVORepresentable.swift */, + E8FC0222908D1595E407695DD27A15FB /* NSObject+Rx+RawRepresentable.swift */, + 7B6C73A34CCB4FCB54A17345BD0051FC /* NSSlider+Rx.swift */, + F3EF76F454F323E3B71A0221AFFC8238 /* NSTextField+Rx.swift */, + 932FF7024616D8D82633AB22546C7DC0 /* NSTextStorage+Rx.swift */, + 0CA26D23785504CD85C0BA05F5263AB7 /* NSTextView+Rx.swift */, + FE06975BE3E77F3DFD642DD868FE617D /* NSView+Rx.swift */, + 645BF6563AFCDBF6A94CF2E1A387FA8C /* Observable+Bind.swift */, + EFC734B57692B8F617FD03908D932F63 /* ObservableConvertibleType+Driver.swift */, + F035F0F1D2D858918B6C937E1F71A98E /* ObservableConvertibleType+SharedSequence.swift */, + EFD03F6EF61FF91A6224DD8CF8BF2FCE /* ObservableConvertibleType+Signal.swift */, + A69562BE3DD6D05DD80BAD1460F44C4C /* Platform.Darwin.swift */, + 06FAB48DA0C18A3EE1754D953DB58E96 /* Platform.Linux.swift */, + C33F711F76B40DF65DA404994ED241BA /* PriorityQueue.swift */, + A124A76CB3B2F5D7198358B2E123B564 /* PublishRelay+Signal.swift */, + 29CBD6F8B67F5629CFB1D1326F23E28A /* Queue.swift */, + FBD270BC6C902DDBA8971425BF78B4A3 /* RecursiveLock.swift */, + 057D6C489248FFA4166DD24D93435763 /* RxCocoa.h */, + 326857EAC596FAC2DD9D5071A5B96D15 /* RxCocoa.swift */, + A4DBD0A365804120DBE621B87A954E25 /* RxCocoaObjCRuntimeError+Extensions.swift */, + A69D2E9F349C5F6AC3EC7F70DB0CCFDD /* RxCocoaRuntime.h */, + 8D02F219043B80DB62FA686E85C09B35 /* RxCollectionViewDataSourcePrefetchingProxy.swift */, + 42D446B359AD540FA2AEFD87D7ABE15C /* RxCollectionViewDataSourceProxy.swift */, + 8898277C74B39B8C2709D3BDFF6C793E /* RxCollectionViewDataSourceType.swift */, + 90028E4B472E1FCD0B7A391D37BC0C80 /* RxCollectionViewDelegateProxy.swift */, + E52F3E93B1A3D47F523D83D8473237C0 /* RxCollectionViewReactiveArrayDataSource.swift */, + 304C3471BD45700A1BFEFC1877E24B5A /* RxNavigationControllerDelegateProxy.swift */, + 2E6CA143EB6F64C9E9AD81EF8A9D3820 /* RxPickerViewAdapter.swift */, + E3F3D140901AD39649AC074216CAC836 /* RxPickerViewDataSourceProxy.swift */, + DF2E2C729461BB0F5D730E63F64A5F23 /* RxPickerViewDataSourceType.swift */, + B4F8C603320BB82716CEBA31405BB25A /* RxPickerViewDelegateProxy.swift */, + 165629B479649391782C794AE7C8E435 /* RxScrollViewDelegateProxy.swift */, + 3F5105C63B26C8CD36ECD3E4D25A4DFC /* RxSearchBarDelegateProxy.swift */, + 192C6CC3B7F6F517C4D157448480ECF7 /* RxSearchControllerDelegateProxy.swift */, + 881FD56231A6918A0EAD0806FB1D9A18 /* RxTabBarControllerDelegateProxy.swift */, + 74F603E9DCC9F74E70AC2EEF9A832481 /* RxTabBarDelegateProxy.swift */, + 1FCF2D3324E392803C9EFBB38E7A9ABA /* RxTableViewDataSourcePrefetchingProxy.swift */, + 67C143D7E7508931CFD2E2398C7BA9F0 /* RxTableViewDataSourceProxy.swift */, + 26A2F37034623F4E9BF155F2042659EF /* RxTableViewDataSourceType.swift */, + 8807FF18BB93251158B72386A622E490 /* RxTableViewDelegateProxy.swift */, + EEB214E2E4C3D3FB6CA0C4109D2F0FF6 /* RxTableViewReactiveArrayDataSource.swift */, + C526294611337A8D4EF5C3D3D571C77B /* RxTarget.swift */, + E76B1466F3C89ABD081A805991109083 /* RxTextStorageDelegateProxy.swift */, + 29D71D26A754963F763183793E0737A6 /* RxTextViewDelegateProxy.swift */, + 4488B560629B5C88A5E9FF2ED9FCDFD5 /* RxWKNavigationDelegateProxy.swift */, + 495812E6EEB9BFC5FBAD933FB325C0BE /* SchedulerType+SharedSequence.swift */, + C32614C0F923CC34E7C2BE3F692976AB /* SectionedViewDataSourceType.swift */, + 2B46D1FBCE62A21E03DAB229F57AD114 /* SharedSequence.swift */, + 191A401108B388D3700F7B69157F58FA /* SharedSequence+Concurrency.swift */, + E520F3EC8458D3F1E6174E0EC460E79B /* SharedSequence+Operators.swift */, + C22601C0B2814C78512F594A7731DE19 /* SharedSequence+Operators+arity.swift */, + CF2909F5D4495CA4ADC352EEF99AA4EC /* Signal.swift */, + 95D551A418E6BD3AAE54051EE0A0129C /* Signal+Subscription.swift */, + F306E6A5D3D559D9E47C8FF351159D2B /* TextInput.swift */, + 55D10B797A89889598E86DF39D020451 /* UIActivityIndicatorView+Rx.swift */, + A4A885E79A8DF08471834BA9D0D31ED3 /* UIApplication+Rx.swift */, + F75DD06A2A169049C9A0D1E77A6D13EA /* UIBarButtonItem+Rx.swift */, + 3497648C5E7B80D2ABC218A50A6CA389 /* UIButton+Rx.swift */, + D37B24A95EEF2249678FBE363925D312 /* UICollectionView+Rx.swift */, + 4ED914EA5EE1E5DAC87E75CFEEEBE002 /* UIControl+Rx.swift */, + 8A9425DD88305B16CADE1573B70E7D7C /* UIDatePicker+Rx.swift */, + B089112AF8A786152A4CFA32042AA817 /* UIGestureRecognizer+Rx.swift */, + 1A5F64B79665DAAF7330A9B901B15EFF /* UINavigationController+Rx.swift */, + 96DB504A50F1E4FBCD16D5BC49EFCF0C /* UIPickerView+Rx.swift */, + 9FC9415FA1C1593D995CF4413F86119E /* UIRefreshControl+Rx.swift */, + A5C55ED5BE5E14115CFDB19FC0330C46 /* UIScrollView+Rx.swift */, + 0F1253A739AF193B8223BE13ABA2A2BE /* UISearchBar+Rx.swift */, + 7A6CCF2E51B64ED58E9F5F6BC18C4500 /* UISearchController+Rx.swift */, + 2B71FB79E7C0B7102E8EF89E2C326862 /* UISegmentedControl+Rx.swift */, + 160D2BDCA79733E1BBB01B00F9404132 /* UISlider+Rx.swift */, + CA138CAED2178679471A0C1994A53ADD /* UIStepper+Rx.swift */, + 8DCA321A43CEC56664AD41086F8B7141 /* UISwitch+Rx.swift */, + 74E7B0CB0BD4C32719550BAEE7471ABC /* UITabBar+Rx.swift */, + E727269035DBECA74CF6FA02E1B24B09 /* UITabBarController+Rx.swift */, + 9C6E055D8D9B83521DB2D0B74D91A032 /* UITableView+Rx.swift */, + BE8D91CD998AB1AE8E676FD3F36C8F2D /* UITextField+Rx.swift */, + 089F4ED85F7C9FD8E053CA99D41D3132 /* UITextView+Rx.swift */, + 69B3A5BB96CFA43786C0ACFCF6162F46 /* URLSession+Rx.swift */, + 8051259FDEC630E944D8CD2114B0226B /* WKWebView+Rx.swift */, + 295AFD80C44BCD5AE0CFE5ED66C0EF6D /* Support Files */, + ); + path = RxCocoa; + sourceTree = ""; + }; +/* End PBXGroup section */ + +/* Begin PBXHeadersBuildPhase section */ + 0C9ED7F80C58C162BDF0D2A96D8615F6 /* Headers */ = { + isa = PBXHeadersBuildPhase; + buildActionMask = 2147483647; + files = ( + 28B20C35F4E1B3DDE716C831B049ADBC /* _RX.h in Headers */, + 543824E1170EF49570C40DAE54604F21 /* _RXDelegateProxy.h in Headers */, + 4251CDB971A8B94270E34381974BC9F8 /* _RXKVOObserver.h in Headers */, + 69657DEC11BB7E4F9F5B6DE8E1148B3E /* _RXObjCRuntime.h in Headers */, + 9A151985A3D24023E8B2996BF3EBA2BB /* RxCocoa.h in Headers */, + 557AE7547352CEA86AEE5518CC1A503E /* RxCocoa-umbrella.h in Headers */, + 45F6BA1117D64D98B32E0C77670EF906 /* RxCocoaRuntime.h in Headers */, + ); + runOnlyForDeploymentPostprocessing = 0; + }; + 410D0F27EDB13938D025BB9DBD661EB4 /* Headers */ = { + isa = PBXHeadersBuildPhase; + buildActionMask = 2147483647; + files = ( + AB60B7775C160D5D62FBC93FAC8F90EC /* Moya-umbrella.h in Headers */, + ); + runOnlyForDeploymentPostprocessing = 0; + }; + 5D82C29ACD851E6EA219B34A73C961F5 /* Headers */ = { + isa = PBXHeadersBuildPhase; + buildActionMask = 2147483647; + files = ( + 67E941CADB3CDDEEDF8CE4EE4A4A05BB /* MBProgressHUD.h in Headers */, + 5BAC1EF86D0E57E44E404B2796993561 /* MBProgressHUD-umbrella.h in Headers */, + ); + runOnlyForDeploymentPostprocessing = 0; + }; + 5FA4790A32ECD84F2CEA55509107BD0A /* Headers */ = { + isa = PBXHeadersBuildPhase; + buildActionMask = 2147483647; + files = ( + A3E3AB7C765C21AE17B1E6EE6560040C /* SnapKit-umbrella.h in Headers */, + ); + runOnlyForDeploymentPostprocessing = 0; + }; + 6FC876053E92670778D608CA0478F728 /* Headers */ = { + isa = PBXHeadersBuildPhase; + buildActionMask = 2147483647; + files = ( + EEFF0A57765CB734CF01868904F56DA7 /* HandyJSON.h in Headers */, + C920144CE195D2198DAE63F2D976AADB /* HandyJSON-umbrella.h in Headers */, + ); + runOnlyForDeploymentPostprocessing = 0; + }; + 6FE53F6191854563DFA7CE2E0C3378E0 /* Headers */ = { + isa = PBXHeadersBuildPhase; + buildActionMask = 2147483647; + files = ( + E7C58133036040A730E4546D0C0DE87F /* Reusable-umbrella.h in Headers */, + ); + runOnlyForDeploymentPostprocessing = 0; + }; + 76797DC1949EF10E4CD36CF86C9A5F73 /* Headers */ = { + isa = PBXHeadersBuildPhase; + buildActionMask = 2147483647; + files = ( + CCBCFE35FEFAD9C1307334491148DA27 /* RxRelay-umbrella.h in Headers */, + ); + runOnlyForDeploymentPostprocessing = 0; + }; + 7BA941A73E8FBF5B0419B83592AA4F77 /* Headers */ = { + isa = PBXHeadersBuildPhase; + buildActionMask = 2147483647; + files = ( + B4ED29084E130F41F61D6E4B15DB3551 /* RxSwift-umbrella.h in Headers */, + ); + runOnlyForDeploymentPostprocessing = 0; + }; + 9F4F99D2A751CF26D6C10130E33EBBC8 /* Headers */ = { + isa = PBXHeadersBuildPhase; + buildActionMask = 2147483647; + files = ( + 612674D32D68391DF2AF6E89FA6D9BBC /* Pods-yinmeng-ios-umbrella.h in Headers */, + ); + runOnlyForDeploymentPostprocessing = 0; + }; + ED12AA7015568FEE3FAA009FC97DAAD5 /* Headers */ = { + isa = PBXHeadersBuildPhase; + buildActionMask = 2147483647; + files = ( + F038D81F7ABAA15CF03246AD4BF334F7 /* Alamofire-umbrella.h in Headers */, + ); + runOnlyForDeploymentPostprocessing = 0; + }; + EE7AE9E8918B6F399A2DDE80341B119D /* Headers */ = { + isa = PBXHeadersBuildPhase; + buildActionMask = 2147483647; + files = ( + 5484C183C3C25F933AEDAFADF8E4C404 /* Kingfisher-umbrella.h in Headers */, + ); + runOnlyForDeploymentPostprocessing = 0; + }; +/* End PBXHeadersBuildPhase section */ + +/* Begin PBXNativeTarget section */ + 10D88C24864319FF583AD6D156896F32 /* HandyJSON */ = { + isa = PBXNativeTarget; + buildConfigurationList = 50FD3D310936ECB8784F9C1229DA48CC /* Build configuration list for PBXNativeTarget "HandyJSON" */; + buildPhases = ( + 6FC876053E92670778D608CA0478F728 /* Headers */, + B186292004011247A56FAC41B9D6C6A2 /* Sources */, + 5BFADEC849BD22C6CD97E83544F3E6C1 /* Frameworks */, + C66434357555D3E88C8F202AD4D00053 /* Resources */, + ); + buildRules = ( + ); + dependencies = ( + ); + name = HandyJSON; + productName = HandyJSON; + productReference = CD54121DDA84872534168702B5F92950 /* HandyJSON.framework */; + productType = "com.apple.product-type.framework"; + }; + 17F9141D333DA1A7BE5937F227221070 /* Moya */ = { + isa = PBXNativeTarget; + buildConfigurationList = 01BAF98FDA9A2155B61AAC471DB108C6 /* Build configuration list for PBXNativeTarget "Moya" */; + buildPhases = ( + 410D0F27EDB13938D025BB9DBD661EB4 /* Headers */, + 0F059D90C50CD829E3DBCB5EB514E8DD /* Sources */, + 41444FC6B9FA2D386D58EF06093B5C77 /* Frameworks */, + 4C0F08BBDA0F701DF186D4677854849E /* Resources */, + ); + buildRules = ( + ); + dependencies = ( + 861D671FE3252AAF9F3546CB1B7E113C /* PBXTargetDependency */, + ); + name = Moya; + productName = Moya; + productReference = 3756A9BBE41ABEE8DCBF5BCA6972C4DA /* Moya */; + productType = "com.apple.product-type.framework"; + }; + 19622742EBA51E823D6DAE3F8CDBFAD4 /* SnapKit */ = { + isa = PBXNativeTarget; + buildConfigurationList = 58EAA7FF29EA237538F747F2AF468203 /* Build configuration list for PBXNativeTarget "SnapKit" */; + buildPhases = ( + 5FA4790A32ECD84F2CEA55509107BD0A /* Headers */, + 7B7E69B2799BABEB7764F85296B591B7 /* Sources */, + E8E4E7CE8309D3EF7B7476AC57986BE9 /* Frameworks */, + 820C67429A90336F5AF1C850DF03B1B9 /* Resources */, + ); + buildRules = ( + ); + dependencies = ( + ); + name = SnapKit; + productName = SnapKit; + productReference = 979486118B3E90C08386079D57962701 /* SnapKit */; + productType = "com.apple.product-type.framework"; + }; + 20A1E7406A71749DBD4ADC955548E4AF /* Pods-yinmeng-ios */ = { + isa = PBXNativeTarget; + buildConfigurationList = 09CCB2E572716A4C9765854032B74A05 /* Build configuration list for PBXNativeTarget "Pods-yinmeng-ios" */; + buildPhases = ( + 9F4F99D2A751CF26D6C10130E33EBBC8 /* Headers */, + B61519DD991056A1D585A34B6FA1D19C /* Sources */, + AB4F7BDEBC13070575FC00805E8C810B /* Frameworks */, + 4177B571C700B914AC7CAFACDF839D37 /* Resources */, + ); + buildRules = ( + ); + dependencies = ( + 294D4F167509B367133479F70C99FAAE /* PBXTargetDependency */, + 9D46F8983711587F027876C6D9483255 /* PBXTargetDependency */, + 7AB2CEB2384A2E610A19A45C46C38838 /* PBXTargetDependency */, + 94F1664E9E64C92DEFB0970E1925F652 /* PBXTargetDependency */, + 9A711F5A31AD64A8B5050478F04948AD /* PBXTargetDependency */, + F6A63E96803B3C03A914736028E41D5E /* PBXTargetDependency */, + D7BCCB438C6783D4AD34AFA01C3017E2 /* PBXTargetDependency */, + BB9A3FAEC46882D1BE980F96D535919F /* PBXTargetDependency */, + AAA859713D3E1B87E847AD768604A711 /* PBXTargetDependency */, + 19677A4C977E43BF6FDC659077FF8F64 /* PBXTargetDependency */, + ); + name = "Pods-yinmeng-ios"; + productName = Pods_yinmeng_ios; + productReference = 9BC03DDC341E7F14C1F96A0C0F826FD3 /* Pods-yinmeng-ios */; + productType = "com.apple.product-type.framework"; + }; + 4622BFEF3DC16E8BD15EEFC30D4D0084 /* RxRelay */ = { + isa = PBXNativeTarget; + buildConfigurationList = 5D6B3CF88B71711BCA7DA130AF7EC13D /* Build configuration list for PBXNativeTarget "RxRelay" */; + buildPhases = ( + 76797DC1949EF10E4CD36CF86C9A5F73 /* Headers */, + D21AEE57BB74E8BE2A5ABEE23432A806 /* Sources */, + 69E41FE1C983D4504EF52D46E5289EA7 /* Frameworks */, + 76CC561DC552B829176FBDE7B0EA1979 /* Resources */, + ); + buildRules = ( + ); + dependencies = ( + 129B8D6EDBC0E697BF55B3C8FE0FE1A6 /* PBXTargetDependency */, + ); + name = RxRelay; + productName = RxRelay; + productReference = FF8B264DFE802855D5D67E7CDDABFC3C /* RxRelay */; + productType = "com.apple.product-type.framework"; + }; + 542460E7CDF2A9D5B2ECB5F8CE549E34 /* Reusable */ = { + isa = PBXNativeTarget; + buildConfigurationList = 865D36780A78CA83F04FC3A8CDB81EE4 /* Build configuration list for PBXNativeTarget "Reusable" */; + buildPhases = ( + 6FE53F6191854563DFA7CE2E0C3378E0 /* Headers */, + 502D4F95CF367F48D643967011501E21 /* Sources */, + 5FE88477180E51E6261C299B8858B2F2 /* Frameworks */, + 661A1BDB1E080B04B6F0DD83DE90E23A /* Resources */, + ); + buildRules = ( + ); + dependencies = ( + ); + name = Reusable; + productName = Reusable; + productReference = A0ABA07B4D48354ED3F51C2D6AF5426B /* Reusable */; + productType = "com.apple.product-type.framework"; + }; + 7AD0C6DCDC9CEC8A3C7C10C7FEE07BE6 /* RxCocoa */ = { + isa = PBXNativeTarget; + buildConfigurationList = 1E42B460D55BA3EBE021004CC2CE312C /* Build configuration list for PBXNativeTarget "RxCocoa" */; + buildPhases = ( + 0C9ED7F80C58C162BDF0D2A96D8615F6 /* Headers */, + 3DA8F71AF3BF41150950832BA8D64BFE /* Sources */, + E877FC0D3719519B688F3E17FF0228B2 /* Frameworks */, + 5D4809C72FC4B366B262906F436A3EF1 /* Resources */, + ); + buildRules = ( + ); + dependencies = ( + D9B00D70E911FF84772D30A6F17F24C2 /* PBXTargetDependency */, + 41D57993E84517CD638C70ADEC5E44C6 /* PBXTargetDependency */, + ); + name = RxCocoa; + productName = RxCocoa; + productReference = BC432FD48A5932251F1CAFBC4BF74894 /* RxCocoa */; + productType = "com.apple.product-type.framework"; + }; + 82B0A41D3031FF27D78E17B0A9A46FB0 /* MBProgressHUD */ = { + isa = PBXNativeTarget; + buildConfigurationList = A7BD2681E97C00DCC2EF91B0EBA76110 /* Build configuration list for PBXNativeTarget "MBProgressHUD" */; + buildPhases = ( + 5D82C29ACD851E6EA219B34A73C961F5 /* Headers */, + 7E957D4020E4C4BC633BF50F7F51E5F6 /* Sources */, + D6DC8F0C2894774845C1DD2E7CA07B0C /* Frameworks */, + C0E0F7D28F4D633128D0F53BEAE34D3D /* Resources */, + ); + buildRules = ( + ); + dependencies = ( + ); + name = MBProgressHUD; + productName = MBProgressHUD; + productReference = 8B8FAB0D627B17EDE1366984278705D9 /* MBProgressHUD.framework */; + productType = "com.apple.product-type.framework"; + }; + 9828BBC09E9FB1238624113D7456E59E /* Kingfisher-Kingfisher */ = { + isa = PBXNativeTarget; + buildConfigurationList = E29E987197D3C29B626AB8FA0A012C04 /* Build configuration list for PBXNativeTarget "Kingfisher-Kingfisher" */; + buildPhases = ( + B9C4339E494FCDEDF339AE80CF8263B3 /* Sources */, + 7384B674865A3735705993DE278F24FB /* Frameworks */, + 534208814D98B46052FC5F7AF7F8CB0C /* Resources */, + ); + buildRules = ( + ); + dependencies = ( + ); + name = "Kingfisher-Kingfisher"; + productName = Kingfisher; + productReference = C298ABB78D9B05529B89D8322DB2E7B0 /* Kingfisher-Kingfisher */; + productType = "com.apple.product-type.bundle"; + }; + E8022D22FAA6690B5E1C379C1BCE1491 /* Kingfisher */ = { + isa = PBXNativeTarget; + buildConfigurationList = 61C623C1EDB6AD9DC66AD8969115C6E1 /* Build configuration list for PBXNativeTarget "Kingfisher" */; + buildPhases = ( + EE7AE9E8918B6F399A2DDE80341B119D /* Headers */, + 4BB76B024D854BF05C17FA65706B2CDD /* Sources */, + 7B0303768C22ED77186E9DAE044BDE14 /* Frameworks */, + 193F205B96B5C673605F0D2762DD1737 /* Resources */, + ); + buildRules = ( + ); + dependencies = ( + E7FE09331A2C0535926E5A346DDFE0AB /* PBXTargetDependency */, + ); + name = Kingfisher; + productName = Kingfisher; + productReference = C3F44C782D64D7EB20B61CE3844EBFAD /* Kingfisher */; + productType = "com.apple.product-type.framework"; + }; + EA9EA43B3B503823EE36C60D9C8A865F /* RxSwift */ = { + isa = PBXNativeTarget; + buildConfigurationList = BD779400D1CA952C3C31F225A3BA7650 /* Build configuration list for PBXNativeTarget "RxSwift" */; + buildPhases = ( + 7BA941A73E8FBF5B0419B83592AA4F77 /* Headers */, + 647BE045D378FFA99A884983B70E9E03 /* Sources */, + 022CF4B8BBD5C8D34A275928347518C5 /* Frameworks */, + 32EBDC9D24846EFD7CC23F9D0F90F003 /* Resources */, + ); + buildRules = ( + ); + dependencies = ( + ); + name = RxSwift; + productName = RxSwift; + productReference = 809C5FAB588354C9BA37DC3EAB8CB45C /* RxSwift */; + productType = "com.apple.product-type.framework"; + }; + EAAA1AD3A8A1B59AB91319EE40752C6D /* Alamofire */ = { + isa = PBXNativeTarget; + buildConfigurationList = D7761A54AFA2998F27E0BC2FACC2EB53 /* Build configuration list for PBXNativeTarget "Alamofire" */; + buildPhases = ( + ED12AA7015568FEE3FAA009FC97DAAD5 /* Headers */, + 277C3B3F937C6D40D2B777A164FAB89D /* Sources */, + 5BF6E64D3157435E5797A5278584A4DC /* Frameworks */, + 565FD2058706F22D2347B30C65280F30 /* Resources */, + ); + buildRules = ( + ); + dependencies = ( + ); + name = Alamofire; + productName = Alamofire; + productReference = 5D797E9A5C5782CE845840781FA1CC81 /* Alamofire */; + productType = "com.apple.product-type.framework"; + }; +/* End PBXNativeTarget section */ + +/* Begin PBXProject section */ + BFDFE7DC352907FC980B868725387E98 /* Project object */ = { + isa = PBXProject; + attributes = { + LastSwiftUpdateCheck = 1300; + LastUpgradeCheck = 1300; + }; + buildConfigurationList = 4821239608C13582E20E6DA73FD5F1F9 /* Build configuration list for PBXProject "Pods" */; + compatibilityVersion = "Xcode 14.0"; + developmentRegion = en; + hasScannedForEncodings = 0; + knownRegions = ( + Base, + en, + ); + mainGroup = CF1408CF629C7361332E53B88F7BD30C; + productRefGroup = 4ACE8263887E88BE1B13DCD869DFFCAF /* Products */; + projectDirPath = ""; + projectRoot = ""; + targets = ( + EAAA1AD3A8A1B59AB91319EE40752C6D /* Alamofire */, + 10D88C24864319FF583AD6D156896F32 /* HandyJSON */, + E8022D22FAA6690B5E1C379C1BCE1491 /* Kingfisher */, + 9828BBC09E9FB1238624113D7456E59E /* Kingfisher-Kingfisher */, + 82B0A41D3031FF27D78E17B0A9A46FB0 /* MBProgressHUD */, + 17F9141D333DA1A7BE5937F227221070 /* Moya */, + 20A1E7406A71749DBD4ADC955548E4AF /* Pods-yinmeng-ios */, + 542460E7CDF2A9D5B2ECB5F8CE549E34 /* Reusable */, + 7AD0C6DCDC9CEC8A3C7C10C7FEE07BE6 /* RxCocoa */, + 4622BFEF3DC16E8BD15EEFC30D4D0084 /* RxRelay */, + EA9EA43B3B503823EE36C60D9C8A865F /* RxSwift */, + 19622742EBA51E823D6DAE3F8CDBFAD4 /* SnapKit */, + ); + }; +/* End PBXProject section */ + +/* Begin PBXResourcesBuildPhase section */ + 193F205B96B5C673605F0D2762DD1737 /* Resources */ = { + isa = PBXResourcesBuildPhase; + buildActionMask = 2147483647; + files = ( + 3841545F19CF975D5CA907A73A949FF6 /* Kingfisher-Kingfisher in Resources */, + ); + runOnlyForDeploymentPostprocessing = 0; + }; + 32EBDC9D24846EFD7CC23F9D0F90F003 /* Resources */ = { + isa = PBXResourcesBuildPhase; + buildActionMask = 2147483647; + files = ( + ); + runOnlyForDeploymentPostprocessing = 0; + }; + 4177B571C700B914AC7CAFACDF839D37 /* Resources */ = { + isa = PBXResourcesBuildPhase; + buildActionMask = 2147483647; + files = ( + ); + runOnlyForDeploymentPostprocessing = 0; + }; + 4C0F08BBDA0F701DF186D4677854849E /* Resources */ = { + isa = PBXResourcesBuildPhase; + buildActionMask = 2147483647; + files = ( + ); + runOnlyForDeploymentPostprocessing = 0; + }; + 534208814D98B46052FC5F7AF7F8CB0C /* Resources */ = { + isa = PBXResourcesBuildPhase; + buildActionMask = 2147483647; + files = ( + CFB94F60324C50650E055314D46837BA /* PrivacyInfo.xcprivacy in Resources */, + ); + runOnlyForDeploymentPostprocessing = 0; + }; + 565FD2058706F22D2347B30C65280F30 /* Resources */ = { + isa = PBXResourcesBuildPhase; + buildActionMask = 2147483647; + files = ( + ); + runOnlyForDeploymentPostprocessing = 0; + }; + 5D4809C72FC4B366B262906F436A3EF1 /* Resources */ = { + isa = PBXResourcesBuildPhase; + buildActionMask = 2147483647; + files = ( + ); + runOnlyForDeploymentPostprocessing = 0; + }; + 661A1BDB1E080B04B6F0DD83DE90E23A /* Resources */ = { + isa = PBXResourcesBuildPhase; + buildActionMask = 2147483647; + files = ( + ); + runOnlyForDeploymentPostprocessing = 0; + }; + 76CC561DC552B829176FBDE7B0EA1979 /* Resources */ = { + isa = PBXResourcesBuildPhase; + buildActionMask = 2147483647; + files = ( + ); + runOnlyForDeploymentPostprocessing = 0; + }; + 820C67429A90336F5AF1C850DF03B1B9 /* Resources */ = { + isa = PBXResourcesBuildPhase; + buildActionMask = 2147483647; + files = ( + ); + runOnlyForDeploymentPostprocessing = 0; + }; + C0E0F7D28F4D633128D0F53BEAE34D3D /* Resources */ = { + isa = PBXResourcesBuildPhase; + buildActionMask = 2147483647; + files = ( + ); + runOnlyForDeploymentPostprocessing = 0; + }; + C66434357555D3E88C8F202AD4D00053 /* Resources */ = { + isa = PBXResourcesBuildPhase; + buildActionMask = 2147483647; + files = ( + ); + runOnlyForDeploymentPostprocessing = 0; + }; +/* End PBXResourcesBuildPhase section */ + +/* Begin PBXSourcesBuildPhase section */ + 0F059D90C50CD829E3DBCB5EB514E8DD /* Sources */ = { + isa = PBXSourcesBuildPhase; + buildActionMask = 2147483647; + files = ( + A755043CEE0384C2BB9238AF2F200F4B /* AccessTokenPlugin.swift in Sources */, + 7CB4D382650A1BB458B68BF3B39FE27D /* AnyEncodable.swift in Sources */, + 2AA5064ABDA1A14FD82F98F25CF853D8 /* Atomic.swift in Sources */, + 375CAADA212D838EE018E292E684F61E /* Cancellable.swift in Sources */, + AD75E7744AC7055BD537E5F9E4A098B4 /* CredentialsPlugin.swift in Sources */, + E7B06E98F3530C96FB6B2D8272169C22 /* Endpoint.swift in Sources */, + 8A7A14267160A9EACDC74A9E21B8F058 /* Image.swift in Sources */, + 9930A6A180279D0493FB8DB95BF23C21 /* Moya+Alamofire.swift in Sources */, + 79AB21FCF882EB4FC9DD5F111C2F53D3 /* Moya-dummy.m in Sources */, + 76374B984BAD760575C5223FEC2C6FC1 /* MoyaError.swift in Sources */, + 0618E661B571A4FCC8B886F792E756CE /* MoyaProvider.swift in Sources */, + 77F109FA3951C23E7F0E7A4F5581F488 /* MoyaProvider+Defaults.swift in Sources */, + 7212ACC786B61C86DE7EBED50CC29FD5 /* MoyaProvider+Internal.swift in Sources */, + 9A3537E0E6B50DE756E96CDB3AD4EDE3 /* MultipartFormData.swift in Sources */, + 241FB0C1BD55CC6F05C7FD78590EE5A1 /* MultiTarget.swift in Sources */, + 9426B0386E4DC02F4E347A457C39144A /* NetworkActivityPlugin.swift in Sources */, + 0EA96364E99A403FB19009B589203048 /* NetworkLoggerPlugin.swift in Sources */, + 6C5571DAC14E51299671ABC2AF0E1A62 /* Plugin.swift in Sources */, + DADAAFFCDC241D3E6A4DCF567C12D280 /* RequestTypeWrapper.swift in Sources */, + FBBA4924C2C83A3715D6F04B1E6E64C4 /* Response.swift in Sources */, + 95563637A4972EEA70958AC205B9D88A /* TargetType.swift in Sources */, + B0EF3E2802E1715202F99325EAE0F27A /* Task.swift in Sources */, + 7E313C5665BD42F0877BFD2CEBBD82CE /* URL+Moya.swift in Sources */, + D5CFDCFE3128D6FA2A4D385FDFD42AA1 /* URLRequest+Encoding.swift in Sources */, + 0C080D5202A572C8434CA8635D35B29C /* ValidationType.swift in Sources */, + ); + runOnlyForDeploymentPostprocessing = 0; + }; + 277C3B3F937C6D40D2B777A164FAB89D /* Sources */ = { + isa = PBXSourcesBuildPhase; + buildActionMask = 2147483647; + files = ( + 320C0D7A88AA812EFB20016BA1F5D7AE /* AFError.swift in Sources */, + 81E6A0FF7F286008345ECFA3A2103FA8 /* Alamofire.swift in Sources */, + D09FBBADAF7C5C757AA5AB5DFE54BD25 /* Alamofire-dummy.m in Sources */, + F2415AE8678DE2698B7AD7D88B1A5C0F /* AlamofireExtended.swift in Sources */, + 197457852FC83E905248660B0F930452 /* AuthenticationInterceptor.swift in Sources */, + 04A8430BFC619C34E5F4D3878D094380 /* CachedResponseHandler.swift in Sources */, + 385BC4B250B6A6DB8AAAEA77D5B7A46F /* Combine.swift in Sources */, + 78B1DD1219182494A6AFAD26AAB20AA6 /* Concurrency.swift in Sources */, + 8E698F134A953250D5834C8B83CDAD34 /* DispatchQueue+Alamofire.swift in Sources */, + 82FD97FBBEFE51E2D3B434AF4954FC93 /* EventMonitor.swift in Sources */, + 529173B31EFCD3D199E79866AFBEC86C /* HTTPHeaders.swift in Sources */, + F66CC47AD425C8D57BD149AFD09C2AFE /* HTTPMethod.swift in Sources */, + 737747B9A98257DB58112C3A23686669 /* MultipartFormData.swift in Sources */, + 732C29255F73EF3D83D49BD4F8FEAA8F /* MultipartUpload.swift in Sources */, + BAB17A1C6CAD14B3788973EAF8466C93 /* NetworkReachabilityManager.swift in Sources */, + 3A59D8FBAF9A54906E3644AC80465AFB /* Notifications.swift in Sources */, + 7D64BC3E6CAA4AB54EAC0AAADE93F578 /* OperationQueue+Alamofire.swift in Sources */, + B17D933C8F8BC6A4F91AA620D7D7A870 /* ParameterEncoder.swift in Sources */, + 482B74C0548970BB9C095E2D8530E421 /* ParameterEncoding.swift in Sources */, + 079F0820555C5B86C9FBD5EC6344137F /* Protected.swift in Sources */, + ECE6F23823454A8FDB3F97CE1A7CD182 /* RedirectHandler.swift in Sources */, + 5B92A66A66BD639411C3D839A0F87B0C /* Request.swift in Sources */, + A523488C60BF961290D0B1ABB9ADACEC /* RequestCompression.swift in Sources */, + 1AFD57838680DF58184FF94D14C7F3FF /* RequestInterceptor.swift in Sources */, + ECF2F956B37A4C28B228BC291A57AD6E /* RequestTaskMap.swift in Sources */, + AA721ECC2B36AFB7D9FE70C83E6D63F9 /* Response.swift in Sources */, + 3FA127A261BB563409868A0DC21807B2 /* ResponseSerialization.swift in Sources */, + F6E94E8EE1CE35F49B9091BE8748587B /* Result+Alamofire.swift in Sources */, + 643A7AFFB7AEB70B2B9B7E0926055023 /* RetryPolicy.swift in Sources */, + 77AB6AF4BFC6DE016DA7C057B5799C84 /* ServerTrustEvaluation.swift in Sources */, + 282FCD4EA8B05830E9108690B8CD336B /* Session.swift in Sources */, + E6251F02EE12804D1B66AE32E716E664 /* SessionDelegate.swift in Sources */, + C04739CBCEE445B66192BFA708655EDF /* StringEncoding+Alamofire.swift in Sources */, + D0560E8E2E5EB407B5D8E0381BF453FA /* URLConvertible+URLRequestConvertible.swift in Sources */, + C8269B42DED12AB1F275648D0BD32E45 /* URLEncodedFormEncoder.swift in Sources */, + 11CCD832BD537718892C6A216A38490A /* URLRequest+Alamofire.swift in Sources */, + 67B10FEAA3B7E5387D20E76B1085E94D /* URLSessionConfiguration+Alamofire.swift in Sources */, + D368E6F70C5E6998548A72E65F92432D /* Validation.swift in Sources */, + ); + runOnlyForDeploymentPostprocessing = 0; + }; + 3DA8F71AF3BF41150950832BA8D64BFE /* Sources */ = { + isa = PBXSourcesBuildPhase; + buildActionMask = 2147483647; + files = ( + 426C76C68C9FA3582F26BBB9E96316E4 /* _RX.m in Sources */, + C2D4FEEAF01038DB5C31CA401C105476 /* _RXDelegateProxy.m in Sources */, + F60E2B85B28D1E27FD52F9B0D62A50C8 /* _RXKVOObserver.m in Sources */, + C12DCA02D36C5C6167F566AFC96A6057 /* _RXObjCRuntime.m in Sources */, + 8A8AD24A8CE75FBE807EB5A9FC11E62A /* Bag.swift in Sources */, + FE9261A1344AF922C1EFCB457B938425 /* BehaviorRelay+Driver.swift in Sources */, + 1CC3FBF38E35B664C2A003664C58E2D7 /* ControlEvent.swift in Sources */, + 47D3FBF90386DABCAB70AA2CA176C8EB /* ControlEvent+Driver.swift in Sources */, + F3B4A826460EF6A9B19849D1E7AF6A52 /* ControlEvent+Signal.swift in Sources */, + 0907413AF1BF312948C6CA8289CE29AE /* ControlProperty.swift in Sources */, + D6FDE9DFAC4AA548A9A4E2D6BBCE54FC /* ControlProperty+Driver.swift in Sources */, + 81148E8E0935476F92B10881A023D0DC /* ControlTarget.swift in Sources */, + B3167FEDC691D1DDF267F855CFF33636 /* DelegateProxy.swift in Sources */, + 567E2B1BAE575E6556A2E57191BA2DA7 /* DelegateProxyType.swift in Sources */, + CF32140300489AD5D6D5A74E4605FDAF /* DispatchQueue+Extensions.swift in Sources */, + 0B5BB08F1937AD6324F0ADDD8F9E067B /* Driver.swift in Sources */, + BA5658B6C27A81FA4665E507A1ED88DA /* Driver+Subscription.swift in Sources */, + 6927E0A61FCF762B43C75325110C3D77 /* Infallible+Bind.swift in Sources */, + D3AB490FA372E1922315D4F2E5709254 /* InfiniteSequence.swift in Sources */, + 377229136C0061FE2FABE71862C2070F /* ItemEvents.swift in Sources */, + C784A7AAD94DD830A9EB5ADDEE6DE1BB /* KVORepresentable.swift in Sources */, + 5230B70A7B448918B83D3B983533D29A /* KVORepresentable+CoreGraphics.swift in Sources */, + CE08483A41A5535019BE5E198792480B /* KVORepresentable+Swift.swift in Sources */, + 5A3DE5038C0E8C2BAFC3316589D0F918 /* NotificationCenter+Rx.swift in Sources */, + B59095D5EF330419B3ADFBAD7EBC2B1F /* NSButton+Rx.swift in Sources */, + BAD3834746DAB3C038417D16101B29A2 /* NSControl+Rx.swift in Sources */, + BB72FC9215BD907A82AE928782813D6C /* NSObject+Rx.swift in Sources */, + 2087DD8278E2FC32F75C947E058EA423 /* NSObject+Rx+KVORepresentable.swift in Sources */, + 96F9E4762C05BF7B009FA52FC18C18C5 /* NSObject+Rx+RawRepresentable.swift in Sources */, + F2DDF679DF721DDA14A53744DD540092 /* NSSlider+Rx.swift in Sources */, + 5A39F3F258372FA025F08ECAFFFCF71D /* NSTextField+Rx.swift in Sources */, + D2004A03ADD62CD0C4649710F32A91F5 /* NSTextStorage+Rx.swift in Sources */, + FCD9660A73D7E00EA19E2F2295876E04 /* NSTextView+Rx.swift in Sources */, + 6DB19BEE9C42CBE8101A114524B38CE7 /* NSView+Rx.swift in Sources */, + F9821B669566BA01F845426DC6834E76 /* Observable+Bind.swift in Sources */, + 55713DE36F28B0D078ADAD60D5EE7FF4 /* ObservableConvertibleType+Driver.swift in Sources */, + 4F315C18FC854325DD5D062DD7A363D5 /* ObservableConvertibleType+SharedSequence.swift in Sources */, + D47B1058991EEC007A109B8E354EDB80 /* ObservableConvertibleType+Signal.swift in Sources */, + 2662EA3D1400EC4BD90947902CD85670 /* Platform.Darwin.swift in Sources */, + A0208B623442A26CB9157F193CBB4A7F /* Platform.Linux.swift in Sources */, + 6F803B4767FE50C12E3F0402DC0A3BE5 /* PriorityQueue.swift in Sources */, + 275C15979C1EC7DB6234974758037906 /* PublishRelay+Signal.swift in Sources */, + 72EE3F69E6154EF5C5524DE4F4EE0B5C /* Queue.swift in Sources */, + 2FCCAB4BA1D71EDB993309159D5DFA7C /* RecursiveLock.swift in Sources */, + 263A6B3B9C8592FC16697D2AB6333AC9 /* RxCocoa.swift in Sources */, + 18211EE7B495AA06EBBED1D6FD9423C0 /* RxCocoa-dummy.m in Sources */, + 84AEE29F4E7DDA962C49D6FAC6044EBC /* RxCocoaObjCRuntimeError+Extensions.swift in Sources */, + 72FCE0D3F5EA7EB908C108DFD468B267 /* RxCollectionViewDataSourcePrefetchingProxy.swift in Sources */, + B5ACECCDD52AF69EBA2E11666BBAEB42 /* RxCollectionViewDataSourceProxy.swift in Sources */, + 7BA5D9B38DAEDD6A5166ECF2A498D194 /* RxCollectionViewDataSourceType.swift in Sources */, + C6A1AF1239CD2F0D4745BAA097E1E63F /* RxCollectionViewDelegateProxy.swift in Sources */, + 9F370B3928A333AD7E41680A29B1F051 /* RxCollectionViewReactiveArrayDataSource.swift in Sources */, + 6DFB5C921332D5E14BF251A5ADA46473 /* RxNavigationControllerDelegateProxy.swift in Sources */, + 111810B8652D290C58076B92FCE40A1F /* RxPickerViewAdapter.swift in Sources */, + 782082D9F5529E63F249E8811BA6FD10 /* RxPickerViewDataSourceProxy.swift in Sources */, + 61EB40AB5F1BB5E6FDC8C5CDE06C3DE9 /* RxPickerViewDataSourceType.swift in Sources */, + EA5FE4B4B3BF04976C37430E4F3721EF /* RxPickerViewDelegateProxy.swift in Sources */, + ACA3DBC73A19F3CDF9C4FAB09988D0E6 /* RxScrollViewDelegateProxy.swift in Sources */, + 7C9C0D2AB5BB6670928CC95B4DA46814 /* RxSearchBarDelegateProxy.swift in Sources */, + A93FC5BCB5B02182D27377A3724A60B1 /* RxSearchControllerDelegateProxy.swift in Sources */, + 07550E0A8451CACE9593873C543F1B78 /* RxTabBarControllerDelegateProxy.swift in Sources */, + AAA7A11591D6E4B06124708291C37698 /* RxTabBarDelegateProxy.swift in Sources */, + 2EFF6DCB0FC66EB564B96A35840D5016 /* RxTableViewDataSourcePrefetchingProxy.swift in Sources */, + 1787EBB3723875770997006509209EDD /* RxTableViewDataSourceProxy.swift in Sources */, + 3EFE8454C7301C05A00EC9870F47968B /* RxTableViewDataSourceType.swift in Sources */, + EF6DD06709E5EFD67031FF9B5901A827 /* RxTableViewDelegateProxy.swift in Sources */, + CB3ACAC0625702DEC5BBB5F9AC0CC737 /* RxTableViewReactiveArrayDataSource.swift in Sources */, + F5AF27692F3A5C9087F015B5C40A35E7 /* RxTarget.swift in Sources */, + 3A379670D0CFBC0FCC9D0F66E944D074 /* RxTextStorageDelegateProxy.swift in Sources */, + 114F6342633413C8BBEC4169F34CFAFD /* RxTextViewDelegateProxy.swift in Sources */, + B3F14F1B196B5858BD951366FA89FA6D /* RxWKNavigationDelegateProxy.swift in Sources */, + 6BDA2BC21E394076C2E58E9269F4AABD /* SchedulerType+SharedSequence.swift in Sources */, + DE71610B229DF6E2B65A8574BAF21414 /* SectionedViewDataSourceType.swift in Sources */, + 9E8BA4FB802EDCD492DAF618CA7BFCE8 /* SharedSequence.swift in Sources */, + 768A33DCEB41CBC5C7ECF5F0220B1A97 /* SharedSequence+Concurrency.swift in Sources */, + FAF7C9C4F9B6AE2CE9F5866B210D9275 /* SharedSequence+Operators.swift in Sources */, + 9ADE1DD7C6AD8B57FD158350A66EF8D0 /* SharedSequence+Operators+arity.swift in Sources */, + 27F2BE5D6E990841E8DA1DF91CF3623B /* Signal.swift in Sources */, + 1F64C124283555FF5E1944FA37501247 /* Signal+Subscription.swift in Sources */, + 24C8FC3B11676AD57F3A7914E6621AD0 /* TextInput.swift in Sources */, + C378AC3DF57A41F6F16D01BBD7A1BB02 /* UIActivityIndicatorView+Rx.swift in Sources */, + 252B64A12E2810921E86B78ECD5BDA9D /* UIApplication+Rx.swift in Sources */, + BBD437FE6BFF63452E6B7E08DFAB4DD9 /* UIBarButtonItem+Rx.swift in Sources */, + 961B5042F0BFBD2C5FCDCCF40E2EA7CD /* UIButton+Rx.swift in Sources */, + A214A653E430C9079AA7B1090169262D /* UICollectionView+Rx.swift in Sources */, + 371CD58570B89DE6A3090CC6CE16AEE7 /* UIControl+Rx.swift in Sources */, + 2AC794BEBE17BA6257A13065584EC5DF /* UIDatePicker+Rx.swift in Sources */, + D4933D17DC286C3DABCFD930BED56DD9 /* UIGestureRecognizer+Rx.swift in Sources */, + 1F6F0B8C1A8EA633EFEBE64EB781A6B5 /* UINavigationController+Rx.swift in Sources */, + A20321979D272B922CD60B531BD05F7F /* UIPickerView+Rx.swift in Sources */, + 660E73ECB1E50185B9D21BAA127DC3A0 /* UIRefreshControl+Rx.swift in Sources */, + D3BC528010D39EB2D79585A671FD80B6 /* UIScrollView+Rx.swift in Sources */, + 057D0EC1E728D714A73210ACAF1FAC6A /* UISearchBar+Rx.swift in Sources */, + AB88D7A71BA82D3BAF097C992BFB221B /* UISearchController+Rx.swift in Sources */, + 90585B3B5526DB8ECBD1AB8EF2C4D5A2 /* UISegmentedControl+Rx.swift in Sources */, + 608DC0C8110DDFF5D8E5A43BB48A6A86 /* UISlider+Rx.swift in Sources */, + 419A11A8F7797E02FA5AAC6D8B4B3C2F /* UIStepper+Rx.swift in Sources */, + 654D9C29A846E7ED4DD5BF0BFC8D64B8 /* UISwitch+Rx.swift in Sources */, + 3EE7A29FCEE9B2A257B977E7137BC44C /* UITabBar+Rx.swift in Sources */, + 5435E924E7CE7B05B7F650C078A12F5B /* UITabBarController+Rx.swift in Sources */, + 8AEE5B74A5BAC274D6589F229D867768 /* UITableView+Rx.swift in Sources */, + B00B8088EB50EA3F0F875993C675F421 /* UITextField+Rx.swift in Sources */, + 14CAA40442778EFE3DF8B07CE170CAF7 /* UITextView+Rx.swift in Sources */, + F7774F70F3F7CD7E11F01BD8B62FFF15 /* URLSession+Rx.swift in Sources */, + D2C293D847E95B01671EB3E6A32F11C7 /* WKWebView+Rx.swift in Sources */, + ); + runOnlyForDeploymentPostprocessing = 0; + }; + 4BB76B024D854BF05C17FA65706B2CDD /* Sources */ = { + isa = PBXSourcesBuildPhase; + buildActionMask = 2147483647; + files = ( + 07C677042BB048A9440E13D5EEB8DC0E /* AnimatedImageView.swift in Sources */, + 40D926572C52D27517FFC92545819FFB /* AuthenticationChallengeResponsable.swift in Sources */, + E7378F61AD6959D5538E595EA4A48AF4 /* AVAssetImageDataProvider.swift in Sources */, + 4B23B05F62E805619C9B5BA83E34F4A9 /* Box.swift in Sources */, + A6FFEA8E51C1C175570C501EB520CE5E /* CacheSerializer.swift in Sources */, + BC16AFDE4BAC1CD19CDE329F20CC6EC4 /* CallbackQueue.swift in Sources */, + 9C14C583C78E7461369235D895A978B7 /* CPListItem+Kingfisher.swift in Sources */, + 4155E1924B8FC76EF105D44698EFB548 /* Delegate.swift in Sources */, + 4DEAE5703BDD544C9956BF42F7D57CE5 /* DiskStorage.swift in Sources */, + CA1BFC94E5AD2E95C061B14902827755 /* ExtensionHelpers.swift in Sources */, + 8E778C0090C85DDB5290B07143FFD917 /* Filter.swift in Sources */, + 6C1EED16F5E7B9F4BA1698A5D083EC50 /* FormatIndicatedCacheSerializer.swift in Sources */, + 2279FE56C854E4A8D1623EFF123490BA /* GIFAnimatedImage.swift in Sources */, + 69D07BBB6641693C30C1D2A3774F6721 /* GraphicsContext.swift in Sources */, + 71D07A691D1D78FD8B421B127CE7496B /* Image.swift in Sources */, + EE4E233D2DD0DFC4F82FD6748EC3429F /* ImageBinder.swift in Sources */, + 5BE4EFBB9E0CB1968E72E793FF118931 /* ImageCache.swift in Sources */, + 38BFFE498FF2491FD1C152319A94E9F5 /* ImageContext.swift in Sources */, + 6066DF8EBAAF4EAD3A904AFF921C3CBB /* ImageDataProcessor.swift in Sources */, + 6BD6A6695D05908524545A776D4C36B9 /* ImageDataProvider.swift in Sources */, + D8548F55D2A30E5935CD1773CFD1510E /* ImageDownloader.swift in Sources */, + 23A3CED3EE6A0A4815A92D9E0B960328 /* ImageDownloaderDelegate.swift in Sources */, + 258A528FB1FD89D83512AA538B069E71 /* ImageDrawing.swift in Sources */, + 08923846D88DF3ED6D918079C91116C6 /* ImageFormat.swift in Sources */, + 2AD8987B16604E75E19FE7172332B9BE /* ImageModifier.swift in Sources */, + AAFBF86E17174FF6DD3BBA2BB393D3EA /* ImagePrefetcher.swift in Sources */, + 43DFB49930346A1A730DC21E94E2F731 /* ImageProcessor.swift in Sources */, + 5EBC224DDA3EC6CCE8C42EED6063FD35 /* ImageProgressive.swift in Sources */, + CC5BC4391CF7452AF3254D8CAFC82062 /* ImageTransition.swift in Sources */, + 80C4B7E883C94E18102938F43B0EF240 /* ImageView+Kingfisher.swift in Sources */, + 0A1E7F06A1E1CA1DE2B389E6AE0A66A0 /* Indicator.swift in Sources */, + 69FE518ED5298543E204E1509D30952A /* KF.swift in Sources */, + 180BE95F60406A62CD794746BFE108B8 /* KFAnimatedImage.swift in Sources */, + 9AE3FEDB17CA68DFCD0BC534B8205E7A /* KFImage.swift in Sources */, + C4E9B6DBCE3A78C2127FA3A6269E57CA /* KFImageOptions.swift in Sources */, + 0FB2B84C4514FAE2D6B7B9E937784F55 /* KFImageProtocol.swift in Sources */, + 80D1BF4CD8C1A9EF7DA5012AAAE4D988 /* KFImageRenderer.swift in Sources */, + D9CC66222E55827BDBE32EFAB31B5381 /* KFOptionsSetter.swift in Sources */, + 3AA3DABB241FB655F8EE42D02EC95DFC /* Kingfisher.swift in Sources */, + 1F285EAFE181E45D258B44A554FF8837 /* Kingfisher-dummy.m in Sources */, + AFAEE9EC6534DE2F69C1FD33B034C92E /* KingfisherError.swift in Sources */, + 761DF0256CBB0CA4506580DFBB612194 /* KingfisherManager.swift in Sources */, + A67083E623272EF11F0ED2115AF7D273 /* KingfisherOptionsInfo.swift in Sources */, + 92B3198E1EBE2EC545BB36AF6A9CC368 /* MemoryStorage.swift in Sources */, + 2E7321581005F0AAF767213937D29680 /* NSButton+Kingfisher.swift in Sources */, + 817B896013FD56C04CD26E2F6C67EA7E /* NSTextAttachment+Kingfisher.swift in Sources */, + 68AF5CE54DF91D0EA6E1DD02432DCB0A /* Placeholder.swift in Sources */, + 43C89358BB61E73227F6791E4697FCCC /* RedirectHandler.swift in Sources */, + 81E4CCFEB1307757E98744344B75B9FB /* RequestModifier.swift in Sources */, + 86C39B668AB190EE95464C8AB1E0111A /* Resource.swift in Sources */, + 87304D5AF2582C6E7839864112534CBE /* Result.swift in Sources */, + 034A1879FF63C73CC22689EC8CBECBBC /* RetryStrategy.swift in Sources */, + F97840AF9065A123E8B1DABA7D95BB9D /* Runtime.swift in Sources */, + 731C34C22800D5F0AF417E801D3409B0 /* SessionDataTask.swift in Sources */, + F575822C8B7F17129429E00A9081ECA2 /* SessionDelegate.swift in Sources */, + E95D6E6462506EFD8EA9332AD9BC492A /* SizeExtensions.swift in Sources */, + BC5A53F94EAA2F46352749E54BE69838 /* Source.swift in Sources */, + FC4568452A01ACA7090C8B78CF6FFF5A /* Storage.swift in Sources */, + D7CB5610FA8E358DDBBCFC468EA56DAF /* String+MD5.swift in Sources */, + 26D320CBBB9394E2CD2AA967CF579315 /* TVMonogramView+Kingfisher.swift in Sources */, + DBD70DE28BDBC4B1C09EEBA3F6D76BF3 /* UIButton+Kingfisher.swift in Sources */, + 66411B211AAEB0C4DB6491A8AED6FEAF /* WKInterfaceImage+Kingfisher.swift in Sources */, + ); + runOnlyForDeploymentPostprocessing = 0; + }; + 502D4F95CF367F48D643967011501E21 /* Sources */ = { + isa = PBXSourcesBuildPhase; + buildActionMask = 2147483647; + files = ( + F3617B01FE1D713C9E39D57E32C905AE /* NibLoadable.swift in Sources */, + 1CFA21C851234CFA8841CF06A19CA1B3 /* NibOwnerLoadable.swift in Sources */, + A88B62F0F6C55645EE179934998FB6AC /* Reusable.swift in Sources */, + E6599DE13C01C6FA8F79536A8970DD3A /* Reusable-dummy.m in Sources */, + 820E300519E853EAC9E09ED6CC71EBDC /* StoryboardBased.swift in Sources */, + 4F894DAB31F1A68FD37EA61B87CDC043 /* StoryboardSceneBased.swift in Sources */, + DDC0F4786752FBF4B07E3A4D4E273DA2 /* UICollectionView+Reusable.swift in Sources */, + C79B457EA34AAC885AABAAB4FE227837 /* UITableView+Reusable.swift in Sources */, + ); + runOnlyForDeploymentPostprocessing = 0; + }; + 647BE045D378FFA99A884983B70E9E03 /* Sources */ = { + isa = PBXSourcesBuildPhase; + buildActionMask = 2147483647; + files = ( + 2A4D8872017458ADB952D7362CD3216D /* AddRef.swift in Sources */, + 96C658C96E9D8CCC2C450D5615A348AF /* Amb.swift in Sources */, + 61E63227D5A012BA17E37229455BA5B8 /* AnonymousDisposable.swift in Sources */, + 5150F2661A947E67A50557847BAA22C0 /* AnonymousObserver.swift in Sources */, + F2B61F23B613A4D92CE8459C4BE431BE /* AnyObserver.swift in Sources */, + A606B3D514262F030ED18600F01588BF /* AsMaybe.swift in Sources */, + 31E3621410AFFDD2DC866DAC48B735CE /* AsSingle.swift in Sources */, + AD635D9C6B76653B9049C2767A165CDC /* AsyncLock.swift in Sources */, + 3278ED404885BB1E20388250FC601681 /* AsyncSubject.swift in Sources */, + DB975FF8F6C9DE0D5B319961CAEDD4E1 /* AtomicInt.swift in Sources */, + 28A857C092C01D8BE7257A552DDDCD7F /* Bag.swift in Sources */, + 9D798263C35826FDE38859EFF5CC9542 /* Bag+Rx.swift in Sources */, + C39C9E0F5F4CB376E9C8286E5838B7DD /* BehaviorSubject.swift in Sources */, + AC3FB067C57DB569636CAFD05974F484 /* BinaryDisposable.swift in Sources */, + E424F89BEDDE19083BAAB0FA1D73E853 /* Binder.swift in Sources */, + ABD5C72702876EFB6C39BCC62269DED2 /* BooleanDisposable.swift in Sources */, + 42E7EEF0A33D83D355C821212F97A390 /* Buffer.swift in Sources */, + E154CD956DF116A1E59C8D6A6891A9BF /* Cancelable.swift in Sources */, + BBC7EE440D9B9A4B3511B1831C428A0D /* Catch.swift in Sources */, + D2032194EB7D200A1F6715A3C024D994 /* CombineLatest.swift in Sources */, + 2E9420467955EA6220D079A3678B4CCF /* CombineLatest+arity.swift in Sources */, + 598A8B5AC028B7EAFE6339965A063384 /* CombineLatest+Collection.swift in Sources */, + 196351F59003315C03DD17E9536AAD36 /* CompactMap.swift in Sources */, + AC5802EA58F43F1223804D5CF9E51A31 /* Completable.swift in Sources */, + DEBBCD7FF906F4D5F2CC4BF62F3A5803 /* Completable+AndThen.swift in Sources */, + 17A8E8E15AA453D69DEF72EA593C00CA /* CompositeDisposable.swift in Sources */, + 80F0B9ABC3E9D190B7A3C755A903EF54 /* Concat.swift in Sources */, + 444DBA6CD07054A7900CF1A1334419BC /* ConcurrentDispatchQueueScheduler.swift in Sources */, + 54A091154030EF2F51399D01C732D578 /* ConcurrentMainScheduler.swift in Sources */, + A473AE2DB5554BC6CB289664628012A5 /* ConnectableObservableType.swift in Sources */, + BFDCAD2AEBDD1AEF0345EE96D33DAC94 /* Create.swift in Sources */, + 12490402D5B61C9A226CBBDA0CC9AA23 /* CurrentThreadScheduler.swift in Sources */, + 42A1F6E790D900B1AC3653DBEFF8EAA6 /* Date+Dispatch.swift in Sources */, + 6DA16B11139D88B0C3BD21BF65790D34 /* Debounce.swift in Sources */, + FDE4F53FC806778F0FEE26810D359D79 /* Debug.swift in Sources */, + D525A536B7A32329405A34062C2BCED6 /* Decode.swift in Sources */, + 2742BB22F7F098635E8D99F6A6FF844A /* DefaultIfEmpty.swift in Sources */, + 2F7ECD73855CF5C4B91D44495A9D186D /* Deferred.swift in Sources */, + 5B0CD721D955D01B28AFE5291318A7DE /* Delay.swift in Sources */, + C00C4FF56C3B54CEB62ACA9DFB166FCD /* DelaySubscription.swift in Sources */, + 529BE65BAC3A56AB2FF74B26B63D3029 /* Dematerialize.swift in Sources */, + CEB12B808790BBA447EF912D41AB9C78 /* DispatchQueue+Extensions.swift in Sources */, + A766E407DA39FF588AEC62A4C30387A6 /* DispatchQueueConfiguration.swift in Sources */, + FA823A5BF5E118ADBC89B7CCD6B433A3 /* Disposable.swift in Sources */, + B53EB1446767571221ED954E16FDE1AA /* Disposables.swift in Sources */, + FDBC11E754B3FD24CE89D3587C34793D /* DisposeBag.swift in Sources */, + 16F9DEE85ECC94DE79B387073AC78AC7 /* DisposeBase.swift in Sources */, + 956ACEDE64971D2B3AE15D1EDAD4AB56 /* DistinctUntilChanged.swift in Sources */, + 2DAB889F1C979E0BDF2A951CF07F453E /* Do.swift in Sources */, + F79760816256C3B04E54319DA3A105E2 /* ElementAt.swift in Sources */, + 78EB4944F6EE0CF299F715B7340E19AB /* Empty.swift in Sources */, + 414CF2DE69210BDE0A1C0256F87E061A /* Enumerated.swift in Sources */, + 64986C72DEBFAB6607409ED2AC830D1E /* Error.swift in Sources */, + E65F73FA2E14351853CD4EB8729D0AC7 /* Errors.swift in Sources */, + 4965C451517127864A70BD41E0FA8AF9 /* Event.swift in Sources */, + 1A3A6D1CD56F36D4F2C74B4EA79967E7 /* Filter.swift in Sources */, + A61CDA7A9C259DC743A7553676B4E537 /* First.swift in Sources */, + 810421CBB613D2EA65E39D66C98C1B5A /* Generate.swift in Sources */, + F0D6C540C0CAEFE51A29FC9C5867096E /* GroupBy.swift in Sources */, + 20C99AA440645B161DCD0E6698F4A351 /* GroupedObservable.swift in Sources */, + 98CC71A93BBD481D6C77E99854E65282 /* HistoricalScheduler.swift in Sources */, + 7B81980B63BBD77A851BCD01FF160D44 /* HistoricalSchedulerTimeConverter.swift in Sources */, + 160F66863942DB8C996DB1D79984C7AD /* ImmediateSchedulerType.swift in Sources */, + 186E59D8CB5FC42AA40B9F8B1C0C27A5 /* Infallible.swift in Sources */, + 729183886B27549C5B666CC3F5C1B495 /* Infallible+CombineLatest+arity.swift in Sources */, + F0483870DE1B0E2DD94DAAA7287E46AD /* Infallible+Concurrency.swift in Sources */, + C20F7278CDDB5021D18140A001BA7470 /* Infallible+Create.swift in Sources */, + 6B4A32082CED69B110A83E603813FDB7 /* Infallible+Operators.swift in Sources */, + 0CB878167AA17431D1069C94A3EFF8F4 /* Infallible+Zip+arity.swift in Sources */, + FCA5D79BFD9CAE6F09CF2D9E4CCB7C9B /* InfiniteSequence.swift in Sources */, + 5223E292D90519A9F902F743DE388C22 /* InvocableScheduledItem.swift in Sources */, + 54EEEBA0AA7C4D84A5D0752813489F5F /* InvocableType.swift in Sources */, + 8BE63006C33671D8617303C1FBDF4AD0 /* Just.swift in Sources */, + B13CAD74E806387CF131495AD8CF453F /* Lock.swift in Sources */, + C46DF9765B3769C9EDA8BCC7052B6D23 /* LockOwnerType.swift in Sources */, + 362DD94616F8D1CA08A33B4F41273239 /* MainScheduler.swift in Sources */, + 89EE8751EC67604A80510F131F373127 /* Map.swift in Sources */, + 3957E07A50A304366C83854C41E6013B /* Materialize.swift in Sources */, + AACC3B4A90C3C71FEF3BB1C2FC0374F1 /* Maybe.swift in Sources */, + F2EF471EA98AA31CA53CEE65F76F151E /* Merge.swift in Sources */, + E3B0F5D520566D7244B300501D43F86E /* Multicast.swift in Sources */, + 8E6F33205BF126E6DECF929A32A98869 /* Never.swift in Sources */, + 10FF6AC524FAED0730F4BB577CF243B9 /* NopDisposable.swift in Sources */, + 97F63B52ED34F3A5A222C208253462F1 /* Observable.swift in Sources */, + 7542BDA803F84EC71005AE526659436A /* Observable+Concurrency.swift in Sources */, + F006EB7A9EF6612EE871EBBF1EE4655B /* ObservableConvertibleType.swift in Sources */, + AE64B504EC63283C3EEC47A88A0C5F43 /* ObservableConvertibleType+Infallible.swift in Sources */, + 3118CFD451916A9BB78E222597E8969E /* ObservableType.swift in Sources */, + BBDD1E970F7D15CEA5E1F39F47641664 /* ObservableType+Extensions.swift in Sources */, + 8951BE47D18264444C90F76B1695A1D0 /* ObservableType+PrimitiveSequence.swift in Sources */, + 094F725274CC4EC8EB2F0D2551C26019 /* ObserveOn.swift in Sources */, + B4BA49385319831FD3A3921DFCF76230 /* ObserverBase.swift in Sources */, + 0A7B97BD9262E628FCF5684C817D3D73 /* ObserverType.swift in Sources */, + 924E2F405AE00EDF695B3D926EB6BB1A /* OperationQueueScheduler.swift in Sources */, + 5357162246E301753EE5CBE40BF75038 /* Optional.swift in Sources */, + 753A064C58BBF2D833F709412D9E9FE3 /* Platform.Darwin.swift in Sources */, + FFEA28FE74753ABA9BDD87EDB46E5910 /* Platform.Linux.swift in Sources */, + DC4F588F90F6E49F9B67F0782B392E39 /* PrimitiveSequence.swift in Sources */, + 4BFFEA52EC61D92F315006DEB55CC6E5 /* PrimitiveSequence+Concurrency.swift in Sources */, + AEF083E81756E640AB92BFF5CC853355 /* PrimitiveSequence+Zip+arity.swift in Sources */, + B274128C2FE5EDE87850D4C9B996F4C8 /* PriorityQueue.swift in Sources */, + A9FB28DEC9FEAD03294A753F0C6A738B /* Producer.swift in Sources */, + 53F5DA7BA570018EFB8761D97C00DA6D /* PublishSubject.swift in Sources */, + B66C3C5709346F849100234EFCDB664E /* Queue.swift in Sources */, + C17A8818F6F518F4367C0C551782FB3B /* Range.swift in Sources */, + D507CB260B300128E39601CD83627509 /* Reactive.swift in Sources */, + 4D5E233A3AAB006B7EC565C74D18A8C1 /* RecursiveLock.swift in Sources */, + D73BED39648BD901FA022356FD6A4468 /* RecursiveScheduler.swift in Sources */, + 82747E86C0002A1A0BE8467C000C88F9 /* Reduce.swift in Sources */, + EBE8A06FA3C662A9D01320EF1FD0E120 /* RefCountDisposable.swift in Sources */, + A6D2F8EBCCEE6CE64FA4964877BF89F3 /* Repeat.swift in Sources */, + 1B9E805DAD08E186C49A07E76CE551F2 /* ReplaySubject.swift in Sources */, + F3ED4CDEB88F2CFB6AE17AEB4C59F210 /* RetryWhen.swift in Sources */, + D3318EE7E4339E6C5A6070D251DC845F /* Rx.swift in Sources */, + A2A423B6246A35EB8FB11B1924389E05 /* RxMutableBox.swift in Sources */, + 28F7BF27F82AD7A83B634F70E879ECFA /* RxSwift-dummy.m in Sources */, + 6339E0715C212DB48BD9F6A3FFD883DA /* Sample.swift in Sources */, + A549C0E0DBBD2D57F007FD6088F426BD /* Scan.swift in Sources */, + E895A8F95627AB1F7C2F1D7B035BAE1C /* ScheduledDisposable.swift in Sources */, + C812836F779AF53458795EEF5066F29A /* ScheduledItem.swift in Sources */, + 2CF7F5AEDD22D446868F6EC11694B46A /* ScheduledItemType.swift in Sources */, + ED3841B1E7CECC078D6BCDD78FDA7E36 /* SchedulerServices+Emulation.swift in Sources */, + B4AE9B23299C9CE3B70FAA7A66D50F7C /* SchedulerType.swift in Sources */, + E21CC70AD211E5F874C1208BA7D1631E /* Sequence.swift in Sources */, + 9FD204AB576F46B2AFA28B4074837ABC /* SerialDispatchQueueScheduler.swift in Sources */, + E54EA1C1B2B9304A9F7956AE0C9589D2 /* SerialDisposable.swift in Sources */, + AC8A2E59A2B5FFAD78AD95F4B053DB76 /* ShareReplayScope.swift in Sources */, + 4DDE90582DEB58DC0EF7BCC911D3BCBA /* Single.swift in Sources */, + A58048C722771C3C46C2623274174B7B /* SingleAssignmentDisposable.swift in Sources */, + B5E5A2CB9CD57723F8117D9402A80FD3 /* SingleAsync.swift in Sources */, + AF0C1DE86BD97C967EAD57DD459EDE65 /* Sink.swift in Sources */, + 1CBDD9F1C5BE4FAE59177A9E4E26ED68 /* Skip.swift in Sources */, + 13F86B00E27F85F2A19E7FC2D60032D3 /* SkipUntil.swift in Sources */, + CBF35F58D74E7F9E25EA97F82CBCEA10 /* SkipWhile.swift in Sources */, + 9EED5194D92B5A4B4E81FF9D6D98B7E0 /* StartWith.swift in Sources */, + 5FEA895A04C350A054C05410C2807F00 /* SubjectType.swift in Sources */, + D2C1DE6833F16A9EDEAE12D39DBBECD8 /* SubscribeOn.swift in Sources */, + 7E29FFE700C1C3AC047E58CC1E8EA468 /* SubscriptionDisposable.swift in Sources */, + A12579942726F0D2EC587B8ED74D6253 /* SwiftSupport.swift in Sources */, + 0E1A429FC9CD37AF039A2A19A0D018D9 /* Switch.swift in Sources */, + CDD0A0D9253EFF9923F92E89BC96A882 /* SwitchIfEmpty.swift in Sources */, + 76F608B4608884FCB00256FEF79A61E3 /* SynchronizedDisposeType.swift in Sources */, + CCADF670B558392F08CC5302CE8DFC34 /* SynchronizedOnType.swift in Sources */, + 5A8A82AA7F76A861CE989B801C506551 /* SynchronizedUnsubscribeType.swift in Sources */, + 8F1CD0744791BEC18F73D6FF3A150090 /* TailRecursiveSink.swift in Sources */, + 946AABD244DF0FA4F9BE1A018AF02D44 /* Take.swift in Sources */, + ED4155032D3BF65BD7B649E490A6EEFE /* TakeLast.swift in Sources */, + D4A79D2D2532673DF39ED456EB7005CF /* TakeWithPredicate.swift in Sources */, + 558B0B6DA4F450EB47428619840800E9 /* Throttle.swift in Sources */, + 514272471493DBBD026BC35D58547601 /* Timeout.swift in Sources */, + 23CB3C6D36D477A8DDBDA86ED0C29396 /* Timer.swift in Sources */, + E99A170AB4E460307ACAFC938CA2B591 /* ToArray.swift in Sources */, + 79F3A6E62579CE8906D3DA8B984347CC /* Using.swift in Sources */, + E4CA5C8A54DD0978858EE82D7D78ECB1 /* VirtualTimeConverterType.swift in Sources */, + D204501A876D178E882CF0D3CAA30473 /* VirtualTimeScheduler.swift in Sources */, + 2AF40AD9BAE58EECFEE829EF7996669B /* Window.swift in Sources */, + 6AFDE75A0DBBC5BB095963EFD1DBE944 /* WithLatestFrom.swift in Sources */, + E4AC5D4B5B930DDF6912483ED8436635 /* WithUnretained.swift in Sources */, + 24F54746A72C89AED62D33CF008D0BE1 /* Zip.swift in Sources */, + D072D375CE0C6D2F4A98A57FEEBF6BA2 /* Zip+arity.swift in Sources */, + F07878596C474719C556096025C2E9E4 /* Zip+Collection.swift in Sources */, + ); + runOnlyForDeploymentPostprocessing = 0; + }; + 7B7E69B2799BABEB7764F85296B591B7 /* Sources */ = { + isa = PBXSourcesBuildPhase; + buildActionMask = 2147483647; + files = ( + 6EAC8B6FA2D115DE708A58C601DD25E1 /* Constraint.swift in Sources */, + 0B994CDC79B1AD3A7BE62490D27C60C8 /* ConstraintAttributes.swift in Sources */, + 3660B4F629053ABC3C1DF69366770289 /* ConstraintConfig.swift in Sources */, + 9C9548E8B4675954566202F7B87FF0E6 /* ConstraintConstantTarget.swift in Sources */, + 5380454C48A12A6E376122ABD8096968 /* ConstraintDescription.swift in Sources */, + E98DC8FB2578E76A812E0C94BA10E1B1 /* ConstraintDirectionalInsets.swift in Sources */, + 04637C70546B34F93C3A1D79C3F78B37 /* ConstraintDirectionalInsetTarget.swift in Sources */, + 56AC6DC6459AE47E7BC4AF06E5B148D2 /* ConstraintDSL.swift in Sources */, + 604D3C93C17978C23600EC415949AB64 /* ConstraintInsets.swift in Sources */, + 9E02CFFEFE1BEC978B512286F03D31DA /* ConstraintInsetTarget.swift in Sources */, + 69DE75BA185BBAB5FDAA28321F3C849F /* ConstraintItem.swift in Sources */, + 611CEF7FF1EF9EA1BCEF6C73EEE3ACCF /* ConstraintLayoutGuide.swift in Sources */, + 6AC1B881BB319C89AD023A02CDC8FC3D /* ConstraintLayoutGuide+Extensions.swift in Sources */, + EF21586EC3DFF6097A58EEC87376A0C1 /* ConstraintLayoutGuideDSL.swift in Sources */, + 00A2749F46C967ED4725A32357E3FB1B /* ConstraintLayoutSupport.swift in Sources */, + 56A72F6D13D930C4A2568F24DEA33C8D /* ConstraintLayoutSupportDSL.swift in Sources */, + FAB03959C2357E325B19E08BC4775DAB /* ConstraintMaker.swift in Sources */, + 220D6AC9B1B1EC8EFFB204F9C1EAC842 /* ConstraintMakerEditable.swift in Sources */, + A5A8BF973BFE9C9304372A26C9F2E35B /* ConstraintMakerExtendable.swift in Sources */, + 42B6ACFCF650183030867CB3EF345E95 /* ConstraintMakerFinalizable.swift in Sources */, + B43017FEC99D227D4CDD81DD2C27D9D9 /* ConstraintMakerPrioritizable.swift in Sources */, + 183D8B3E057B885EA7DF9A8CDCCE9029 /* ConstraintMakerRelatable.swift in Sources */, + 95E194A3AABB5407231E898B6686F73E /* ConstraintMakerRelatable+Extensions.swift in Sources */, + F7C0960CEEB8F0C18F4503B405EAC08F /* ConstraintMultiplierTarget.swift in Sources */, + A03FDA8BC5741880B1EF11AFD248EF48 /* ConstraintOffsetTarget.swift in Sources */, + 06E43B4751069B47B3BD4AFD936A57E3 /* ConstraintPriority.swift in Sources */, + 4DA72FD7F1FB2C0449EDEF4B8A579807 /* ConstraintPriorityTarget.swift in Sources */, + 55E51F45F1E157D3B4942BA7252C277E /* ConstraintRelatableTarget.swift in Sources */, + 4BAD99B7394E225CEDBF94B8100BCC7F /* ConstraintRelation.swift in Sources */, + B752F7C4BECB65894B1F49421049CE5F /* ConstraintView.swift in Sources */, + F953AA9104BFE0C2DAD639EA60104A75 /* ConstraintView+Extensions.swift in Sources */, + 256558233B40ACA6818F143BBC5B8017 /* ConstraintViewDSL.swift in Sources */, + 5D36B99F3CAB1FC7337082D9581FECA6 /* Debugging.swift in Sources */, + 0591132B5EA1BE4DDA268D8A9C3D0421 /* LayoutConstraint.swift in Sources */, + 98F570DA48370453D648BD526FDAAEAA /* LayoutConstraintItem.swift in Sources */, + BD47CB74CD9B2B4D2D942C9B65748DFB /* SnapKit-dummy.m in Sources */, + B03B5579590D528CBA6D11FF638BC2AF /* Typealiases.swift in Sources */, + 38B9D58E94D9C1CECD7E381C64A2329D /* UILayoutSupport+Extensions.swift in Sources */, + ); + runOnlyForDeploymentPostprocessing = 0; + }; + 7E957D4020E4C4BC633BF50F7F51E5F6 /* Sources */ = { + isa = PBXSourcesBuildPhase; + buildActionMask = 2147483647; + files = ( + 0097064E7F7D3F413161738CC5C25EEC /* MBProgressHUD.m in Sources */, + 58C91B4AB36E6B16421106CA634C58EF /* MBProgressHUD-dummy.m in Sources */, + ); + runOnlyForDeploymentPostprocessing = 0; + }; + B186292004011247A56FAC41B9D6C6A2 /* Sources */ = { + isa = PBXSourcesBuildPhase; + buildActionMask = 2147483647; + files = ( + 123E6BAD784E74477DC5B5CFF0272759 /* AnyExtensions.swift in Sources */, + 24658CFD39BCB4586D56C427F8EA751D /* BuiltInBasicType.swift in Sources */, + 3C53583CB1A5F4926491D8838F580074 /* BuiltInBridgeType.swift in Sources */, + ED71E932B7F30AD7CFD2A04968A2B5CC /* CBridge.swift in Sources */, + 798C7D29511D498BDB7BEC4996708557 /* Configuration.swift in Sources */, + CF7FAB0C5D474E379798F82E5DB4092B /* ContextDescriptorType.swift in Sources */, + 309C54EC9536180B960B9CB8EBD412E3 /* CustomDateFormatTransform.swift in Sources */, + 0F4D0B7B522466B970AA826F57343EFF /* DataTransform.swift in Sources */, + 7D9031DCB898CD9DE37C4BD4F3FC550D /* DateFormatterTransform.swift in Sources */, + E7035A074129575E62A0136DD93D8E8F /* DateTransform.swift in Sources */, + 361EA7ABBDD80F154DDC208D9CE920DD /* Deserializer.swift in Sources */, + F16D0BB1231D60CBF7B3AE25B92D0D74 /* EnumTransform.swift in Sources */, + 2878735FE61E1EEB4C493A8B8ED3DCAC /* EnumType.swift in Sources */, + 8C3394695CB4CCECD873D1384F4BA076 /* Export.swift in Sources */, + 19BB09AF94BD545E40C2766045BDDD77 /* ExtendCustomBasicType.swift in Sources */, + A0E5EC9E431A5BD01C4695BC6AE5DEDA /* ExtendCustomModelType.swift in Sources */, + F7425A58E24926CCAC413F85D403B9FA /* FieldDescriptor.swift in Sources */, + BE432D00488E08C853DC689BE24C54F4 /* HandyJSON-dummy.m in Sources */, + 8CD5DE204C3C5F6557878ADE2675A406 /* HelpingMapper.swift in Sources */, + 3A030CA5A4DD41F59802F907A93F85DF /* HexColorTransform.swift in Sources */, + F98E3202B0021DC8B2DB77256FBE5DD3 /* ISO8601DateTransform.swift in Sources */, + E710A550162879CE918FC411CF567789 /* Logger.swift in Sources */, + 33BC540DE351661FAAA24950E165D4F1 /* MangledName.swift in Sources */, + 56CAC06DB79E51F4ED416927D57C79A9 /* Measuable.swift in Sources */, + E2EF09A2D0A87418F0628B2CFAD304D8 /* Metadata.swift in Sources */, + A674A2F3F5F0304A6524F702EA301B42 /* NSDecimalNumberTransform.swift in Sources */, + 1B14ABB3EBE1CF1E69D4E393ADE3E9E4 /* OtherExtension.swift in Sources */, + 02560F1312F13EF15E0EB5FA952C9A48 /* PointerType.swift in Sources */, + 79C7D4E9901AA11C25F8C71F3E9DF612 /* Properties.swift in Sources */, + 8D72B695C7EF0186A0C0F1A18F944880 /* PropertyInfo.swift in Sources */, + 61FCA0616CE6512DCA67D74562D6EA1D /* ReflectionHelper.swift in Sources */, + 044973538553B114516678D144E318CA /* Serializer.swift in Sources */, + 96D8402B4AFC4AC7349F1B487D6EB08C /* Transformable.swift in Sources */, + 78079FE3271F118CE83CFD8D5E4F8C21 /* TransformOf.swift in Sources */, + 846C97A8C420EFD9B8C4B77ADBB1E8F5 /* TransformType.swift in Sources */, + 62C1A489E5C6414819815F3219B52FE8 /* URLTransform.swift in Sources */, + ); + runOnlyForDeploymentPostprocessing = 0; + }; + B61519DD991056A1D585A34B6FA1D19C /* Sources */ = { + isa = PBXSourcesBuildPhase; + buildActionMask = 2147483647; + files = ( + 0DA0657F0B4D4AF03048C3F0591C5F07 /* Pods-yinmeng-ios-dummy.m in Sources */, + ); + runOnlyForDeploymentPostprocessing = 0; + }; + B9C4339E494FCDEDF339AE80CF8263B3 /* Sources */ = { + isa = PBXSourcesBuildPhase; + buildActionMask = 2147483647; + files = ( + ); + runOnlyForDeploymentPostprocessing = 0; + }; + D21AEE57BB74E8BE2A5ABEE23432A806 /* Sources */ = { + isa = PBXSourcesBuildPhase; + buildActionMask = 2147483647; + files = ( + E0D995EBFD58A33805684F01024138E7 /* BehaviorRelay.swift in Sources */, + 2F29E8F0615655488301B37DCCE74DD2 /* Observable+Bind.swift in Sources */, + 0A50200D02E79569C5EAFEDE5448DEA8 /* PublishRelay.swift in Sources */, + 5BA418EFF060B7BEFDAF9B3E1E56ED4E /* ReplayRelay.swift in Sources */, + 0024FB3EA4398F0CCE435DF4134077AB /* RxRelay-dummy.m in Sources */, + C538C2B3F5A5D6BA85BBDCB544777AD4 /* Utils.swift in Sources */, + ); + runOnlyForDeploymentPostprocessing = 0; + }; +/* End PBXSourcesBuildPhase section */ + +/* Begin PBXTargetDependency section */ + 129B8D6EDBC0E697BF55B3C8FE0FE1A6 /* PBXTargetDependency */ = { + isa = PBXTargetDependency; + name = RxSwift; + target = EA9EA43B3B503823EE36C60D9C8A865F /* RxSwift */; + targetProxy = 4C27EC4B5188F89173A9C29D169E0032 /* PBXContainerItemProxy */; + }; + 19677A4C977E43BF6FDC659077FF8F64 /* PBXTargetDependency */ = { + isa = PBXTargetDependency; + name = SnapKit; + target = 19622742EBA51E823D6DAE3F8CDBFAD4 /* SnapKit */; + targetProxy = 6FE4ADF80639F6BB7A8166750DAACBCB /* PBXContainerItemProxy */; + }; + 294D4F167509B367133479F70C99FAAE /* PBXTargetDependency */ = { + isa = PBXTargetDependency; + name = Alamofire; + target = EAAA1AD3A8A1B59AB91319EE40752C6D /* Alamofire */; + targetProxy = 72174616F0F2B6A658A39627B9B3AB27 /* PBXContainerItemProxy */; + }; + 41D57993E84517CD638C70ADEC5E44C6 /* PBXTargetDependency */ = { + isa = PBXTargetDependency; + name = RxSwift; + target = EA9EA43B3B503823EE36C60D9C8A865F /* RxSwift */; + targetProxy = 9453D1A2DED6629FB2E6B2F47B5861EC /* PBXContainerItemProxy */; + }; + 7AB2CEB2384A2E610A19A45C46C38838 /* PBXTargetDependency */ = { + isa = PBXTargetDependency; + name = Kingfisher; + target = E8022D22FAA6690B5E1C379C1BCE1491 /* Kingfisher */; + targetProxy = D55789695C0CB9279A0E694653D0BE12 /* PBXContainerItemProxy */; + }; + 861D671FE3252AAF9F3546CB1B7E113C /* PBXTargetDependency */ = { + isa = PBXTargetDependency; + name = Alamofire; + target = EAAA1AD3A8A1B59AB91319EE40752C6D /* Alamofire */; + targetProxy = D7630C5D5DEF74799EEF3A89A7518F08 /* PBXContainerItemProxy */; + }; + 94F1664E9E64C92DEFB0970E1925F652 /* PBXTargetDependency */ = { + isa = PBXTargetDependency; + name = MBProgressHUD; + target = 82B0A41D3031FF27D78E17B0A9A46FB0 /* MBProgressHUD */; + targetProxy = 2945BE7CD469F91A2F51C450AFA05666 /* PBXContainerItemProxy */; + }; + 9A711F5A31AD64A8B5050478F04948AD /* PBXTargetDependency */ = { + isa = PBXTargetDependency; + name = Moya; + target = 17F9141D333DA1A7BE5937F227221070 /* Moya */; + targetProxy = 1658A2BFA314B61B2A73634AD62CE881 /* PBXContainerItemProxy */; + }; + 9D46F8983711587F027876C6D9483255 /* PBXTargetDependency */ = { + isa = PBXTargetDependency; + name = HandyJSON; + target = 10D88C24864319FF583AD6D156896F32 /* HandyJSON */; + targetProxy = FF15280D6E3817C68943D4D47FCE6488 /* PBXContainerItemProxy */; + }; + AAA859713D3E1B87E847AD768604A711 /* PBXTargetDependency */ = { + isa = PBXTargetDependency; + name = RxSwift; + target = EA9EA43B3B503823EE36C60D9C8A865F /* RxSwift */; + targetProxy = B250CBDA21743BA7F971FA3FFEF57DAA /* PBXContainerItemProxy */; + }; + BB9A3FAEC46882D1BE980F96D535919F /* PBXTargetDependency */ = { + isa = PBXTargetDependency; + name = RxRelay; + target = 4622BFEF3DC16E8BD15EEFC30D4D0084 /* RxRelay */; + targetProxy = DB1DC5BEA8CCBF1B3FD2396BBBEC7A93 /* PBXContainerItemProxy */; + }; + D7BCCB438C6783D4AD34AFA01C3017E2 /* PBXTargetDependency */ = { + isa = PBXTargetDependency; + name = RxCocoa; + target = 7AD0C6DCDC9CEC8A3C7C10C7FEE07BE6 /* RxCocoa */; + targetProxy = 374C7A97590E5FE0A51BFBBD65FB78D1 /* PBXContainerItemProxy */; + }; + D9B00D70E911FF84772D30A6F17F24C2 /* PBXTargetDependency */ = { + isa = PBXTargetDependency; + name = RxRelay; + target = 4622BFEF3DC16E8BD15EEFC30D4D0084 /* RxRelay */; + targetProxy = 304B703E396722BB916969650EE3ECE3 /* PBXContainerItemProxy */; + }; + E7FE09331A2C0535926E5A346DDFE0AB /* PBXTargetDependency */ = { + isa = PBXTargetDependency; + name = "Kingfisher-Kingfisher"; + target = 9828BBC09E9FB1238624113D7456E59E /* Kingfisher-Kingfisher */; + targetProxy = A699C0A386EEF6602AED63A3F0386D29 /* PBXContainerItemProxy */; + }; + F6A63E96803B3C03A914736028E41D5E /* PBXTargetDependency */ = { + isa = PBXTargetDependency; + name = Reusable; + target = 542460E7CDF2A9D5B2ECB5F8CE549E34 /* Reusable */; + targetProxy = 355C8F2CEBF2108145CF958E67525E6C /* PBXContainerItemProxy */; + }; +/* End PBXTargetDependency section */ + +/* Begin XCBuildConfiguration section */ + 166E9C881152A0BEAAF3B03A4FCB9878 /* Release */ = { + isa = XCBuildConfiguration; + baseConfigurationReference = 19B712EE8F117D2EC35F9A295028959B /* RxSwift.release.xcconfig */; + buildSettings = { + "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/RxSwift/RxSwift-prefix.pch"; + INFOPLIST_FILE = "Target Support Files/RxSwift/RxSwift-Info.plist"; + INSTALL_PATH = "$(LOCAL_LIBRARY_DIR)/Frameworks"; + IPHONEOS_DEPLOYMENT_TARGET = 9.0; + LD_RUNPATH_SEARCH_PATHS = ( + "$(inherited)", + "@executable_path/Frameworks", + "@loader_path/Frameworks", + ); + MODULEMAP_FILE = "Target Support Files/RxSwift/RxSwift.modulemap"; + PRODUCT_MODULE_NAME = RxSwift; + PRODUCT_NAME = RxSwift; + SDKROOT = iphoneos; + SKIP_INSTALL = YES; + SWIFT_ACTIVE_COMPILATION_CONDITIONS = "$(inherited) "; + SWIFT_VERSION = 5.1; + TARGETED_DEVICE_FAMILY = "1,2"; + VALIDATE_PRODUCT = YES; + VERSIONING_SYSTEM = "apple-generic"; + VERSION_INFO_PREFIX = ""; + }; + name = Release; + }; + 195F1AC8F6BD95FEFB9983CAC195FCAE /* Release */ = { + isa = XCBuildConfiguration; + baseConfigurationReference = 93BD071E578B69235CCADBFBE9FBAA1B /* Kingfisher.release.xcconfig */; + buildSettings = { + CLANG_ENABLE_OBJC_WEAK = NO; + "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/Kingfisher/Kingfisher-prefix.pch"; + INFOPLIST_FILE = "Target Support Files/Kingfisher/Kingfisher-Info.plist"; + INSTALL_PATH = "$(LOCAL_LIBRARY_DIR)/Frameworks"; + IPHONEOS_DEPLOYMENT_TARGET = 12.0; + LD_RUNPATH_SEARCH_PATHS = ( + "$(inherited)", + "@executable_path/Frameworks", + "@loader_path/Frameworks", + ); + MODULEMAP_FILE = "Target Support Files/Kingfisher/Kingfisher.modulemap"; + PRODUCT_MODULE_NAME = Kingfisher; + PRODUCT_NAME = Kingfisher; + SDKROOT = iphoneos; + SKIP_INSTALL = YES; + SWIFT_ACTIVE_COMPILATION_CONDITIONS = "$(inherited) "; + SWIFT_VERSION = 5.0; + TARGETED_DEVICE_FAMILY = "1,2"; + VALIDATE_PRODUCT = YES; + VERSIONING_SYSTEM = "apple-generic"; + VERSION_INFO_PREFIX = ""; + }; + name = Release; + }; + 1ABF49ADDB0430B6FFCC63A8184EACA2 /* Release */ = { + isa = XCBuildConfiguration; + baseConfigurationReference = 649D2F79A4B50006D2A9D93E21022944 /* Moya.release.xcconfig */; + buildSettings = { + CLANG_ENABLE_OBJC_WEAK = NO; + "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/Moya/Moya-prefix.pch"; + INFOPLIST_FILE = "Target Support Files/Moya/Moya-Info.plist"; + INSTALL_PATH = "$(LOCAL_LIBRARY_DIR)/Frameworks"; + IPHONEOS_DEPLOYMENT_TARGET = 10.0; + LD_RUNPATH_SEARCH_PATHS = ( + "$(inherited)", + "@executable_path/Frameworks", + "@loader_path/Frameworks", + ); + MODULEMAP_FILE = "Target Support Files/Moya/Moya.modulemap"; + PRODUCT_MODULE_NAME = Moya; + PRODUCT_NAME = Moya; + SDKROOT = iphoneos; + SKIP_INSTALL = YES; + SWIFT_ACTIVE_COMPILATION_CONDITIONS = "$(inherited) "; + SWIFT_VERSION = 5.3; + TARGETED_DEVICE_FAMILY = "1,2"; + VALIDATE_PRODUCT = YES; + VERSIONING_SYSTEM = "apple-generic"; + VERSION_INFO_PREFIX = ""; + }; + name = Release; + }; + 2D9905F00DBA0E0A2C139BAFDE426559 /* Release */ = { + isa = XCBuildConfiguration; + baseConfigurationReference = C71988E85D3858110A6CEEF81B0B0CBE /* Reusable.release.xcconfig */; + buildSettings = { + "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/Reusable/Reusable-prefix.pch"; + INFOPLIST_FILE = "Target Support Files/Reusable/Reusable-Info.plist"; + INSTALL_PATH = "$(LOCAL_LIBRARY_DIR)/Frameworks"; + IPHONEOS_DEPLOYMENT_TARGET = 9.0; + LD_RUNPATH_SEARCH_PATHS = ( + "$(inherited)", + "@executable_path/Frameworks", + "@loader_path/Frameworks", + ); + MODULEMAP_FILE = "Target Support Files/Reusable/Reusable.modulemap"; + PRODUCT_MODULE_NAME = Reusable; + PRODUCT_NAME = Reusable; + SDKROOT = iphoneos; + SKIP_INSTALL = YES; + SWIFT_ACTIVE_COMPILATION_CONDITIONS = "$(inherited) "; + SWIFT_VERSION = 5.0; + TARGETED_DEVICE_FAMILY = "1,2"; + VALIDATE_PRODUCT = YES; + VERSIONING_SYSTEM = "apple-generic"; + VERSION_INFO_PREFIX = ""; + }; + name = Release; + }; + 5614F562617D1EE7A1A60E422C2D007A /* Debug */ = { + isa = XCBuildConfiguration; + baseConfigurationReference = 03B41EBBD593C680744DAD960E245F91 /* Reusable.debug.xcconfig */; + buildSettings = { + "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/Reusable/Reusable-prefix.pch"; + INFOPLIST_FILE = "Target Support Files/Reusable/Reusable-Info.plist"; + INSTALL_PATH = "$(LOCAL_LIBRARY_DIR)/Frameworks"; + IPHONEOS_DEPLOYMENT_TARGET = 9.0; + LD_RUNPATH_SEARCH_PATHS = ( + "$(inherited)", + "@executable_path/Frameworks", + "@loader_path/Frameworks", + ); + MODULEMAP_FILE = "Target Support Files/Reusable/Reusable.modulemap"; + PRODUCT_MODULE_NAME = Reusable; + PRODUCT_NAME = Reusable; + SDKROOT = iphoneos; + SKIP_INSTALL = YES; + SWIFT_ACTIVE_COMPILATION_CONDITIONS = "$(inherited) "; + SWIFT_VERSION = 5.0; + TARGETED_DEVICE_FAMILY = "1,2"; + VERSIONING_SYSTEM = "apple-generic"; + VERSION_INFO_PREFIX = ""; + }; + name = Debug; + }; + 577A24D81FA00BED9154F445BE58F743 /* Release */ = { + isa = XCBuildConfiguration; + baseConfigurationReference = 63CF3F8FFB207D7C17E8DB9CB93EDA1E /* RxCocoa.release.xcconfig */; + buildSettings = { + "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/RxCocoa/RxCocoa-prefix.pch"; + INFOPLIST_FILE = "Target Support Files/RxCocoa/RxCocoa-Info.plist"; + INSTALL_PATH = "$(LOCAL_LIBRARY_DIR)/Frameworks"; + IPHONEOS_DEPLOYMENT_TARGET = 9.0; + LD_RUNPATH_SEARCH_PATHS = ( + "$(inherited)", + "@executable_path/Frameworks", + "@loader_path/Frameworks", + ); + MODULEMAP_FILE = "Target Support Files/RxCocoa/RxCocoa.modulemap"; + PRODUCT_MODULE_NAME = RxCocoa; + PRODUCT_NAME = RxCocoa; + SDKROOT = iphoneos; + SKIP_INSTALL = YES; + SWIFT_ACTIVE_COMPILATION_CONDITIONS = "$(inherited) "; + SWIFT_VERSION = 5.1; + TARGETED_DEVICE_FAMILY = "1,2"; + VALIDATE_PRODUCT = YES; + VERSIONING_SYSTEM = "apple-generic"; + VERSION_INFO_PREFIX = ""; + }; + name = Release; + }; + 614A05FBF51042DF76C96CCD248FB774 /* Release */ = { + isa = XCBuildConfiguration; + baseConfigurationReference = 6C4BAD710FAA4AE5F73353998A04A650 /* Pods-yinmeng-ios.release.xcconfig */; + buildSettings = { + ALWAYS_EMBED_SWIFT_STANDARD_LIBRARIES = NO; + CLANG_ENABLE_OBJC_WEAK = NO; + "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-yinmeng-ios/Pods-yinmeng-ios-Info.plist"; + INSTALL_PATH = "$(LOCAL_LIBRARY_DIR)/Frameworks"; + IPHONEOS_DEPLOYMENT_TARGET = 13.0; + LD_RUNPATH_SEARCH_PATHS = ( + "$(inherited)", + "@executable_path/Frameworks", + "@loader_path/Frameworks", + ); + MACH_O_TYPE = staticlib; + MODULEMAP_FILE = "Target Support Files/Pods-yinmeng-ios/Pods-yinmeng-ios.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; + TARGETED_DEVICE_FAMILY = "1,2"; + VALIDATE_PRODUCT = YES; + VERSIONING_SYSTEM = "apple-generic"; + VERSION_INFO_PREFIX = ""; + }; + name = Release; + }; + 74FCF40A76D1E62C63837B25FCE9F45D /* Release */ = { + isa = XCBuildConfiguration; + baseConfigurationReference = 1A9CF67CD4186CDC93B9439A7C72E036 /* HandyJSON.release.xcconfig */; + buildSettings = { + "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/HandyJSON/HandyJSON-prefix.pch"; + INFOPLIST_FILE = "Target Support Files/HandyJSON/HandyJSON-Info.plist"; + INSTALL_PATH = "$(LOCAL_LIBRARY_DIR)/Frameworks"; + IPHONEOS_DEPLOYMENT_TARGET = 13.0; + LD_RUNPATH_SEARCH_PATHS = ( + "$(inherited)", + "@executable_path/Frameworks", + "@loader_path/Frameworks", + ); + MODULEMAP_FILE = "Target Support Files/HandyJSON/HandyJSON.modulemap"; + PRODUCT_MODULE_NAME = HandyJSON; + PRODUCT_NAME = HandyJSON; + SDKROOT = iphoneos; + SKIP_INSTALL = YES; + SWIFT_ACTIVE_COMPILATION_CONDITIONS = "$(inherited) "; + TARGETED_DEVICE_FAMILY = "1,2"; + VALIDATE_PRODUCT = YES; + VERSIONING_SYSTEM = "apple-generic"; + VERSION_INFO_PREFIX = ""; + }; + name = Release; + }; + 8C925430B65BE03F92ABCD1B2005EE0C /* Release */ = { + isa = XCBuildConfiguration; + baseConfigurationReference = 74A65654283AE2CF4A3DFA265199F1C5 /* SnapKit.release.xcconfig */; + buildSettings = { + CLANG_ENABLE_OBJC_WEAK = NO; + "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/SnapKit/SnapKit-prefix.pch"; + INFOPLIST_FILE = "Target Support Files/SnapKit/SnapKit-Info.plist"; + INSTALL_PATH = "$(LOCAL_LIBRARY_DIR)/Frameworks"; + IPHONEOS_DEPLOYMENT_TARGET = 10.0; + LD_RUNPATH_SEARCH_PATHS = ( + "$(inherited)", + "@executable_path/Frameworks", + "@loader_path/Frameworks", + ); + MODULEMAP_FILE = "Target Support Files/SnapKit/SnapKit.modulemap"; + PRODUCT_MODULE_NAME = SnapKit; + PRODUCT_NAME = SnapKit; + SDKROOT = iphoneos; + SKIP_INSTALL = YES; + SWIFT_ACTIVE_COMPILATION_CONDITIONS = "$(inherited) "; + SWIFT_VERSION = 5.0; + TARGETED_DEVICE_FAMILY = "1,2"; + VALIDATE_PRODUCT = YES; + VERSIONING_SYSTEM = "apple-generic"; + VERSION_INFO_PREFIX = ""; + }; + name = Release; + }; + 8DE5143C03248BB6CD542DE3963D6F3A /* Debug */ = { + isa = XCBuildConfiguration; + buildSettings = { + ALWAYS_SEARCH_USER_PATHS = NO; + CLANG_ANALYZER_LOCALIZABILITY_NONLOCALIZED = YES; + 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_QUOTED_INCLUDE_IN_FRAMEWORK_HEADER = YES; + 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; + 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 = 13.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; + SWIFT_OPTIMIZATION_LEVEL = "-Onone"; + SWIFT_VERSION = 5.0; + SYMROOT = "${SRCROOT}/../build"; + }; + name = Debug; + }; + 960DBC77E1DF531EDC9D62CD1E847BA2 /* Debug */ = { + isa = XCBuildConfiguration; + baseConfigurationReference = 537B39F9D626350F9BD4A28C6DF455B6 /* RxSwift.debug.xcconfig */; + buildSettings = { + "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/RxSwift/RxSwift-prefix.pch"; + INFOPLIST_FILE = "Target Support Files/RxSwift/RxSwift-Info.plist"; + INSTALL_PATH = "$(LOCAL_LIBRARY_DIR)/Frameworks"; + IPHONEOS_DEPLOYMENT_TARGET = 9.0; + LD_RUNPATH_SEARCH_PATHS = ( + "$(inherited)", + "@executable_path/Frameworks", + "@loader_path/Frameworks", + ); + MODULEMAP_FILE = "Target Support Files/RxSwift/RxSwift.modulemap"; + PRODUCT_MODULE_NAME = RxSwift; + PRODUCT_NAME = RxSwift; + SDKROOT = iphoneos; + SKIP_INSTALL = YES; + SWIFT_ACTIVE_COMPILATION_CONDITIONS = "$(inherited) "; + SWIFT_VERSION = 5.1; + TARGETED_DEVICE_FAMILY = "1,2"; + VERSIONING_SYSTEM = "apple-generic"; + VERSION_INFO_PREFIX = ""; + }; + name = Debug; + }; + 9E406C6AAF85E580207CD97B0044DEAB /* Release */ = { + isa = XCBuildConfiguration; + buildSettings = { + ALWAYS_SEARCH_USER_PATHS = NO; + CLANG_ANALYZER_LOCALIZABILITY_NONLOCALIZED = YES; + 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_QUOTED_INCLUDE_IN_FRAMEWORK_HEADER = YES; + 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; + 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 = 13.0; + MTL_ENABLE_DEBUG_INFO = NO; + MTL_FAST_MATH = YES; + PRODUCT_NAME = "$(TARGET_NAME)"; + STRIP_INSTALLED_PRODUCT = NO; + SWIFT_COMPILATION_MODE = wholemodule; + SWIFT_OPTIMIZATION_LEVEL = "-O"; + SWIFT_VERSION = 5.0; + SYMROOT = "${SRCROOT}/../build"; + }; + name = Release; + }; + A6974CAC511C0AC2C4BED7CA1BB9D70C /* Debug */ = { + isa = XCBuildConfiguration; + baseConfigurationReference = C7CE4D7E07321EBA8053DBEF4867408A /* Pods-yinmeng-ios.debug.xcconfig */; + buildSettings = { + ALWAYS_EMBED_SWIFT_STANDARD_LIBRARIES = NO; + CLANG_ENABLE_OBJC_WEAK = NO; + "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-yinmeng-ios/Pods-yinmeng-ios-Info.plist"; + INSTALL_PATH = "$(LOCAL_LIBRARY_DIR)/Frameworks"; + IPHONEOS_DEPLOYMENT_TARGET = 13.0; + LD_RUNPATH_SEARCH_PATHS = ( + "$(inherited)", + "@executable_path/Frameworks", + "@loader_path/Frameworks", + ); + MACH_O_TYPE = staticlib; + MODULEMAP_FILE = "Target Support Files/Pods-yinmeng-ios/Pods-yinmeng-ios.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; + TARGETED_DEVICE_FAMILY = "1,2"; + VERSIONING_SYSTEM = "apple-generic"; + VERSION_INFO_PREFIX = ""; + }; + name = Debug; + }; + A6F0173BAEB974532D93E05E5A94E50A /* Debug */ = { + isa = XCBuildConfiguration; + baseConfigurationReference = AA050A692C8C8C04436B0CB1E5317D3A /* SnapKit.debug.xcconfig */; + buildSettings = { + CLANG_ENABLE_OBJC_WEAK = NO; + "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/SnapKit/SnapKit-prefix.pch"; + INFOPLIST_FILE = "Target Support Files/SnapKit/SnapKit-Info.plist"; + INSTALL_PATH = "$(LOCAL_LIBRARY_DIR)/Frameworks"; + IPHONEOS_DEPLOYMENT_TARGET = 10.0; + LD_RUNPATH_SEARCH_PATHS = ( + "$(inherited)", + "@executable_path/Frameworks", + "@loader_path/Frameworks", + ); + MODULEMAP_FILE = "Target Support Files/SnapKit/SnapKit.modulemap"; + PRODUCT_MODULE_NAME = SnapKit; + PRODUCT_NAME = SnapKit; + SDKROOT = iphoneos; + SKIP_INSTALL = YES; + SWIFT_ACTIVE_COMPILATION_CONDITIONS = "$(inherited) "; + SWIFT_VERSION = 5.0; + TARGETED_DEVICE_FAMILY = "1,2"; + VERSIONING_SYSTEM = "apple-generic"; + VERSION_INFO_PREFIX = ""; + }; + name = Debug; + }; + B7D9E7CD650F798EC835C67DACFEBC4F /* Debug */ = { + isa = XCBuildConfiguration; + baseConfigurationReference = 19D15B6F087615D6E6964610E2461AAD /* Alamofire.debug.xcconfig */; + buildSettings = { + CLANG_ENABLE_OBJC_WEAK = NO; + "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/Alamofire-Info.plist"; + INSTALL_PATH = "$(LOCAL_LIBRARY_DIR)/Frameworks"; + IPHONEOS_DEPLOYMENT_TARGET = 10.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_VERSION = 5; + TARGETED_DEVICE_FAMILY = "1,2"; + VERSIONING_SYSTEM = "apple-generic"; + VERSION_INFO_PREFIX = ""; + }; + name = Debug; + }; + BC856BC9A4C1242C1AFA559E24FF0568 /* Debug */ = { + isa = XCBuildConfiguration; + baseConfigurationReference = 43A9212FF806B13E885C7019E059D160 /* Kingfisher.debug.xcconfig */; + buildSettings = { + CLANG_ENABLE_OBJC_WEAK = NO; + "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/Kingfisher/Kingfisher-prefix.pch"; + INFOPLIST_FILE = "Target Support Files/Kingfisher/Kingfisher-Info.plist"; + INSTALL_PATH = "$(LOCAL_LIBRARY_DIR)/Frameworks"; + IPHONEOS_DEPLOYMENT_TARGET = 12.0; + LD_RUNPATH_SEARCH_PATHS = ( + "$(inherited)", + "@executable_path/Frameworks", + "@loader_path/Frameworks", + ); + MODULEMAP_FILE = "Target Support Files/Kingfisher/Kingfisher.modulemap"; + PRODUCT_MODULE_NAME = Kingfisher; + PRODUCT_NAME = Kingfisher; + SDKROOT = iphoneos; + SKIP_INSTALL = YES; + SWIFT_ACTIVE_COMPILATION_CONDITIONS = "$(inherited) "; + SWIFT_VERSION = 5.0; + TARGETED_DEVICE_FAMILY = "1,2"; + VERSIONING_SYSTEM = "apple-generic"; + VERSION_INFO_PREFIX = ""; + }; + name = Debug; + }; + C12D9C5CC8F2071662A98F549A9E6FB4 /* Debug */ = { + isa = XCBuildConfiguration; + baseConfigurationReference = D4F121F8F3564995DB1C8EEF45128BEC /* RxCocoa.debug.xcconfig */; + buildSettings = { + "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/RxCocoa/RxCocoa-prefix.pch"; + INFOPLIST_FILE = "Target Support Files/RxCocoa/RxCocoa-Info.plist"; + INSTALL_PATH = "$(LOCAL_LIBRARY_DIR)/Frameworks"; + IPHONEOS_DEPLOYMENT_TARGET = 9.0; + LD_RUNPATH_SEARCH_PATHS = ( + "$(inherited)", + "@executable_path/Frameworks", + "@loader_path/Frameworks", + ); + MODULEMAP_FILE = "Target Support Files/RxCocoa/RxCocoa.modulemap"; + PRODUCT_MODULE_NAME = RxCocoa; + PRODUCT_NAME = RxCocoa; + SDKROOT = iphoneos; + SKIP_INSTALL = YES; + SWIFT_ACTIVE_COMPILATION_CONDITIONS = "$(inherited) "; + SWIFT_VERSION = 5.1; + TARGETED_DEVICE_FAMILY = "1,2"; + VERSIONING_SYSTEM = "apple-generic"; + VERSION_INFO_PREFIX = ""; + }; + name = Debug; + }; + C3C37B487645A54D043C2C18BF002F24 /* Release */ = { + isa = XCBuildConfiguration; + baseConfigurationReference = FA92B06C831BE63EC9C993A1217E090D /* MBProgressHUD.release.xcconfig */; + buildSettings = { + "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/MBProgressHUD/MBProgressHUD-prefix.pch"; + INFOPLIST_FILE = "Target Support Files/MBProgressHUD/MBProgressHUD-Info.plist"; + INSTALL_PATH = "$(LOCAL_LIBRARY_DIR)/Frameworks"; + IPHONEOS_DEPLOYMENT_TARGET = 13.0; + LD_RUNPATH_SEARCH_PATHS = ( + "$(inherited)", + "@executable_path/Frameworks", + "@loader_path/Frameworks", + ); + MODULEMAP_FILE = "Target Support Files/MBProgressHUD/MBProgressHUD.modulemap"; + PRODUCT_MODULE_NAME = MBProgressHUD; + PRODUCT_NAME = MBProgressHUD; + SDKROOT = iphoneos; + SKIP_INSTALL = YES; + SWIFT_ACTIVE_COMPILATION_CONDITIONS = "$(inherited) "; + SWIFT_VERSION = 5.0; + TARGETED_DEVICE_FAMILY = "1,2"; + VALIDATE_PRODUCT = YES; + VERSIONING_SYSTEM = "apple-generic"; + VERSION_INFO_PREFIX = ""; + }; + name = Release; + }; + C3D15EBC00CE0C7A89C80FF91D85E3DF /* Release */ = { + isa = XCBuildConfiguration; + baseConfigurationReference = 98AC09B0DB090CDE2D7CC82E1811FA69 /* RxRelay.release.xcconfig */; + buildSettings = { + "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/RxRelay/RxRelay-prefix.pch"; + INFOPLIST_FILE = "Target Support Files/RxRelay/RxRelay-Info.plist"; + INSTALL_PATH = "$(LOCAL_LIBRARY_DIR)/Frameworks"; + IPHONEOS_DEPLOYMENT_TARGET = 9.0; + LD_RUNPATH_SEARCH_PATHS = ( + "$(inherited)", + "@executable_path/Frameworks", + "@loader_path/Frameworks", + ); + MODULEMAP_FILE = "Target Support Files/RxRelay/RxRelay.modulemap"; + PRODUCT_MODULE_NAME = RxRelay; + PRODUCT_NAME = RxRelay; + SDKROOT = iphoneos; + SKIP_INSTALL = YES; + SWIFT_ACTIVE_COMPILATION_CONDITIONS = "$(inherited) "; + SWIFT_VERSION = 5.1; + TARGETED_DEVICE_FAMILY = "1,2"; + VALIDATE_PRODUCT = YES; + VERSIONING_SYSTEM = "apple-generic"; + VERSION_INFO_PREFIX = ""; + }; + name = Release; + }; + C844A53BB6B41D694E97EC9D893859EA /* Debug */ = { + isa = XCBuildConfiguration; + baseConfigurationReference = B5077D9342A7330872B9A75748BED92D /* RxRelay.debug.xcconfig */; + buildSettings = { + "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/RxRelay/RxRelay-prefix.pch"; + INFOPLIST_FILE = "Target Support Files/RxRelay/RxRelay-Info.plist"; + INSTALL_PATH = "$(LOCAL_LIBRARY_DIR)/Frameworks"; + IPHONEOS_DEPLOYMENT_TARGET = 9.0; + LD_RUNPATH_SEARCH_PATHS = ( + "$(inherited)", + "@executable_path/Frameworks", + "@loader_path/Frameworks", + ); + MODULEMAP_FILE = "Target Support Files/RxRelay/RxRelay.modulemap"; + PRODUCT_MODULE_NAME = RxRelay; + PRODUCT_NAME = RxRelay; + SDKROOT = iphoneos; + SKIP_INSTALL = YES; + SWIFT_ACTIVE_COMPILATION_CONDITIONS = "$(inherited) "; + SWIFT_VERSION = 5.1; + TARGETED_DEVICE_FAMILY = "1,2"; + VERSIONING_SYSTEM = "apple-generic"; + VERSION_INFO_PREFIX = ""; + }; + name = Debug; + }; + CF6CA7FF39CA75947971C5770D398B3C /* Debug */ = { + isa = XCBuildConfiguration; + baseConfigurationReference = 43A9212FF806B13E885C7019E059D160 /* Kingfisher.debug.xcconfig */; + buildSettings = { + CODE_SIGNING_ALLOWED = NO; + CONFIGURATION_BUILD_DIR = "$(BUILD_DIR)/$(CONFIGURATION)$(EFFECTIVE_PLATFORM_NAME)/Kingfisher"; + IBSC_MODULE = Kingfisher; + INFOPLIST_FILE = "Target Support Files/Kingfisher/ResourceBundle-Kingfisher-Kingfisher-Info.plist"; + IPHONEOS_DEPLOYMENT_TARGET = 12.0; + PRODUCT_NAME = Kingfisher; + SDKROOT = iphoneos; + SKIP_INSTALL = YES; + TARGETED_DEVICE_FAMILY = "1,2"; + WRAPPER_EXTENSION = bundle; + }; + name = Debug; + }; + DE569755C8FE69395D8E6C347DC7A5F8 /* Debug */ = { + isa = XCBuildConfiguration; + baseConfigurationReference = 80E741ED9F7CB291A4CA8068F3FE04F2 /* MBProgressHUD.debug.xcconfig */; + buildSettings = { + "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/MBProgressHUD/MBProgressHUD-prefix.pch"; + INFOPLIST_FILE = "Target Support Files/MBProgressHUD/MBProgressHUD-Info.plist"; + INSTALL_PATH = "$(LOCAL_LIBRARY_DIR)/Frameworks"; + IPHONEOS_DEPLOYMENT_TARGET = 13.0; + LD_RUNPATH_SEARCH_PATHS = ( + "$(inherited)", + "@executable_path/Frameworks", + "@loader_path/Frameworks", + ); + MODULEMAP_FILE = "Target Support Files/MBProgressHUD/MBProgressHUD.modulemap"; + PRODUCT_MODULE_NAME = MBProgressHUD; + PRODUCT_NAME = MBProgressHUD; + SDKROOT = iphoneos; + SKIP_INSTALL = YES; + SWIFT_ACTIVE_COMPILATION_CONDITIONS = "$(inherited) "; + SWIFT_VERSION = 5.0; + TARGETED_DEVICE_FAMILY = "1,2"; + VERSIONING_SYSTEM = "apple-generic"; + VERSION_INFO_PREFIX = ""; + }; + name = Debug; + }; + F5F3306F2C09AB4B623C805497E28D51 /* Release */ = { + isa = XCBuildConfiguration; + baseConfigurationReference = 36DFFD75B7479E1705FAC0F110CE34DC /* Alamofire.release.xcconfig */; + buildSettings = { + CLANG_ENABLE_OBJC_WEAK = NO; + "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/Alamofire-Info.plist"; + INSTALL_PATH = "$(LOCAL_LIBRARY_DIR)/Frameworks"; + IPHONEOS_DEPLOYMENT_TARGET = 10.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_VERSION = 5; + TARGETED_DEVICE_FAMILY = "1,2"; + VALIDATE_PRODUCT = YES; + VERSIONING_SYSTEM = "apple-generic"; + VERSION_INFO_PREFIX = ""; + }; + name = Release; + }; + FA4895DBEAEBEAC4FD8B516447AB8E02 /* Release */ = { + isa = XCBuildConfiguration; + baseConfigurationReference = 93BD071E578B69235CCADBFBE9FBAA1B /* Kingfisher.release.xcconfig */; + buildSettings = { + CODE_SIGNING_ALLOWED = NO; + CONFIGURATION_BUILD_DIR = "$(BUILD_DIR)/$(CONFIGURATION)$(EFFECTIVE_PLATFORM_NAME)/Kingfisher"; + IBSC_MODULE = Kingfisher; + INFOPLIST_FILE = "Target Support Files/Kingfisher/ResourceBundle-Kingfisher-Kingfisher-Info.plist"; + IPHONEOS_DEPLOYMENT_TARGET = 12.0; + PRODUCT_NAME = Kingfisher; + SDKROOT = iphoneos; + SKIP_INSTALL = YES; + TARGETED_DEVICE_FAMILY = "1,2"; + WRAPPER_EXTENSION = bundle; + }; + name = Release; + }; + FA8A3A80F26337CABC8F2D46E5924112 /* Debug */ = { + isa = XCBuildConfiguration; + baseConfigurationReference = E743F2C861099DDED46F43D21958AD4E /* Moya.debug.xcconfig */; + buildSettings = { + CLANG_ENABLE_OBJC_WEAK = NO; + "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/Moya/Moya-prefix.pch"; + INFOPLIST_FILE = "Target Support Files/Moya/Moya-Info.plist"; + INSTALL_PATH = "$(LOCAL_LIBRARY_DIR)/Frameworks"; + IPHONEOS_DEPLOYMENT_TARGET = 10.0; + LD_RUNPATH_SEARCH_PATHS = ( + "$(inherited)", + "@executable_path/Frameworks", + "@loader_path/Frameworks", + ); + MODULEMAP_FILE = "Target Support Files/Moya/Moya.modulemap"; + PRODUCT_MODULE_NAME = Moya; + PRODUCT_NAME = Moya; + SDKROOT = iphoneos; + SKIP_INSTALL = YES; + SWIFT_ACTIVE_COMPILATION_CONDITIONS = "$(inherited) "; + SWIFT_VERSION = 5.3; + TARGETED_DEVICE_FAMILY = "1,2"; + VERSIONING_SYSTEM = "apple-generic"; + VERSION_INFO_PREFIX = ""; + }; + name = Debug; + }; + FC6D85641022ADC4C2AE37E5380D4C88 /* Debug */ = { + isa = XCBuildConfiguration; + baseConfigurationReference = 45E1E6ADB66DF96376E308D63F6B71D8 /* HandyJSON.debug.xcconfig */; + buildSettings = { + "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/HandyJSON/HandyJSON-prefix.pch"; + INFOPLIST_FILE = "Target Support Files/HandyJSON/HandyJSON-Info.plist"; + INSTALL_PATH = "$(LOCAL_LIBRARY_DIR)/Frameworks"; + IPHONEOS_DEPLOYMENT_TARGET = 13.0; + LD_RUNPATH_SEARCH_PATHS = ( + "$(inherited)", + "@executable_path/Frameworks", + "@loader_path/Frameworks", + ); + MODULEMAP_FILE = "Target Support Files/HandyJSON/HandyJSON.modulemap"; + PRODUCT_MODULE_NAME = HandyJSON; + PRODUCT_NAME = HandyJSON; + SDKROOT = iphoneos; + SKIP_INSTALL = YES; + SWIFT_ACTIVE_COMPILATION_CONDITIONS = "$(inherited) "; + TARGETED_DEVICE_FAMILY = "1,2"; + VERSIONING_SYSTEM = "apple-generic"; + VERSION_INFO_PREFIX = ""; + }; + name = Debug; + }; +/* End XCBuildConfiguration section */ + +/* Begin XCConfigurationList section */ + 01BAF98FDA9A2155B61AAC471DB108C6 /* Build configuration list for PBXNativeTarget "Moya" */ = { + isa = XCConfigurationList; + buildConfigurations = ( + FA8A3A80F26337CABC8F2D46E5924112 /* Debug */, + 1ABF49ADDB0430B6FFCC63A8184EACA2 /* Release */, + ); + defaultConfigurationIsVisible = 0; + defaultConfigurationName = Release; + }; + 09CCB2E572716A4C9765854032B74A05 /* Build configuration list for PBXNativeTarget "Pods-yinmeng-ios" */ = { + isa = XCConfigurationList; + buildConfigurations = ( + A6974CAC511C0AC2C4BED7CA1BB9D70C /* Debug */, + 614A05FBF51042DF76C96CCD248FB774 /* Release */, + ); + defaultConfigurationIsVisible = 0; + defaultConfigurationName = Release; + }; + 1E42B460D55BA3EBE021004CC2CE312C /* Build configuration list for PBXNativeTarget "RxCocoa" */ = { + isa = XCConfigurationList; + buildConfigurations = ( + C12D9C5CC8F2071662A98F549A9E6FB4 /* Debug */, + 577A24D81FA00BED9154F445BE58F743 /* Release */, + ); + defaultConfigurationIsVisible = 0; + defaultConfigurationName = Release; + }; + 4821239608C13582E20E6DA73FD5F1F9 /* Build configuration list for PBXProject "Pods" */ = { + isa = XCConfigurationList; + buildConfigurations = ( + 8DE5143C03248BB6CD542DE3963D6F3A /* Debug */, + 9E406C6AAF85E580207CD97B0044DEAB /* Release */, + ); + defaultConfigurationIsVisible = 0; + defaultConfigurationName = Release; + }; + 50FD3D310936ECB8784F9C1229DA48CC /* Build configuration list for PBXNativeTarget "HandyJSON" */ = { + isa = XCConfigurationList; + buildConfigurations = ( + FC6D85641022ADC4C2AE37E5380D4C88 /* Debug */, + 74FCF40A76D1E62C63837B25FCE9F45D /* Release */, + ); + defaultConfigurationIsVisible = 0; + defaultConfigurationName = Release; + }; + 58EAA7FF29EA237538F747F2AF468203 /* Build configuration list for PBXNativeTarget "SnapKit" */ = { + isa = XCConfigurationList; + buildConfigurations = ( + A6F0173BAEB974532D93E05E5A94E50A /* Debug */, + 8C925430B65BE03F92ABCD1B2005EE0C /* Release */, + ); + defaultConfigurationIsVisible = 0; + defaultConfigurationName = Release; + }; + 5D6B3CF88B71711BCA7DA130AF7EC13D /* Build configuration list for PBXNativeTarget "RxRelay" */ = { + isa = XCConfigurationList; + buildConfigurations = ( + C844A53BB6B41D694E97EC9D893859EA /* Debug */, + C3D15EBC00CE0C7A89C80FF91D85E3DF /* Release */, + ); + defaultConfigurationIsVisible = 0; + defaultConfigurationName = Release; + }; + 61C623C1EDB6AD9DC66AD8969115C6E1 /* Build configuration list for PBXNativeTarget "Kingfisher" */ = { + isa = XCConfigurationList; + buildConfigurations = ( + BC856BC9A4C1242C1AFA559E24FF0568 /* Debug */, + 195F1AC8F6BD95FEFB9983CAC195FCAE /* Release */, + ); + defaultConfigurationIsVisible = 0; + defaultConfigurationName = Release; + }; + 865D36780A78CA83F04FC3A8CDB81EE4 /* Build configuration list for PBXNativeTarget "Reusable" */ = { + isa = XCConfigurationList; + buildConfigurations = ( + 5614F562617D1EE7A1A60E422C2D007A /* Debug */, + 2D9905F00DBA0E0A2C139BAFDE426559 /* Release */, + ); + defaultConfigurationIsVisible = 0; + defaultConfigurationName = Release; + }; + A7BD2681E97C00DCC2EF91B0EBA76110 /* Build configuration list for PBXNativeTarget "MBProgressHUD" */ = { + isa = XCConfigurationList; + buildConfigurations = ( + DE569755C8FE69395D8E6C347DC7A5F8 /* Debug */, + C3C37B487645A54D043C2C18BF002F24 /* Release */, + ); + defaultConfigurationIsVisible = 0; + defaultConfigurationName = Release; + }; + BD779400D1CA952C3C31F225A3BA7650 /* Build configuration list for PBXNativeTarget "RxSwift" */ = { + isa = XCConfigurationList; + buildConfigurations = ( + 960DBC77E1DF531EDC9D62CD1E847BA2 /* Debug */, + 166E9C881152A0BEAAF3B03A4FCB9878 /* Release */, + ); + defaultConfigurationIsVisible = 0; + defaultConfigurationName = Release; + }; + D7761A54AFA2998F27E0BC2FACC2EB53 /* Build configuration list for PBXNativeTarget "Alamofire" */ = { + isa = XCConfigurationList; + buildConfigurations = ( + B7D9E7CD650F798EC835C67DACFEBC4F /* Debug */, + F5F3306F2C09AB4B623C805497E28D51 /* Release */, + ); + defaultConfigurationIsVisible = 0; + defaultConfigurationName = Release; + }; + E29E987197D3C29B626AB8FA0A012C04 /* Build configuration list for PBXNativeTarget "Kingfisher-Kingfisher" */ = { + isa = XCConfigurationList; + buildConfigurations = ( + CF6CA7FF39CA75947971C5770D398B3C /* Debug */, + FA4895DBEAEBEAC4FD8B516447AB8E02 /* Release */, + ); + defaultConfigurationIsVisible = 0; + defaultConfigurationName = Release; + }; +/* End XCConfigurationList section */ + }; + rootObject = BFDFE7DC352907FC980B868725387E98 /* Project object */; +} diff --git a/Pods/Pods.xcodeproj/xcuserdata/fengshuo.xcuserdatad/xcschemes/Alamofire.xcscheme b/Pods/Pods.xcodeproj/xcuserdata/fengshuo.xcuserdatad/xcschemes/Alamofire.xcscheme new file mode 100644 index 0000000..3658e11 --- /dev/null +++ b/Pods/Pods.xcodeproj/xcuserdata/fengshuo.xcuserdatad/xcschemes/Alamofire.xcscheme @@ -0,0 +1,58 @@ + + + + + + + + + + + + + + + + + + + + + + + diff --git a/Pods/Pods.xcodeproj/xcuserdata/fengshuo.xcuserdatad/xcschemes/HandyJSON.xcscheme b/Pods/Pods.xcodeproj/xcuserdata/fengshuo.xcuserdatad/xcschemes/HandyJSON.xcscheme new file mode 100644 index 0000000..57087e5 --- /dev/null +++ b/Pods/Pods.xcodeproj/xcuserdata/fengshuo.xcuserdatad/xcschemes/HandyJSON.xcscheme @@ -0,0 +1,58 @@ + + + + + + + + + + + + + + + + + + + + + + + diff --git a/Pods/Pods.xcodeproj/xcuserdata/fengshuo.xcuserdatad/xcschemes/Kingfisher-Kingfisher.xcscheme b/Pods/Pods.xcodeproj/xcuserdata/fengshuo.xcuserdatad/xcschemes/Kingfisher-Kingfisher.xcscheme new file mode 100644 index 0000000..6316027 --- /dev/null +++ b/Pods/Pods.xcodeproj/xcuserdata/fengshuo.xcuserdatad/xcschemes/Kingfisher-Kingfisher.xcscheme @@ -0,0 +1,58 @@ + + + + + + + + + + + + + + + + + + + + + + + diff --git a/Pods/Pods.xcodeproj/xcuserdata/fengshuo.xcuserdatad/xcschemes/Kingfisher.xcscheme b/Pods/Pods.xcodeproj/xcuserdata/fengshuo.xcuserdatad/xcschemes/Kingfisher.xcscheme new file mode 100644 index 0000000..71b3f40 --- /dev/null +++ b/Pods/Pods.xcodeproj/xcuserdata/fengshuo.xcuserdatad/xcschemes/Kingfisher.xcscheme @@ -0,0 +1,58 @@ + + + + + + + + + + + + + + + + + + + + + + + diff --git a/Pods/Pods.xcodeproj/xcuserdata/fengshuo.xcuserdatad/xcschemes/MBProgressHUD.xcscheme b/Pods/Pods.xcodeproj/xcuserdata/fengshuo.xcuserdatad/xcschemes/MBProgressHUD.xcscheme new file mode 100644 index 0000000..39f48e1 --- /dev/null +++ b/Pods/Pods.xcodeproj/xcuserdata/fengshuo.xcuserdatad/xcschemes/MBProgressHUD.xcscheme @@ -0,0 +1,58 @@ + + + + + + + + + + + + + + + + + + + + + + + diff --git a/Pods/Pods.xcodeproj/xcuserdata/fengshuo.xcuserdatad/xcschemes/Moya.xcscheme b/Pods/Pods.xcodeproj/xcuserdata/fengshuo.xcuserdatad/xcschemes/Moya.xcscheme new file mode 100644 index 0000000..3d55b05 --- /dev/null +++ b/Pods/Pods.xcodeproj/xcuserdata/fengshuo.xcuserdatad/xcschemes/Moya.xcscheme @@ -0,0 +1,58 @@ + + + + + + + + + + + + + + + + + + + + + + + diff --git a/Pods/Pods.xcodeproj/xcuserdata/fengshuo.xcuserdatad/xcschemes/Pods-yinmeng-ios.xcscheme b/Pods/Pods.xcodeproj/xcuserdata/fengshuo.xcuserdatad/xcschemes/Pods-yinmeng-ios.xcscheme new file mode 100644 index 0000000..af444f4 --- /dev/null +++ b/Pods/Pods.xcodeproj/xcuserdata/fengshuo.xcuserdatad/xcschemes/Pods-yinmeng-ios.xcscheme @@ -0,0 +1,58 @@ + + + + + + + + + + + + + + + + + + + + + + + diff --git a/Pods/Pods.xcodeproj/xcuserdata/fengshuo.xcuserdatad/xcschemes/Reusable.xcscheme b/Pods/Pods.xcodeproj/xcuserdata/fengshuo.xcuserdatad/xcschemes/Reusable.xcscheme new file mode 100644 index 0000000..f50d2c2 --- /dev/null +++ b/Pods/Pods.xcodeproj/xcuserdata/fengshuo.xcuserdatad/xcschemes/Reusable.xcscheme @@ -0,0 +1,58 @@ + + + + + + + + + + + + + + + + + + + + + + + diff --git a/Pods/Pods.xcodeproj/xcuserdata/fengshuo.xcuserdatad/xcschemes/RxCocoa.xcscheme b/Pods/Pods.xcodeproj/xcuserdata/fengshuo.xcuserdatad/xcschemes/RxCocoa.xcscheme new file mode 100644 index 0000000..ab56e3e --- /dev/null +++ b/Pods/Pods.xcodeproj/xcuserdata/fengshuo.xcuserdatad/xcschemes/RxCocoa.xcscheme @@ -0,0 +1,58 @@ + + + + + + + + + + + + + + + + + + + + + + + diff --git a/Pods/Pods.xcodeproj/xcuserdata/fengshuo.xcuserdatad/xcschemes/RxRelay.xcscheme b/Pods/Pods.xcodeproj/xcuserdata/fengshuo.xcuserdatad/xcschemes/RxRelay.xcscheme new file mode 100644 index 0000000..be7db3d --- /dev/null +++ b/Pods/Pods.xcodeproj/xcuserdata/fengshuo.xcuserdatad/xcschemes/RxRelay.xcscheme @@ -0,0 +1,58 @@ + + + + + + + + + + + + + + + + + + + + + + + diff --git a/Pods/Pods.xcodeproj/xcuserdata/fengshuo.xcuserdatad/xcschemes/RxSwift.xcscheme b/Pods/Pods.xcodeproj/xcuserdata/fengshuo.xcuserdatad/xcschemes/RxSwift.xcscheme new file mode 100644 index 0000000..1696fa5 --- /dev/null +++ b/Pods/Pods.xcodeproj/xcuserdata/fengshuo.xcuserdatad/xcschemes/RxSwift.xcscheme @@ -0,0 +1,58 @@ + + + + + + + + + + + + + + + + + + + + + + + diff --git a/Pods/Pods.xcodeproj/xcuserdata/fengshuo.xcuserdatad/xcschemes/SnapKit.xcscheme b/Pods/Pods.xcodeproj/xcuserdata/fengshuo.xcuserdatad/xcschemes/SnapKit.xcscheme new file mode 100644 index 0000000..70f41b0 --- /dev/null +++ b/Pods/Pods.xcodeproj/xcuserdata/fengshuo.xcuserdatad/xcschemes/SnapKit.xcscheme @@ -0,0 +1,58 @@ + + + + + + + + + + + + + + + + + + + + + + + diff --git a/Pods/Pods.xcodeproj/xcuserdata/fengshuo.xcuserdatad/xcschemes/xcschememanagement.plist b/Pods/Pods.xcodeproj/xcuserdata/fengshuo.xcuserdatad/xcschemes/xcschememanagement.plist new file mode 100644 index 0000000..44066f6 --- /dev/null +++ b/Pods/Pods.xcodeproj/xcuserdata/fengshuo.xcuserdatad/xcschemes/xcschememanagement.plist @@ -0,0 +1,95 @@ + + + + + SchemeUserState + + Alamofire.xcscheme + + isShown + + orderHint + 0 + + HandyJSON.xcscheme + + isShown + + orderHint + 1 + + Kingfisher-Kingfisher.xcscheme + + isShown + + orderHint + 3 + + Kingfisher.xcscheme + + isShown + + orderHint + 2 + + MBProgressHUD.xcscheme + + isShown + + orderHint + 4 + + Moya.xcscheme + + isShown + + orderHint + 5 + + Pods-yinmeng-ios.xcscheme + + isShown + + orderHint + 6 + + Reusable.xcscheme + + isShown + + orderHint + 7 + + RxCocoa.xcscheme + + isShown + + orderHint + 8 + + RxRelay.xcscheme + + isShown + + orderHint + 9 + + RxSwift.xcscheme + + isShown + + orderHint + 10 + + SnapKit.xcscheme + + isShown + + orderHint + 11 + + + SuppressBuildableAutocreation + + + diff --git a/Pods/Reusable/LICENSE b/Pods/Reusable/LICENSE new file mode 100644 index 0000000..96d78c1 --- /dev/null +++ b/Pods/Reusable/LICENSE @@ -0,0 +1,21 @@ +The MIT License (MIT) + +Copyright (c) 2016 AliSoftware + +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/Reusable/README.md b/Pods/Reusable/README.md new file mode 100644 index 0000000..85a1dda --- /dev/null +++ b/Pods/Reusable/README.md @@ -0,0 +1,528 @@ +# Reusable + +

+ Reusable +

+ +A Swift mixin to use `UITableViewCells`, `UICollectionViewCells` and `UIViewControllers` in a **type-safe way**, without the need to manipulate their `String`-typed `reuseIdentifiers`. This library also supports arbitrary `UIView` to be loaded via a XIB using a simple call to `loadFromNib()` + +[![CircleCI](https://circleci.com/gh/AliSoftware/Reusable/tree/master.svg?style=svg)](https://circleci.com/gh/AliSoftware/Reusable/tree/master) +[![Platform](http://cocoapod-badges.herokuapp.com/p/Reusable/badge.png)](http://cocoadocs.org/docsets/Reusable) +[![Version](http://cocoapod-badges.herokuapp.com/v/Reusable/badge.png)](http://cocoadocs.org/docsets/Reusable) +[![Language: Swift 3](https://img.shields.io/badge/Swift-3-orange)](https://swift.org) +[![Language: Swift 4](https://img.shields.io/badge/Swift-4-orange)](https://swift.org) +[![Language: Swift 5](https://img.shields.io/badge/Swift-5-orange)](https://swift.org) + +# Installation + +
Requirements: which Reusable version to use for each Swift Version? + +| Swift Version | Reusable Version | +|----------------|--------------------| +| 2.2 & 2.3 | 2.5.1 | +| 3.0 (†) | 3.0.0 + | +| 4.0 | 4.0.2 + | +| 5.0 | 4.1.0 + | + +_(†) The Reusable 3.0 code also compiles with Swift 4, you'll need 4.0.2+ only if you're using Carthage for integration_ + +
+ +Reusable can be integrated to your Xcode projects using one of the following options: + +
Installation instructions for Swift Package Manager (SPM) + +[Swift Package Manager](https://swift.org/package-manager/) is Apple's decentralized dependency manager to integrate libraries to your Swift projects. It is now fully integrated with Xcode 11 + +To integrate Reusable into your project using SPM, specify it in your `Package.swift` file: + +```swift +let package = Package( + … + dependencies: [ + .package(url: "https://github.com/AliSoftware/Reusable.git", from: "4.1.0"), + ], + targets: [ + .target(name: "YourTarget", dependencies: ["Reusable", …]) + … + ] +) +``` + +
+ +
Installation instructions for Carthage + +[Carthage](https://github.com/Carthage/Carthage) is a decentralized dependency manager to add pre-built frameworks to your Cocoa application. + +To integrate Reusable into your Xcode project using Carthage, specify it in your `Cartfile`: + +```bash +github "AliSoftware/Reusable" +``` + +
+ +
Installation instructions for CocoaPods + +[CocoaPods](https://cocoapods.org/) is a dependency manager to automate integration of frameworks to your Swift and Objective-C Cocoa projects. + +To integrate Reusable into your Xcode project using Cocoapods, specify it in your `Podfile`: + +```bash +pod 'Reusable' +``` + +
+ +# Introduction + +This library aims to make it super-easy to create, dequeue and instantiate reusable views anywhere this pattern is used: from the obvious `UITableViewCell` and `UICollectionViewCell` to custom `UIViews`, even supporting `UIViewControllers` from Storyboards. +All of that simply by **marking your classes as conforming to a protocol, without having to add any code**, and **creating a type-safe API with no more String-based API**. + +```swift +// Example of what Reusable allows you to do +final class MyCustomCell: UITableViewCell, Reusable { /* And that's it! */ } +tableView.register(cellType: MyCustomCell.self) +let cell: MyCustomCell = tableView.dequeueReusableCell(for: indexPath) +``` + +This concept, called a [Mixin](http://alisoftware.github.io/swift/protocol/2015/11/08/mixins-over-inheritance/) (a protocol with default implementation for all its methods), is explained [here in my blog post](http://alisoftware.github.io/swift/generics/2016/01/06/generic-tableviewcells/) in details. + +**Table of Contents** + +* [Type-safe cells](#type-safe-uitableviewcell--uicollectionviewcell) +* [Type-safe XIB-based reusable views](#type-safe-xib-based-reusable-views) +* [Type-safe ViewControllers from Storyboards](#type-safe-viewcontrollers-from-storyboards) +* [Additional tips](#additional-tips) +* [Example project](#example-project) +* [Talks and Articles about Reusable](#talks-and-articles-about-reusable) +* [License](#license) + + +--- + + + +# Type-safe `UITableViewCell` / `UICollectionViewCell` + +> ✍️ Examples and explanations below use `UITableView` and `UITableViewCell`, but the exact same examples and explanations apply for `UICollectionView` and `UICollectionViewCell`. + +## 1. Declare your cells to conform to `Reusable` or `NibReusable` + +* Use the `Reusable` protocol if they don't depend on a NIB (this will use `registerClass(…)` to register the cell) +* Use the `NibReusable` typealias (= `Reusable & NibLoadable`) if they use a `XIB` file for their content (this will use `registerNib(…)` to register the cell) + +```swift +final class CustomCell: UITableViewCell, Reusable { /* And that's it! */ } +``` + +> ✍️ **Notes** +> +> * For cells embedded in a Storyboard's tableView, either one of those two protocols will work (as you won't need to register the cell manually anyway, since registration is handled by the storyboard automatically) +> * If you create a XIB-based cell, don't forget to set its _Reuse Identifier_ field in Interface Builder to the same string as the name of the cell class itself. +> * 💡 `NibReusable` is a typealias, so you could still use two protocols conformance `Reusable, NibLoadable` instead of `NibReusable`. + + +
+📑 Example for a Code-based custom tableView cell + +```swift +final class CodeBasedCustomCell: UITableViewCell, Reusable { + // By default this cell will have a reuseIdentifier of "CodeBasedCustomCell" + // unless you provide an alternative implementation of `static var reuseIdentifier` + + // No need to add anything to conform to Reusable. You can just keep your normal cell code + @IBOutlet private weak var label: UILabel! + func fillWithText(text: String?) { label.text = text } +} +``` +
+ +
+📑 Example for a Nib-based custom tableView cell + +```swift +final class NibBasedCustomCell: UITableViewCell, NibReusable { +// or +// final class NibBasedCustomCell: UITableViewCell, Reusable, NibLoadable { + + // Here we provide a nib for this cell class (which, if we don't override the protocol's + // default implementation of `static var nib: UINib`, will use a XIB of the same name as the class) + + // No need to add anything to conform to Reusable. You can just keep your normal cell code + @IBOutlet private weak var pictureView: UIImageView! + func fillWithImage(image: UIImage?) { pictureView.image = image } +} +``` +
+ +
+📑 Example for a Code-based custom collectionView cell + +```swift +// A UICollectionViewCell which doesn't need a XIB to register +// Either because it's all-code, or because it's registered via Storyboard +final class CodeBasedCollectionViewCell: UICollectionViewCell, Reusable { + // The rest of the cell code goes here +} +``` +
+ +
+📑 Example for a Nib-based custom collectionView cell + +```swift +// A UICollectionViewCell using a XIB to define it's UI +// And that will need to register using that XIB +final class NibBasedCollectionViewCell: UICollectionViewCell, NibReusable { +// or +// final class NibBasedCollectionViewCell: UICollectionViewCell, Reusable, NibLoadable { + + // The rest of the cell code goes here + +} +``` +
+ +## 2. Register your cells + +Unless you've prototyped your cell in a Storyboard, you'll have to register the cell class or Nib by code. + +To do this, instead of calling `registerClass(…)` or `registerNib(…)` using a String-based `reuseIdentifier`, just call: + +```swift +tableView.register(cellType: theCellClass.self) +``` + +
+📑 Example of `UITableView` registration + +```swift +class MyViewController: UIViewController { + @IBOutlet private weak var tableView: UITableView! + + override func viewDidLoad() { + super.viewDidLoad() + // This will register using the class (via `register(AnyClass?, forCellReuseIdentifier: String)`) + // because the CodeBasedCustomCell type conforms to Reusable, but not NibLoadable (nor the NibReusable typealias) + tableView.register(cellType: CodeBasedCustomCell.self) + // This will register using NibBasedCustomCell.xib (via `register(UINib?, forCellReuseIdentifier: String)`) + // because the NibBasedCustomCell type conforms to NibLoadable (via the NibReusable typealias) + tableView.register(cellType: NibBasedCustomCell.self) + } +} +``` +
+ +## 3. Dequeue your cells + +To dequeue a cell (typically in your `cellForRowAtIndexPath` implementation), simply call `dequeueReusableCell(indexPath:)`: + +```swift +// Either +let cell = tableView.dequeueReusableCell(for: indexPath) as MyCustomCell +// Or +let cell: MyCustomCell = tableView.dequeueReusableCell(for: indexPath) +``` + +As long as **Swift can use type-inference to understand that you'll want a cell of type `MyCustomCell`** (either using `as MyCustomCell` or explicitly typing the receiving variable `cell: MyCustomCell`), it will magically infer both the cell class to use and thus its `reuseIdentifier` needed to dequeue the cell, and which exact type to return to save you a type-cast. + +* No need for you to manipulate `reuseIdentifiers` Strings manually anymore! +* No need to force-cast the returned `UITableViewCell` instance down to your `MyCustomCell` class either! + +
+📑 Example implementation of `cellForRowAtIndexPath` using `Reusable` + +```swift +extension MyViewController: UITableViewDataSource { + func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell { + if indexPath.section == 0 { + let cell = tableView.dequeueReusableCell(indexPath: indexPath) as CodeBasedCustomCell + // Customize the cell here. You can call any type-specific methods here without the need for type-casting + cell.fillWithText("Foo") + return cell + } else { + let cell = tableView.dequeueReusableCell(indexPath: indexPath) as NibBasedCustomCell + // Customize the cell here. no need to downcasting here either! + cell.fillWithImage(UIImage(named:"Bar")) + return cell + } + } +} +``` +
+ +Now all you have is **a beautiful code and type-safe cells**, with compile-type checking, and no more String-based API! + +> 💡 If the cell class you want to dequeue is computed at runtime and stored in a variable, you won't be able to use `as theVariable` or `let cell: theVariable` obviously. Instead, you can use the optional parameter `cellType` (which otherwise gets infered by the return type and is thus not necessary to provide explicitly) +> +>
+> 📑 Example with a cell type determined at runtime +> +> ```swift +> class ParentCell: UITableViewCell, Reusable {} +> class Child1Cell: ParentCell {} +> class Child2Cell: ParentCell {} +> +> func cellType(for indexPath: NSIndexPath) -> ParentCell.Type { +> return indexPath.row.isMultiple(of: 2) ? Child1Cell.self : Child2Cell.self +> } +> +> func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell { +> let cellClass = self.cellType(for: indexPath) +> // As `self.cellType(for:)` always returns a `ParentCell` (sub-)class, the type +> // of the variable `cell` below is infered to be `ParentCell` too. So only methods +> // declared in the parent `ParentCell` class will be accessible on the `cell` variable. +> // But this code will still dequeue the proper type of cell (Child1Cell or Child2Cell). +> let cell = tableView.dequeueReusableCell(for: indexPath, cellType: cellClass) +> // Then fill the content of your cell (using methods/properties from `ParentCell` type) +> return cell +> } +> ``` +>
+ +--- + + + +# Type-safe XIB-based reusable views + +`Reusable` also allows you to create reusable custom views designed in Interface Builder to reuse them in other XIBs or Storyboards, or by code. This allows you to treat those views like custom UI widgets that can be used in multiple places in your app. + +## 1. Declare your views to conform to `NibLoadable` or `NibOwnerLoadable` + +In your swift source declaring your custom view class: + +* Use the `NibLoadable` protocol if the XIB you're using don't use its "File's Owner" and the reusable view you're designing is the root view of the XIB +* Use the `NibOwnerLoadable` protocol if you used a "File's Owner" of the XIB being of the class of your reusable view, and the root view(s) of the XIB is to be set as a subview providing its content. + +```swift +// a XIB-based custom UIView, used as root of the XIB +final class NibBasedRootView: UIView, NibLoadable { /* and that's it! */ } + +// a XIB-based custom UIView, used as the XIB's "File's Owner" +final class NibBasedFileOwnerView: UIView, NibOwnerLoadable { /* and that's it! */ } +``` + +> 💡 You should use the second approach if you plan to use your custom view in another XIB or Storyboard. +> This will allow you to just drop a UIView in a XIB/Storyboard and change its class in IB's inspector to the class of your custom XIB-based view to use it. That custom view will then automagically load its own content from the associated XIB when instantiated by the storyboard containing it, without having to write additional code to load the content of the custom view manually every time. + +## 2. Design your view in Interface Builder + +For example if you named your class `MyCustomWidget` and made it `NibOwnerLoadable`: + +* Set the _File's Owner_'s class to `MyCustomWidget` +* Design the content of the view via the root view of that XIB (which is a standard `UIView` with no custom class) and its subviews +* Connect any `@IBOutlets` and `@IBActions` between the _File's Owner_ (the `MyCustomWidget`) and its content + +
+🖼📑 A view configured to be `NibOwnerLoadable` + +![NibOwnerLoadable view in Interface Builder](NibOwnerLoadable.png) + +```swift +final class MyCustomWidget: UIView, NibOwnerLoadable { + @IBOutlet private var rectView: UIView! + @IBOutlet private var textLabel: UILabel! + + @IBInspectable var rectColor: UIColor? { + didSet { + self.rectView.backgroundColor = self.rectColor + } + } + @IBInspectable var text: String? { + didSet { + self.textLabel.text = self.text + } + } +… +} +``` +
+ +Then that widget can be integrated in a Storyboard Scene (or any other XIB) by simply dropping a `UIView` on the Storyboard, and changing its class to `MyCustomWidget` in IB's inspector. + +
+🖼 Example of a `NibOwnerLoadable` custom view once integrated in another Storyboard + +* In the capture below, all blue square views have a custom class of `MyCustomWidget` set in Interface Builder. +* When selecting one of these custom views, you have direct access to all `@IBOutlet` that this `MyCustomWidget` exposes, which allows you to connect them to other views of the Storyboard if needed +* When selecting one of these custom views, you also have access to all the `@IBInspectable` properties. For example, in the capture below, you can see the "Rect color" and "Text" inspectable properties on the right panel, that you can change right from the Storyboard integrating your custom widget. + +![NibOwnerLoadable integrated in a Storyboard](NibOwnerLoadable-InStoryboard.png) +
+ +## 3a. Auto-loading the content of a `NibOwnerLoadable` view + +If you used `NibOwnerLoadable` and made your custom view the File's Owner of your XIB, you should then override `init?(coder:)` so that it loads it's associated XIB as subviews and add constraints automatically: + +```swift +final class MyCustomWidget: UIView, NibOwnerLoadable { + … + required init?(coder aDecoder: NSCoder) { + super.init(coder: aDecoder) + self.loadNibContent() + } +} +``` + +`self.loadNibContent()` is a method provided by the `NibOwnerLoadable` mixin. It basically loads the content from the associated `MyCustomWidget.xib`, then add all the root views in that XIB as subviews of your `MyCustomWidget`, with appropriate layout constraints to make them the same size as your `MyCustomWidget` container view. + +Overriding `init?(coder:)` and calling `self.loadNibContent()` thus allows you to have that content automatically loaded by the system when that `MyCustomWidget` in included in another XIB or in a Storyboard (as `init?(coder:)` is the `init` that is called by iOS to create those instances in a XIB or Storyboard) + +_💡 Note: it is also possible to override `init(frame:)` similarly, in order to be able to also create an instance of that view manually via code if needed._ + +## 3b. Instantiating a `NibLoadable` view + +If you used `NibLoadable` and made your custom view the root view of your XIB (not using the File's Owner at all), these are not designed to be used in other Storyboards or XIBs like `NibOwnerLoadable` is, as they won't be able to auto-load their content. + +Instead, you will instantiate those `NibLoadable` views by code, which is as simple as calling `loadFromNib()` on your custom class: + +```swift +let view1 = NibBasedRootView.loadFromNib() // Create one instance +let view2 = NibBasedRootView.loadFromNib() // Create another one +let view3 = NibBasedRootView.loadFromNib() // and another one +… +``` + +--- + + + +# Type-safe ViewControllers from Storyboards + +`Reusable` also allows you to mark your `UIViewController` classes as `StoryboardBased` or `StoryboardSceneBased` to easily instantiate them from their associated Storyboard in a type-safe way. + +## 1. Declare your `UIViewController` to conform to `StoryboardBased` or `StoryboardSceneBased` + +In your swift source declaring your custom `UIViewController` class: + +* Use the `StoryboardBased` protocol if the `*.storyboard` file has the same name as the ViewController's class, and its scene is the "initial scene" of the storyboard. + * This is typically ideal if you use one Storyboard per ViewController, for example. +* Use the `StoryboardSceneBased` protocol if scene in your storyboard has the same `sceneIdentifier` as the name of the ViewController's class, but the `*.storyboard` file name doesn't necessary match the ViewController's class name. + * This is typically ideal for secondary scenes in bigger storyboards + * You'll then be required to implement the `sceneStoryboard` type property to indicate the storyboard it belongs to. + +
+📑 Example of a ViewController being the initial ViewController of its Storyboard + +In this example, `CustomVC` is designed as the initial ViewController of a Storyboard named `CustomVC.storyboard`: + +```swift +final class CustomVC: UIViewController, StoryboardBased { /* and that's it! */ } +``` +
+ +
+📑 Example of a ViewController being an arbitrary scene in a differently-named Storyboard + +In this example, `SecondaryVC` is designed in a Storyboard name `CustomVC.storyboard` (so with a different name than the class itself) and is _not_ the initial ViewController, but instead has its **"Scene Identifier"** set to the value `"SecondaryVC"` (same as the class name) + +Conforming to `StoryboardSceneBased` will still require you to implement `static var sceneStoryboard: UIStoryboard { get }` to indicate the Storyboard where this scene is designed. You can typically implement that property using a `let` type constant: + +```swift +final class SecondaryVC: UIViewController, StoryboardSceneBased { + static let sceneStoryboard = UIStoryboard(name: "CustomVC", bundle: nil) + /* and that's it! */ +} +``` +
+ +## 2. Instantiate your UIViewControllers + +Simply call `instantiate()` on your custom class. This will automatically know which storyboard to load it from, and which scene (initial or not) to use to instantiate it. + +```swift +func presentSecondary() { + let vc = SecondaryVC.instantiate() // Init from the "SecondaryVC" scene of CustomVC.storyboard + self.present(vc, animated: true) {} +} +``` + + + +--- + + + +# Additional tips + +## Make your subclasses `final` + +I advise you to mark your custom `UITableViewCell`, `UICollectionViewCell`, `UIView` and `UIViewController` subclasses as being `final`. This is because: + +* In most cases, the custom cells and VCs you plan to instantiate are not intended to be subclassed themselves. +* More importantly, it helps the compiler a lot and gives you big optimizations +* It can be required in some cases when conforming to `protocols` that have `Self` requirements, like the ones used by this pod (`Reusable`, `StoryboardBased`, …). + +In some cases you can avoid making your classes `final`, but in general it's a good practice, and in the case of this pod, usually your custom `UIViewController` or whatever won't be subclassed anyway: + +* Either they are intended to be used and instantiated directly and never be subclassed, so `final` makes sense here +* In case your custom `UIViewController`, `UITableViewCell`, etc… is intended to be subclassed and be the parent class of many classes in your app, it makes more sense to **add the protocol conformance (`StoryboardBased`, `Reusable`, …) to the child classes (and mark _them_ `final`)** than adding the protocol on the parent, abstract class. + +## Customize reuseIdentifier, nib, etc for non-conventional uses + +The protocols in this pod, like `Reusable`, `NibLoadable`, `NibOwnerLoadable`, `StoryboardBased`, `NibReusable`… are what is usually called [Mixins](http://alisoftware.github.io/swift/protocol/2015/11/08/mixins-over-inheritance/), which basically is a Swift protocol with a default implementation provided for all of its methods. + +The main benefit is that **you don't need to add any code**: just conform to `Reusable`, `NibOwnerLoadable` or any of those protocol and you're ready to go with no additional code to write. + +But of course, those provided implementations are just **default implementations**. That means that if you need **you can still provide your own implementations** in case for some reason some of your cells don't follow the classic configuration of using the same name for both the class, the `reuseIdentifier` and the XIB file. + +```swift +final class VeryCustomNibBasedCell: UITableViewCell, NibReusable { + // This cell use a non-standard configuration: its reuseIdentifier and XIB file + // have a different name as the class itself. So we need to provide a custom implementation or `NibReusable` + static var reuseIdentifier: String { return "VeryCustomReuseIdentifier" } + static var nib: UINib { return UINib(nibName: "VeryCustomUI", bundle: nil) } // Use VeryCustomUI.xib + + // Then continue with the rest of your normal cell code +} +``` + +The same is true for all the protocols of this pod, which always provide default implementations which could still be replaced by your own if you need some custom cases. + +_But the beauty is in 90% of cases the default implementation will match typical conventions and the default implementations will be exactly what you want!_ + +## Type-safety and `fatalError` + +`Reusable` allows you to manipulate type-safe APIs and make you avoid typos. But things could still go wrong in case of a misconfguration, for example if you forgot to set the `reuseIdentifier` of your cell in its `XIB`, or you declared a `FooViewController` to be `StoryboardBased` but forgot to set the initial ViewController flag on that `FooViewController` scene in that Storyboard, etc. + +In such cases, because those are developer errors that should be caught as early as possible in the development process, `Reusable` will call `fatalError` **with an error message as descriptive as possible** (instead of crashing with an obscure message about some force-cast or force-unwrap or whatnot) to help you configure it right. + +For example, if `Reusable` fails to dequeue a cell, it will bail with a message like: + +> « Failed to dequeue a cell with identifier \\(cellType.reuseIdentifier) matching type \\(cellType.self). +> Check that the reuseIdentifier is set properly in your XIB/Storyboard and that you registered the cell beforehand. » + +Hopefully, those explicit failure messages will allow you to understand what was misconfigured and help you fix it! + + + +--- + + + +# Example Project + +This repository comes with an example project in the `Example/` folder. Feel free to try it. + +It demonstrates how `Reusable` works for: + +* `UITableViewCell` and `UICollectionViewCell` subclasses, +* Cells whose UI template is either only provided by plain code, or provided by a XIB, or prototyped directly in a Storyboard. +* `UICollectionView`'s `SupplementaryViews` (section Headers) +* Custom `UIView` designed in a XIB (`NibOwnerLoadable`) + +# Talks and Articles about Reusable + +The concepts behind Reusable has been presented in various articles and talks: + +* [Using Generics to improve TableView cells](https://alisoftware.github.io/swift/generics/2016/01/06/generic-tableviewcells/) on my blog +* [FrenchKit'16 talk: Mixins over Inheritance](https://youtu.be/BSn4jlunn4I) (video) +* Same talk was also given at NSSpain'16 ([slides](https://speakerdeck.com/alisoftware/mixins-over-inheritance)) and AppDevCon'17 ([slides](https://speakerdeck.com/alisoftware/mixins-over-inheritance-appdevcon-17)) +* [No more String-typed instantiations on iOS Development](https://medium.com/@zonilyjame/reusable-no-more-string-typed-instantiations-on-ios-development-aa1a4f59201c) + +# License + +This code is distributed under the MIT license. See the `LICENSE` file for more info. diff --git a/Pods/Reusable/Sources/Storyboard/StoryboardBased.swift b/Pods/Reusable/Sources/Storyboard/StoryboardBased.swift new file mode 100644 index 0000000..1ab0ae2 --- /dev/null +++ b/Pods/Reusable/Sources/Storyboard/StoryboardBased.swift @@ -0,0 +1,49 @@ +/********************************************* + * + * This code is under the MIT License (MIT) + * + * Copyright (c) 2016 AliSoftware + * + *********************************************/ + +#if canImport(UIKit) +import UIKit + +// MARK: Protocol Definition + +/// Make your UIViewController subclasses conform to this protocol when: +/// * they *are* Storyboard-based, and +/// * this ViewController is the initialViewController of your Storyboard +/// +/// to be able to instantiate them from the Storyboard in a type-safe manner +public protocol StoryboardBased: AnyObject { + /// The UIStoryboard to use when we want to instantiate this ViewController + static var sceneStoryboard: UIStoryboard { get } +} + +// MARK: Default Implementation + +public extension StoryboardBased { + /// By default, use the storybaord with the same name as the class + static var sceneStoryboard: UIStoryboard { + return UIStoryboard(name: String(describing: self), bundle: Bundle(for: self)) + } +} + +// MARK: Support for instantiation from Storyboard + +public extension StoryboardBased where Self: UIViewController { + /** + Create an instance of the ViewController from its associated Storyboard's initialViewController + + - returns: instance of the conforming ViewController + */ + static func instantiate() -> Self { + let viewController = sceneStoryboard.instantiateInitialViewController() + guard let typedViewController = viewController as? Self else { + fatalError("The initialViewController of '\(sceneStoryboard)' is not of class '\(self)'") + } + return typedViewController + } +} +#endif diff --git a/Pods/Reusable/Sources/Storyboard/StoryboardSceneBased.swift b/Pods/Reusable/Sources/Storyboard/StoryboardSceneBased.swift new file mode 100644 index 0000000..7ea5880 --- /dev/null +++ b/Pods/Reusable/Sources/Storyboard/StoryboardSceneBased.swift @@ -0,0 +1,55 @@ +/********************************************* + * + * This code is under the MIT License (MIT) + * + * Copyright (c) 2016 AliSoftware + * + *********************************************/ + +#if canImport(UIKit) +import UIKit + +// MARK: Protocol Definition + +/// Make your UIViewController subclasses conform to this protocol when: +/// * they *are* Storyboard-based, and +/// * this ViewController is not the initialViewController of your Storyboard, but a different scene +/// +/// to be able to instantiate them from the Storyboard in a type-safe manner. +/// +/// You need to implement `sceneStoryboard` yourself to indicate the UIStoryboard this scene is from. +public protocol StoryboardSceneBased: AnyObject { + /// The UIStoryboard to use when we want to instantiate this ViewController + static var sceneStoryboard: UIStoryboard { get } + /// The scene identifier to use when we want to instantiate this ViewController from its associated Storyboard + static var sceneIdentifier: String { get } +} + +// MARK: Default Implementation + +public extension StoryboardSceneBased { + /// By default, use the `sceneIdentifier` with the same name as the class + static var sceneIdentifier: String { + return String(describing: self) + } +} + +// MARK: Support for instantiation from Storyboard + +public extension StoryboardSceneBased where Self: UIViewController { + /** + Create an instance of the ViewController from its associated Storyboard and the + Scene with identifier `sceneIdentifier` + + - returns: instance of the conforming ViewController + */ + static func instantiate() -> Self { + let storyboard = Self.sceneStoryboard + let viewController = storyboard.instantiateViewController(withIdentifier: self.sceneIdentifier) + guard let typedViewController = viewController as? Self else { + fatalError("The viewController '\(self.sceneIdentifier)' of '\(storyboard)' is not of class '\(self)'") + } + return typedViewController + } +} +#endif diff --git a/Pods/Reusable/Sources/View/NibLoadable.swift b/Pods/Reusable/Sources/View/NibLoadable.swift new file mode 100755 index 0000000..9676753 --- /dev/null +++ b/Pods/Reusable/Sources/View/NibLoadable.swift @@ -0,0 +1,49 @@ +/********************************************* + * + * This code is under the MIT License (MIT) + * + * Copyright (c) 2016 AliSoftware + * + *********************************************/ + +#if canImport(UIKit) +import UIKit + +// MARK: Protocol Definition + +/// Make your UIView subclasses conform to this protocol when: +/// * they *are* NIB-based, and +/// * this class is used as the XIB's root view +/// +/// to be able to instantiate them from the NIB in a type-safe manner +public protocol NibLoadable: AnyObject { + /// The nib file to use to load a new instance of the View designed in a XIB + static var nib: UINib { get } +} + +// MARK: Default implementation + +public extension NibLoadable { + /// By default, use the nib which have the same name as the name of the class, + /// and located in the bundle of that class + static var nib: UINib { + return UINib(nibName: String(describing: self), bundle: Bundle(for: self)) + } +} + +// MARK: Support for instantiation from NIB + +public extension NibLoadable where Self: UIView { + /** + Returns a `UIView` object instantiated from nib + + - returns: A `NibLoadable`, `UIView` instance + */ + static func loadFromNib() -> Self { + guard let view = nib.instantiate(withOwner: nil, options: nil).first as? Self else { + fatalError("The nib \(nib) expected its root view to be of type \(self)") + } + return view + } +} +#endif diff --git a/Pods/Reusable/Sources/View/NibOwnerLoadable.swift b/Pods/Reusable/Sources/View/NibOwnerLoadable.swift new file mode 100644 index 0000000..d70df54 --- /dev/null +++ b/Pods/Reusable/Sources/View/NibOwnerLoadable.swift @@ -0,0 +1,63 @@ +/********************************************* + * + * This code is under the MIT License (MIT) + * + * Copyright (c) 2016 AliSoftware + * + *********************************************/ + +#if canImport(UIKit) +import UIKit + +// MARK: Protocol Definition + +/// Make your UIView subclasses conform to this protocol when: +/// * they *are* NIB-based, and +/// * this class is used as the XIB's File's Owner +/// +/// to be able to instantiate them from the NIB in a type-safe manner +public protocol NibOwnerLoadable: AnyObject { + /// The nib file to use to load a new instance of the View designed in a XIB + static var nib: UINib { get } +} + +// MARK: Default implementation + +public extension NibOwnerLoadable { + /// By default, use the nib which have the same name as the name of the class, + /// and located in the bundle of that class + static var nib: UINib { + return UINib(nibName: String(describing: self), bundle: Bundle(for: self)) + } +} + +// MARK: Support for instantiation from NIB + +public extension NibOwnerLoadable where Self: UIView { + /** + Adds content loaded from the nib to the end of the receiver's list of subviews and adds constraints automatically. + */ + func loadNibContent() { + let layoutAttributes: [NSLayoutConstraint.Attribute] = [.top, .leading, .bottom, .trailing] + for case let view as UIView in type(of: self).nib.instantiate(withOwner: self, options: nil) { + view.translatesAutoresizingMaskIntoConstraints = false + self.addSubview(view) + NSLayoutConstraint.activate(layoutAttributes.map { attribute in + NSLayoutConstraint( + item: view, attribute: attribute, + relatedBy: .equal, + toItem: self, attribute: attribute, + multiplier: 1, constant: 0.0 + ) + }) + } + } +} +#endif + +/// Swift < 4.2 support +#if !(swift(>=4.2)) +private extension NSLayoutConstraint { + typealias Attribute = NSLayoutAttribute +} +#endif diff --git a/Pods/Reusable/Sources/View/Reusable.swift b/Pods/Reusable/Sources/View/Reusable.swift new file mode 100644 index 0000000..d568886 --- /dev/null +++ b/Pods/Reusable/Sources/View/Reusable.swift @@ -0,0 +1,35 @@ +/********************************************* + * + * This code is under the MIT License (MIT) + * + * Copyright (c) 2016 AliSoftware + * + *********************************************/ + +#if canImport(UIKit) +import UIKit + +// MARK: Protocol definition + +/// Make your `UITableViewCell` and `UICollectionViewCell` subclasses +/// conform to this protocol when they are *not* NIB-based but only code-based +/// to be able to dequeue them in a type-safe manner +public protocol Reusable: AnyObject { + /// The reuse identifier to use when registering and later dequeuing a reusable cell + static var reuseIdentifier: String { get } +} + +/// Make your `UITableViewCell` and `UICollectionViewCell` subclasses +/// conform to this typealias when they *are* NIB-based +/// to be able to dequeue them in a type-safe manner +public typealias NibReusable = Reusable & NibLoadable + +// MARK: - Default implementation + +public extension Reusable { + /// By default, use the name of the class as String for its reuseIdentifier + static var reuseIdentifier: String { + return String(describing: self) + } +} +#endif diff --git a/Pods/Reusable/Sources/View/UICollectionView+Reusable.swift b/Pods/Reusable/Sources/View/UICollectionView+Reusable.swift new file mode 100644 index 0000000..a6f9f2b --- /dev/null +++ b/Pods/Reusable/Sources/View/UICollectionView+Reusable.swift @@ -0,0 +1,132 @@ +/********************************************* + * + * This code is under the MIT License (MIT) + * + * Copyright (c) 2016 AliSoftware + * + *********************************************/ + +#if canImport(UIKit) +import UIKit + +// MARK: Reusable support for UICollectionView + +public extension UICollectionView { + /** + Register a NIB-Based `UICollectionViewCell` subclass (conforming to `Reusable` & `NibLoadable`) + + - parameter cellType: the `UICollectionViewCell` (`Reusable` & `NibLoadable`-conforming) subclass to register + + - seealso: `register(_:,forCellWithReuseIdentifier:)` + */ + final func register(cellType: T.Type) + where T: Reusable & NibLoadable { + self.register(cellType.nib, forCellWithReuseIdentifier: cellType.reuseIdentifier) + } + + /** + Register a Class-Based `UICollectionViewCell` subclass (conforming to `Reusable`) + + - parameter cellType: the `UICollectionViewCell` (`Reusable`-conforming) subclass to register + + - seealso: `register(_:,forCellWithReuseIdentifier:)` + */ + final func register(cellType: T.Type) + where T: Reusable { + self.register(cellType.self, forCellWithReuseIdentifier: cellType.reuseIdentifier) + } + + /** + Returns a reusable `UICollectionViewCell` object for the class inferred by the return-type + + - parameter indexPath: The index path specifying the location of the cell. + - parameter cellType: The cell class to dequeue + + - returns: A `Reusable`, `UICollectionViewCell` instance + + - note: The `cellType` parameter can generally be omitted and infered by the return type, + except when your type is in a variable and cannot be determined at compile time. + - seealso: `dequeueReusableCell(withReuseIdentifier:,for:)` + */ + final func dequeueReusableCell(for indexPath: IndexPath, cellType: T.Type = T.self) -> T + where T: Reusable { + let bareCell = self.dequeueReusableCell(withReuseIdentifier: cellType.reuseIdentifier, for: indexPath) + guard let cell = bareCell as? T else { + fatalError( + "Failed to dequeue a cell with identifier \(cellType.reuseIdentifier) matching type \(cellType.self). " + + "Check that the reuseIdentifier is set properly in your XIB/Storyboard " + + "and that you registered the cell beforehand" + ) + } + return cell + } + + /** + Register a NIB-Based `UICollectionReusableView` subclass (conforming to `Reusable` & `NibLoadable`) + as a Supplementary View + + - parameter supplementaryViewType: the `UIView` (`Reusable` & `NibLoadable`-conforming) subclass + to register as Supplementary View + - parameter elementKind: The kind of supplementary view to create. + + - seealso: `register(_:,forSupplementaryViewOfKind:,withReuseIdentifier:)` + */ + final func register(supplementaryViewType: T.Type, ofKind elementKind: String) + where T: Reusable & NibLoadable { + self.register( + supplementaryViewType.nib, + forSupplementaryViewOfKind: elementKind, + withReuseIdentifier: supplementaryViewType.reuseIdentifier + ) + } + + /** + Register a Class-Based `UICollectionReusableView` subclass (conforming to `Reusable`) as a Supplementary View + + - parameter supplementaryViewType: the `UIView` (`Reusable`-conforming) subclass to register as Supplementary View + - parameter elementKind: The kind of supplementary view to create. + + - seealso: `register(_:,forSupplementaryViewOfKind:,withReuseIdentifier:)` + */ + final func register(supplementaryViewType: T.Type, ofKind elementKind: String) + where T: Reusable { + self.register( + supplementaryViewType.self, + forSupplementaryViewOfKind: elementKind, + withReuseIdentifier: supplementaryViewType.reuseIdentifier + ) + } + + /** + Returns a reusable `UICollectionReusableView` object for the class inferred by the return-type + + - parameter elementKind: The kind of supplementary view to retrieve. + - parameter indexPath: The index path specifying the location of the cell. + - parameter viewType: The view class to dequeue + + - returns: A `Reusable`, `UICollectionReusableView` instance + + - note: The `viewType` parameter can generally be omitted and infered by the return type, + except when your type is in a variable and cannot be determined at compile time. + - seealso: `dequeueReusableSupplementaryView(ofKind:,withReuseIdentifier:,for:)` + */ + final func dequeueReusableSupplementaryView + (ofKind elementKind: String, for indexPath: IndexPath, viewType: T.Type = T.self) -> T + where T: Reusable { + let view = self.dequeueReusableSupplementaryView( + ofKind: elementKind, + withReuseIdentifier: viewType.reuseIdentifier, + for: indexPath + ) + guard let typedView = view as? T else { + fatalError( + "Failed to dequeue a supplementary view with identifier \(viewType.reuseIdentifier) " + + "matching type \(viewType.self). " + + "Check that the reuseIdentifier is set properly in your XIB/Storyboard " + + "and that you registered the supplementary view beforehand" + ) + } + return typedView + } +} +#endif diff --git a/Pods/Reusable/Sources/View/UITableView+Reusable.swift b/Pods/Reusable/Sources/View/UITableView+Reusable.swift new file mode 100644 index 0000000..c5ca194 --- /dev/null +++ b/Pods/Reusable/Sources/View/UITableView+Reusable.swift @@ -0,0 +1,112 @@ +/********************************************* + * + * This code is under the MIT License (MIT) + * + * Copyright (c) 2016 AliSoftware + * + *********************************************/ + +#if canImport(UIKit) +import UIKit + +// MARK: Reusable support for UITableView + +public extension UITableView { + /** + Register a NIB-Based `UITableViewCell` subclass (conforming to `Reusable` & `NibLoadable`) + + - parameter cellType: the `UITableViewCell` (`Reusable` & `NibLoadable`-conforming) subclass to register + + - seealso: `register(_:,forCellReuseIdentifier:)` + */ + final func register(cellType: T.Type) + where T: Reusable & NibLoadable { + self.register(cellType.nib, forCellReuseIdentifier: cellType.reuseIdentifier) + } + + /** + Register a Class-Based `UITableViewCell` subclass (conforming to `Reusable`) + + - parameter cellType: the `UITableViewCell` (`Reusable`-conforming) subclass to register + + - seealso: `register(_:,forCellReuseIdentifier:)` + */ + final func register(cellType: T.Type) + where T: Reusable { + self.register(cellType.self, forCellReuseIdentifier: cellType.reuseIdentifier) + } + + /** + Returns a reusable `UITableViewCell` object for the class inferred by the return-type + + - parameter indexPath: The index path specifying the location of the cell. + - parameter cellType: The cell class to dequeue + + - returns: A `Reusable`, `UITableViewCell` instance + + - note: The `cellType` parameter can generally be omitted and infered by the return type, + except when your type is in a variable and cannot be determined at compile time. + - seealso: `dequeueReusableCell(withIdentifier:,for:)` + */ + final func dequeueReusableCell(for indexPath: IndexPath, cellType: T.Type = T.self) -> T + where T: Reusable { + guard let cell = self.dequeueReusableCell(withIdentifier: cellType.reuseIdentifier, for: indexPath) as? T else { + fatalError( + "Failed to dequeue a cell with identifier \(cellType.reuseIdentifier) matching type \(cellType.self). " + + "Check that the reuseIdentifier is set properly in your XIB/Storyboard " + + "and that you registered the cell beforehand" + ) + } + return cell + } + + /** + Register a NIB-Based `UITableViewHeaderFooterView` subclass (conforming to `Reusable` & `NibLoadable`) + + - parameter headerFooterViewType: the `UITableViewHeaderFooterView` (`Reusable` & `NibLoadable`-conforming) + subclass to register + + - seealso: `register(_:,forHeaderFooterViewReuseIdentifier:)` + */ + final func register(headerFooterViewType: T.Type) + where T: Reusable & NibLoadable { + self.register(headerFooterViewType.nib, forHeaderFooterViewReuseIdentifier: headerFooterViewType.reuseIdentifier) + } + + /** + Register a Class-Based `UITableViewHeaderFooterView` subclass (conforming to `Reusable`) + + - parameter headerFooterViewType: the `UITableViewHeaderFooterView` (`Reusable`-confirming) subclass to register + + - seealso: `register(_:,forHeaderFooterViewReuseIdentifier:)` + */ + final func register(headerFooterViewType: T.Type) + where T: Reusable { + self.register(headerFooterViewType.self, forHeaderFooterViewReuseIdentifier: headerFooterViewType.reuseIdentifier) + } + + /** + Returns a reusable `UITableViewHeaderFooterView` object for the class inferred by the return-type + + - parameter viewType: The view class to dequeue + + - returns: A `Reusable`, `UITableViewHeaderFooterView` instance + + - note: The `viewType` parameter can generally be omitted and infered by the return type, + except when your type is in a variable and cannot be determined at compile time. + - seealso: `dequeueReusableHeaderFooterView(withIdentifier:)` + */ + final func dequeueReusableHeaderFooterView(_ viewType: T.Type = T.self) -> T? + where T: Reusable { + guard let view = self.dequeueReusableHeaderFooterView(withIdentifier: viewType.reuseIdentifier) as? T? else { + fatalError( + "Failed to dequeue a header/footer with identifier \(viewType.reuseIdentifier) " + + "matching type \(viewType.self). " + + "Check that the reuseIdentifier is set properly in your XIB/Storyboard " + + "and that you registered the header/footer beforehand" + ) + } + return view + } +} +#endif diff --git a/Pods/RxCocoa/LICENSE.md b/Pods/RxCocoa/LICENSE.md new file mode 100644 index 0000000..e32511b --- /dev/null +++ b/Pods/RxCocoa/LICENSE.md @@ -0,0 +1,9 @@ +**The MIT License** +**Copyright © 2015 Krunoslav Zaher, Shai Mishali** +**All rights reserved.** + +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/RxCocoa/Platform/DataStructures/Bag.swift b/Pods/RxCocoa/Platform/DataStructures/Bag.swift new file mode 100644 index 0000000..5720a3b --- /dev/null +++ b/Pods/RxCocoa/Platform/DataStructures/Bag.swift @@ -0,0 +1,181 @@ +// +// Bag.swift +// Platform +// +// Created by Krunoslav Zaher on 2/28/15. +// Copyright © 2015 Krunoslav Zaher. All rights reserved. +// + +import Swift + +let arrayDictionaryMaxSize = 30 + +struct BagKey { + /** + Unique identifier for object added to `Bag`. + + It's underlying type is UInt64. If we assume there in an idealized CPU that works at 4GHz, + it would take ~150 years of continuous running time for it to overflow. + */ + fileprivate let rawValue: UInt64 +} + +/** +Data structure that represents a bag of elements typed `T`. + +Single element can be stored multiple times. + +Time and space complexity of insertion and deletion is O(n). + +It is suitable for storing small number of elements. +*/ +struct Bag : CustomDebugStringConvertible { + /// Type of identifier for inserted elements. + typealias KeyType = BagKey + + typealias Entry = (key: BagKey, value: T) + + private var _nextKey: BagKey = BagKey(rawValue: 0) + + // data + + // first fill inline variables + var _key0: BagKey? + var _value0: T? + + // then fill "array dictionary" + var _pairs = ContiguousArray() + + // last is sparse dictionary + var _dictionary: [BagKey: T]? + + var _onlyFastPath = true + + /// Creates new empty `Bag`. + init() { + } + + /** + Inserts `value` into bag. + + - parameter element: Element to insert. + - returns: Key that can be used to remove element from bag. + */ + mutating func insert(_ element: T) -> BagKey { + let key = _nextKey + + _nextKey = BagKey(rawValue: _nextKey.rawValue &+ 1) + + if _key0 == nil { + _key0 = key + _value0 = element + return key + } + + _onlyFastPath = false + + if _dictionary != nil { + _dictionary![key] = element + return key + } + + if _pairs.count < arrayDictionaryMaxSize { + _pairs.append((key: key, value: element)) + return key + } + + _dictionary = [key: element] + + return key + } + + /// - returns: Number of elements in bag. + var count: Int { + let dictionaryCount: Int = _dictionary?.count ?? 0 + return (_value0 != nil ? 1 : 0) + _pairs.count + dictionaryCount + } + + /// Removes all elements from bag and clears capacity. + mutating func removeAll() { + _key0 = nil + _value0 = nil + + _pairs.removeAll(keepingCapacity: false) + _dictionary?.removeAll(keepingCapacity: false) + } + + /** + Removes element with a specific `key` from bag. + + - parameter key: Key that identifies element to remove from bag. + - returns: Element that bag contained, or nil in case element was already removed. + */ + mutating func removeKey(_ key: BagKey) -> T? { + if _key0 == key { + _key0 = nil + let value = _value0! + _value0 = nil + return value + } + + if let existingObject = _dictionary?.removeValue(forKey: key) { + return existingObject + } + + for i in 0 ..< _pairs.count where _pairs[i].key == key { + let value = _pairs[i].value + _pairs.remove(at: i) + return value + } + + return nil + } +} + +extension Bag { + /// A textual representation of `self`, suitable for debugging. + var debugDescription : String { + "\(self.count) elements in Bag" + } +} + +extension Bag { + /// Enumerates elements inside the bag. + /// + /// - parameter action: Enumeration closure. + func forEach(_ action: (T) -> Void) { + if _onlyFastPath { + if let value0 = _value0 { + action(value0) + } + return + } + + let value0 = _value0 + let dictionary = _dictionary + + if let value0 = value0 { + action(value0) + } + + for i in 0 ..< _pairs.count { + action(_pairs[i].value) + } + + if dictionary?.count ?? 0 > 0 { + for element in dictionary!.values { + action(element) + } + } + } +} + +extension BagKey: Hashable { + func hash(into hasher: inout Hasher) { + hasher.combine(rawValue) + } +} + +func ==(lhs: BagKey, rhs: BagKey) -> Bool { + lhs.rawValue == rhs.rawValue +} diff --git a/Pods/RxCocoa/Platform/DataStructures/InfiniteSequence.swift b/Pods/RxCocoa/Platform/DataStructures/InfiniteSequence.swift new file mode 100644 index 0000000..75d7bea --- /dev/null +++ b/Pods/RxCocoa/Platform/DataStructures/InfiniteSequence.swift @@ -0,0 +1,23 @@ +// +// InfiniteSequence.swift +// Platform +// +// Created by Krunoslav Zaher on 6/13/15. +// Copyright © 2015 Krunoslav Zaher. All rights reserved. +// + +/// Sequence that repeats `repeatedValue` infinite number of times. +struct InfiniteSequence : Sequence { + typealias Iterator = AnyIterator + + private let repeatedValue: Element + + init(repeatedValue: Element) { + self.repeatedValue = repeatedValue + } + + func makeIterator() -> Iterator { + let repeatedValue = self.repeatedValue + return AnyIterator { repeatedValue } + } +} diff --git a/Pods/RxCocoa/Platform/DataStructures/PriorityQueue.swift b/Pods/RxCocoa/Platform/DataStructures/PriorityQueue.swift new file mode 100644 index 0000000..9ed856b --- /dev/null +++ b/Pods/RxCocoa/Platform/DataStructures/PriorityQueue.swift @@ -0,0 +1,111 @@ +// +// PriorityQueue.swift +// Platform +// +// Created by Krunoslav Zaher on 12/27/15. +// Copyright © 2015 Krunoslav Zaher. All rights reserved. +// + +struct PriorityQueue { + private let hasHigherPriority: (Element, Element) -> Bool + private let isEqual: (Element, Element) -> Bool + + private var elements = [Element]() + + init(hasHigherPriority: @escaping (Element, Element) -> Bool, isEqual: @escaping (Element, Element) -> Bool) { + self.hasHigherPriority = hasHigherPriority + self.isEqual = isEqual + } + + mutating func enqueue(_ element: Element) { + elements.append(element) + bubbleToHigherPriority(elements.count - 1) + } + + func peek() -> Element? { + elements.first + } + + var isEmpty: Bool { + elements.count == 0 + } + + mutating func dequeue() -> Element? { + guard let front = peek() else { + return nil + } + + removeAt(0) + + return front + } + + mutating func remove(_ element: Element) { + for i in 0 ..< elements.count { + if self.isEqual(elements[i], element) { + removeAt(i) + return + } + } + } + + private mutating func removeAt(_ index: Int) { + let removingLast = index == elements.count - 1 + if !removingLast { + elements.swapAt(index, elements.count - 1) + } + + _ = elements.popLast() + + if !removingLast { + bubbleToHigherPriority(index) + bubbleToLowerPriority(index) + } + } + + private mutating func bubbleToHigherPriority(_ initialUnbalancedIndex: Int) { + precondition(initialUnbalancedIndex >= 0) + precondition(initialUnbalancedIndex < elements.count) + + var unbalancedIndex = initialUnbalancedIndex + + while unbalancedIndex > 0 { + let parentIndex = (unbalancedIndex - 1) / 2 + guard self.hasHigherPriority(elements[unbalancedIndex], elements[parentIndex]) else { break } + elements.swapAt(unbalancedIndex, parentIndex) + unbalancedIndex = parentIndex + } + } + + private mutating func bubbleToLowerPriority(_ initialUnbalancedIndex: Int) { + precondition(initialUnbalancedIndex >= 0) + precondition(initialUnbalancedIndex < elements.count) + + var unbalancedIndex = initialUnbalancedIndex + while true { + let leftChildIndex = unbalancedIndex * 2 + 1 + let rightChildIndex = unbalancedIndex * 2 + 2 + + var highestPriorityIndex = unbalancedIndex + + if leftChildIndex < elements.count && self.hasHigherPriority(elements[leftChildIndex], elements[highestPriorityIndex]) { + highestPriorityIndex = leftChildIndex + } + + if rightChildIndex < elements.count && self.hasHigherPriority(elements[rightChildIndex], elements[highestPriorityIndex]) { + highestPriorityIndex = rightChildIndex + } + + guard highestPriorityIndex != unbalancedIndex else { break } + elements.swapAt(highestPriorityIndex, unbalancedIndex) + + unbalancedIndex = highestPriorityIndex + } + } +} + +extension PriorityQueue : CustomDebugStringConvertible { + var debugDescription: String { + elements.debugDescription + } +} diff --git a/Pods/RxCocoa/Platform/DataStructures/Queue.swift b/Pods/RxCocoa/Platform/DataStructures/Queue.swift new file mode 100644 index 0000000..625d473 --- /dev/null +++ b/Pods/RxCocoa/Platform/DataStructures/Queue.swift @@ -0,0 +1,148 @@ +// +// Queue.swift +// Platform +// +// Created by Krunoslav Zaher on 3/21/15. +// Copyright © 2015 Krunoslav Zaher. All rights reserved. +// + +/** +Data structure that represents queue. + +Complexity of `enqueue`, `dequeue` is O(1) when number of operations is +averaged over N operations. + +Complexity of `peek` is O(1). +*/ +struct Queue: Sequence { + /// Type of generator. + typealias Generator = AnyIterator + + private let resizeFactor = 2 + + private var storage: ContiguousArray + private var innerCount = 0 + private var pushNextIndex = 0 + private let initialCapacity: Int + + /** + Creates new queue. + + - parameter capacity: Capacity of newly created queue. + */ + init(capacity: Int) { + initialCapacity = capacity + + storage = ContiguousArray(repeating: nil, count: capacity) + } + + private var dequeueIndex: Int { + let index = pushNextIndex - count + return index < 0 ? index + storage.count : index + } + + /// - returns: Is queue empty. + var isEmpty: Bool { count == 0 } + + /// - returns: Number of elements inside queue. + var count: Int { innerCount } + + /// - returns: Element in front of a list of elements to `dequeue`. + func peek() -> T { + precondition(count > 0) + + return storage[dequeueIndex]! + } + + mutating private func resizeTo(_ size: Int) { + var newStorage = ContiguousArray(repeating: nil, count: size) + + let count = self.count + + let dequeueIndex = self.dequeueIndex + let spaceToEndOfQueue = storage.count - dequeueIndex + + // first batch is from dequeue index to end of array + let countElementsInFirstBatch = Swift.min(count, spaceToEndOfQueue) + // second batch is wrapped from start of array to end of queue + let numberOfElementsInSecondBatch = count - countElementsInFirstBatch + + newStorage[0 ..< countElementsInFirstBatch] = storage[dequeueIndex ..< (dequeueIndex + countElementsInFirstBatch)] + newStorage[countElementsInFirstBatch ..< (countElementsInFirstBatch + numberOfElementsInSecondBatch)] = storage[0 ..< numberOfElementsInSecondBatch] + + self.innerCount = count + pushNextIndex = count + storage = newStorage + } + + /// Enqueues `element`. + /// + /// - parameter element: Element to enqueue. + mutating func enqueue(_ element: T) { + if count == storage.count { + resizeTo(Swift.max(storage.count, 1) * resizeFactor) + } + + storage[pushNextIndex] = element + pushNextIndex += 1 + innerCount += 1 + + if pushNextIndex >= storage.count { + pushNextIndex -= storage.count + } + } + + private mutating func dequeueElementOnly() -> T { + precondition(count > 0) + + let index = dequeueIndex + + defer { + storage[index] = nil + innerCount -= 1 + } + + return storage[index]! + } + + /// Dequeues element or throws an exception in case queue is empty. + /// + /// - returns: Dequeued element. + mutating func dequeue() -> T? { + if self.count == 0 { + return nil + } + + defer { + let downsizeLimit = storage.count / (resizeFactor * resizeFactor) + if count < downsizeLimit && downsizeLimit >= initialCapacity { + resizeTo(storage.count / resizeFactor) + } + } + + return dequeueElementOnly() + } + + /// - returns: Generator of contained elements. + func makeIterator() -> AnyIterator { + var i = dequeueIndex + var innerCount = count + + return AnyIterator { + if innerCount == 0 { + return nil + } + + defer { + innerCount -= 1 + i += 1 + } + + if i >= self.storage.count { + i -= self.storage.count + } + + return self.storage[i] + } + } +} diff --git a/Pods/RxCocoa/Platform/DispatchQueue+Extensions.swift b/Pods/RxCocoa/Platform/DispatchQueue+Extensions.swift new file mode 100644 index 0000000..aaf24ca --- /dev/null +++ b/Pods/RxCocoa/Platform/DispatchQueue+Extensions.swift @@ -0,0 +1,21 @@ +// +// DispatchQueue+Extensions.swift +// Platform +// +// Created by Krunoslav Zaher on 10/22/16. +// Copyright © 2016 Krunoslav Zaher. All rights reserved. +// + +import Dispatch + +extension DispatchQueue { + private static var token: DispatchSpecificKey<()> = { + let key = DispatchSpecificKey<()>() + DispatchQueue.main.setSpecific(key: key, value: ()) + return key + }() + + static var isMain: Bool { + DispatchQueue.getSpecific(key: token) != nil + } +} diff --git a/Pods/RxCocoa/Platform/Platform.Darwin.swift b/Pods/RxCocoa/Platform/Platform.Darwin.swift new file mode 100644 index 0000000..eacc194 --- /dev/null +++ b/Pods/RxCocoa/Platform/Platform.Darwin.swift @@ -0,0 +1,35 @@ +// +// Platform.Darwin.swift +// Platform +// +// Created by Krunoslav Zaher on 12/29/15. +// Copyright © 2015 Krunoslav Zaher. All rights reserved. +// + +#if os(macOS) || os(iOS) || os(tvOS) || os(watchOS) + + import Darwin + import Foundation + + extension Thread { + static func setThreadLocalStorageValue(_ value: T?, forKey key: NSCopying) { + let currentThread = Thread.current + let threadDictionary = currentThread.threadDictionary + + if let newValue = value { + threadDictionary[key] = newValue + } + else { + threadDictionary[key] = nil + } + } + + static func getThreadLocalStorageValueForKey(_ key: NSCopying) -> T? { + let currentThread = Thread.current + let threadDictionary = currentThread.threadDictionary + + return threadDictionary[key] as? T + } + } + +#endif diff --git a/Pods/RxCocoa/Platform/Platform.Linux.swift b/Pods/RxCocoa/Platform/Platform.Linux.swift new file mode 100644 index 0000000..52a3e3a --- /dev/null +++ b/Pods/RxCocoa/Platform/Platform.Linux.swift @@ -0,0 +1,32 @@ +// +// Platform.Linux.swift +// Platform +// +// Created by Krunoslav Zaher on 12/29/15. +// Copyright © 2015 Krunoslav Zaher. All rights reserved. +// + +#if os(Linux) + + import Foundation + + extension Thread { + + static func setThreadLocalStorageValue(_ value: T?, forKey key: String) { + if let newValue = value { + Thread.current.threadDictionary[key] = newValue + } + else { + Thread.current.threadDictionary[key] = nil + } + } + + static func getThreadLocalStorageValueForKey(_ key: String) -> T? { + let currentThread = Thread.current + let threadDictionary = currentThread.threadDictionary + + return threadDictionary[key] as? T + } + } + +#endif diff --git a/Pods/RxCocoa/Platform/RecursiveLock.swift b/Pods/RxCocoa/Platform/RecursiveLock.swift new file mode 100644 index 0000000..10b9bbb --- /dev/null +++ b/Pods/RxCocoa/Platform/RecursiveLock.swift @@ -0,0 +1,34 @@ +// +// RecursiveLock.swift +// Platform +// +// Created by Krunoslav Zaher on 12/18/16. +// Copyright © 2016 Krunoslav Zaher. All rights reserved. +// + +import Foundation + +#if TRACE_RESOURCES + class RecursiveLock: NSRecursiveLock { + override init() { + _ = Resources.incrementTotal() + super.init() + } + + override func lock() { + super.lock() + _ = Resources.incrementTotal() + } + + override func unlock() { + super.unlock() + _ = Resources.decrementTotal() + } + + deinit { + _ = Resources.decrementTotal() + } + } +#else + typealias RecursiveLock = NSRecursiveLock +#endif diff --git a/Pods/RxCocoa/README.md b/Pods/RxCocoa/README.md new file mode 100644 index 0000000..a95d9e0 --- /dev/null +++ b/Pods/RxCocoa/README.md @@ -0,0 +1,254 @@ +

+RxSwift Logo +
+Build Status +Supported Platforms: iOS, macOS, tvOS, watchOS & Linux +
+ + + +

+ +Rx is a [generic abstraction of computation](https://youtu.be/looJcaeboBY) expressed through `Observable` interface, which lets you broadcast and subscribe to values and other events from an `Observable` stream. + +RxSwift is the Swift-specific implementation of the [Reactive Extensions](http://reactivex.io) standard. + +

RxSwift Observable Example of a price constantly changing and updating the app's UI

+ +While this version aims to stay true to the original spirit and naming conventions of Rx, this projects also aims to provide a true Swift-first API for Rx APIs. + +Cross platform documentation can be found on [ReactiveX.io](http://reactivex.io/). + +Like other Rx implementation, RxSwift's intention is to enable easy composition of asynchronous operations and streams of data in the form of `Observable` objects and a suite of methods to transform and compose these pieces of asynchronous work. + +KVO observation, async operations, UI Events and other streams of data are all unified under [abstraction of sequence](Documentation/GettingStarted.md#observables-aka-sequences). This is the reason why Rx is so simple, elegant and powerful. + +## I came here because I want to ... + +###### ... understand + +* [why use rx?](Documentation/Why.md) +* [the basics, getting started with RxSwift](Documentation/GettingStarted.md) +* [traits](Documentation/Traits.md) - what are `Single`, `Completable`, `Maybe`, `Driver`, and `ControlProperty` ... and why do they exist? +* [testing](Documentation/UnitTests.md) +* [tips and common errors](Documentation/Tips.md) +* [debugging](Documentation/GettingStarted.md#debugging) +* [the math behind Rx](Documentation/MathBehindRx.md) +* [what are hot and cold observable sequences?](Documentation/HotAndColdObservables.md) + +###### ... install + +* Integrate RxSwift/RxCocoa with my app. [Installation Guide](#installation) + +###### ... hack around + +* with the example app. [Running Example App](Documentation/ExampleApp.md) +* with operators in playgrounds. [Playgrounds](Documentation/Playgrounds.md) + +###### ... interact + +* All of this is great, but it would be nice to talk with other people using RxSwift and exchange experiences.
[Join Slack Channel](http://slack.rxswift.org) +* Report a problem using the library. [Open an Issue With Bug Template](.github/ISSUE_TEMPLATE.md) +* Request a new feature. [Open an Issue With Feature Request Template](Documentation/NewFeatureRequestTemplate.md) +* Help out [Check out contribution guide](CONTRIBUTING.md) + +###### ... compare + +* [with Combine and ReactiveSwift](Documentation/ComparisonWithOtherLibraries.md). + +###### ... understand the structure + +RxSwift is as compositional as the asynchronous work it drives. The core unit is RxSwift itself, while other dependencies can be added for UI Work, testing, and more. + +It comprises five separate components depending on each other in the following way: + +```none +┌──────────────┐ ┌──────────────┐ +│ RxCocoa ├────▶ RxRelay │ +└───────┬──────┘ └──────┬───────┘ + │ │ +┌───────▼──────────────────▼───────┐ +│ RxSwift │ +└───────▲──────────────────▲───────┘ + │ │ +┌───────┴──────┐ ┌──────┴───────┐ +│ RxTest │ │ RxBlocking │ +└──────────────┘ └──────────────┘ +``` + +* **RxSwift**: The core of RxSwift, providing the Rx standard as (mostly) defined by [ReactiveX](https://reactivex.io). It has no other dependencies. +* **RxCocoa**: Provides Cocoa-specific capabilities for general iOS/macOS/watchOS & tvOS app development, such as Shared Sequences, Traits, and much more. It depends on both `RxSwift` and `RxRelay`. +* **RxRelay**: Provides `PublishRelay`, `BehaviorRelay` and `ReplayRelay`, three [simple wrappers around Subjects](https://github.com/ReactiveX/RxSwift/blob/main/Documentation/Subjects.md#relays). It depends on `RxSwift`. +* **RxTest** and **RxBlocking**: Provides testing capabilities for Rx-based systems. It depends on `RxSwift`. + +## Usage + + + + + + + + + + + + + + + + + + + +
Here's an exampleIn Action
Define search for GitHub repositories ...
+let searchResults = searchBar.rx.text.orEmpty
+    .throttle(.milliseconds(300), scheduler: MainScheduler.instance)
+    .distinctUntilChanged()
+    .flatMapLatest { query -> Observable<[Repository]> in
+        if query.isEmpty {
+            return .just([])
+        }
+        return searchGitHub(query)
+            .catchAndReturn([])
+    }
+    .observe(on: MainScheduler.instance)
... then bind the results to your tableview
+searchResults
+    .bind(to: tableView.rx.items(cellIdentifier: "Cell")) {
+        (index, repository: Repository, cell) in
+        cell.textLabel?.text = repository.name
+        cell.detailTextLabel?.text = repository.url
+    }
+    .disposed(by: disposeBag)
+ + +## Requirements + +* Xcode 12.x +* Swift 5.x + +For Xcode 11 and below, [use RxSwift 5.x](https://github.com/ReactiveX/RxSwift/releases/tag/5.1.1). + +## Installation + +RxSwift doesn't contain any external dependencies. + +These are currently the supported installation options: + +### Manual + +Open Rx.xcworkspace, choose `RxExample` and hit run. This method will build everything and run the sample app + +### [CocoaPods](https://guides.cocoapods.org/using/using-cocoapods.html) + +```ruby +# Podfile +use_frameworks! + +target 'YOUR_TARGET_NAME' do + pod 'RxSwift', '6.5.0' + pod 'RxCocoa', '6.5.0' +end + +# RxTest and RxBlocking make the most sense in the context of unit/integration tests +target 'YOUR_TESTING_TARGET' do + pod 'RxBlocking', '6.5.0' + pod 'RxTest', '6.5.0' +end +``` + +Replace `YOUR_TARGET_NAME` and then, in the `Podfile` directory, type: + +```bash +$ pod install +``` + +### XCFrameworks + +Each release starting with RxSwift 6 includes `*.xcframework` framework binaries. + +Simply drag the needed framework binaries to your **Frameworks, Libraries, and Embedded Content** section under your target's **General** tab. + +> **Note**: If you're using `RxCocoa`, be sure to also drag **RxCocoaRuntime.xcframework** before importing `RxCocoa`. + +XCFrameworks instructions + +### [Carthage](https://github.com/Carthage/Carthage) + +Add this to `Cartfile` + +``` +github "ReactiveX/RxSwift" "6.5.0" +``` + +```bash +$ carthage update +``` + +#### Carthage as a Static Library + +Carthage defaults to building RxSwift as a Dynamic Library. + +If you wish to build RxSwift as a Static Library using Carthage you may use the script below to manually modify the framework type before building with Carthage: + +```bash +carthage update RxSwift --platform iOS --no-build +sed -i -e 's/MACH_O_TYPE = mh_dylib/MACH_O_TYPE = staticlib/g' Carthage/Checkouts/RxSwift/Rx.xcodeproj/project.pbxproj +carthage build RxSwift --platform iOS +``` + +### [Swift Package Manager](https://github.com/apple/swift-package-manager) + +> **Note**: There is a critical cross-dependency bug affecting many projects including RxSwift in Swift Package Manager. We've [filed a bug (SR-12303)](https://bugs.swift.org/browse/SR-12303) in early 2020 but have no answer yet. Your mileage may vary. A partial workaround can be found [here](https://github.com/ReactiveX/RxSwift/issues/2127#issuecomment-717830502). + +Create a `Package.swift` file. + +```swift +// swift-tools-version:5.0 + +import PackageDescription + +let package = Package( + name: "RxTestProject", + dependencies: [ + .package(url: "https://github.com/ReactiveX/RxSwift.git", .exact("6.5.0")) + ], + targets: [ + .target(name: "RxTestProject", dependencies: ["RxSwift", "RxCocoa"]) + ] +) +``` + +```bash +$ swift build +``` + +To build or test a module with RxTest dependency, set `TEST=1`. + +```bash +$ TEST=1 swift test +``` + +### Manually using git submodules + +* Add RxSwift as a submodule + +```bash +$ git submodule add git@github.com:ReactiveX/RxSwift.git +``` + +* Drag `Rx.xcodeproj` into Project Navigator +* Go to `Project > Targets > Build Phases > Link Binary With Libraries`, click `+` and select `RxSwift`, `RxCocoa` and `RxRelay` targets + +## References + +* [http://reactivex.io/](http://reactivex.io/) +* [Reactive Extensions GitHub (GitHub)](https://github.com/Reactive-Extensions) +* [RxSwift RayWenderlich.com Book](https://store.raywenderlich.com/products/rxswift-reactive-programming-with-swift) +* [RxSwift: Debunking the myth of hard (YouTube)](https://www.youtube.com/watch?v=GdvLP0ZAhhc) +* [Boxue.io RxSwift Online Course](https://boxueio.com/series/rxswift-101) (Chinese 🇨🇳) +* [Expert to Expert: Brian Beckman and Erik Meijer - Inside the .NET Reactive Framework (Rx) (video)](https://youtu.be/looJcaeboBY) +* [Reactive Programming Overview (Jafar Husain from Netflix)](https://youtu.be/-8Y1-lE6NSA) +* [Subject/Observer is Dual to Iterator (paper)](http://csl.stanford.edu/~christos/pldi2010.fit/meijer.duality.pdf) +* [Rx standard sequence operators visualized (visualization tool)](http://rxmarbles.com/) +* [Haskell](https://www.haskell.org/) diff --git a/Pods/RxCocoa/RxCocoa/Common/ControlTarget.swift b/Pods/RxCocoa/RxCocoa/Common/ControlTarget.swift new file mode 100644 index 0000000..231c3fe --- /dev/null +++ b/Pods/RxCocoa/RxCocoa/Common/ControlTarget.swift @@ -0,0 +1,88 @@ +// +// ControlTarget.swift +// RxCocoa +// +// Created by Krunoslav Zaher on 2/21/15. +// Copyright © 2015 Krunoslav Zaher. All rights reserved. +// + +#if os(iOS) || os(tvOS) || os(macOS) + +import RxSwift + +#if os(iOS) || os(tvOS) + import UIKit + + typealias Control = UIKit.UIControl +#elseif os(macOS) + import Cocoa + + typealias Control = Cocoa.NSControl +#endif + +// This should be only used from `MainScheduler` +final class ControlTarget: RxTarget { + typealias Callback = (Control) -> Void + + let selector: Selector = #selector(ControlTarget.eventHandler(_:)) + + weak var control: Control? +#if os(iOS) || os(tvOS) + let controlEvents: UIControl.Event +#endif + var callback: Callback? + #if os(iOS) || os(tvOS) + init(control: Control, controlEvents: UIControl.Event, callback: @escaping Callback) { + MainScheduler.ensureRunningOnMainThread() + + self.control = control + self.controlEvents = controlEvents + self.callback = callback + + super.init() + + control.addTarget(self, action: selector, for: controlEvents) + + let method = self.method(for: selector) + if method == nil { + rxFatalError("Can't find method") + } + } +#elseif os(macOS) + init(control: Control, callback: @escaping Callback) { + MainScheduler.ensureRunningOnMainThread() + + self.control = control + self.callback = callback + + super.init() + + control.target = self + control.action = self.selector + + let method = self.method(for: self.selector) + if method == nil { + rxFatalError("Can't find method") + } + } +#endif + + @objc func eventHandler(_ sender: Control!) { + if let callback = self.callback, let control = self.control { + callback(control) + } + } + + override func dispose() { + super.dispose() +#if os(iOS) || os(tvOS) + self.control?.removeTarget(self, action: self.selector, for: self.controlEvents) +#elseif os(macOS) + self.control?.target = nil + self.control?.action = nil +#endif + self.callback = nil + } +} + +#endif diff --git a/Pods/RxCocoa/RxCocoa/Common/DelegateProxy.swift b/Pods/RxCocoa/RxCocoa/Common/DelegateProxy.swift new file mode 100644 index 0000000..d103448 --- /dev/null +++ b/Pods/RxCocoa/RxCocoa/Common/DelegateProxy.swift @@ -0,0 +1,294 @@ +// +// DelegateProxy.swift +// RxCocoa +// +// Created by Krunoslav Zaher on 6/14/15. +// Copyright © 2015 Krunoslav Zaher. All rights reserved. +// + +#if !os(Linux) + + import RxSwift + #if SWIFT_PACKAGE && !os(Linux) + import RxCocoaRuntime + #endif + + /// Base class for `DelegateProxyType` protocol. + /// + /// This implementation is not thread safe and can be used only from one thread (Main thread). + open class DelegateProxy: _RXDelegateProxy { + public typealias ParentObject = P + public typealias Delegate = D + + private var _sentMessageForSelector = [Selector: MessageDispatcher]() + private var _methodInvokedForSelector = [Selector: MessageDispatcher]() + + /// Parent object associated with delegate proxy. + private weak var _parentObject: ParentObject? + + private let _currentDelegateFor: (ParentObject) -> AnyObject? + private let _setCurrentDelegateTo: (AnyObject?, ParentObject) -> Void + + /// Initializes new instance. + /// + /// - parameter parentObject: Optional parent object that owns `DelegateProxy` as associated object. + public init(parentObject: ParentObject, delegateProxy: Proxy.Type) + where Proxy: DelegateProxy, Proxy.ParentObject == ParentObject, Proxy.Delegate == Delegate { + self._parentObject = parentObject + self._currentDelegateFor = delegateProxy._currentDelegate + self._setCurrentDelegateTo = delegateProxy._setCurrentDelegate + + MainScheduler.ensureRunningOnMainThread() + #if TRACE_RESOURCES + _ = Resources.incrementTotal() + #endif + super.init() + } + + /** + Returns observable sequence of invocations of delegate methods. Elements are sent *before method is invoked*. + + Only methods that have `void` return value can be observed using this method because + those methods are used as a notification mechanism. It doesn't matter if they are optional + or not. Observing is performed by installing a hidden associated `PublishSubject` that is + used to dispatch messages to observers. + + Delegate methods that have non `void` return value can't be observed directly using this method + because: + * those methods are not intended to be used as a notification mechanism, but as a behavior customization mechanism + * there is no sensible automatic way to determine a default return value + + In case observing of delegate methods that have return type is required, it can be done by + manually installing a `PublishSubject` or `BehaviorSubject` and implementing delegate method. + + e.g. + + // delegate proxy part (RxScrollViewDelegateProxy) + + let internalSubject = PublishSubject + + public func requiredDelegateMethod(scrollView: UIScrollView, arg1: CGPoint) -> Bool { + internalSubject.on(.next(arg1)) + return self._forwardToDelegate?.requiredDelegateMethod?(scrollView, arg1: arg1) ?? defaultReturnValue + } + + .... + + // reactive property implementation in a real class (`UIScrollView`) + public var property: Observable { + let proxy = RxScrollViewDelegateProxy.proxy(for: base) + return proxy.internalSubject.asObservable() + } + + **In case calling this method prints "Delegate proxy is already implementing `\(selector)`, + a more performant way of registering might exist.", that means that manual observing method + is required analog to the example above because delegate method has already been implemented.** + + - parameter selector: Selector used to filter observed invocations of delegate methods. + - returns: Observable sequence of arguments passed to `selector` method. + */ + open func sentMessage(_ selector: Selector) -> Observable<[Any]> { + MainScheduler.ensureRunningOnMainThread() + + let subject = self._sentMessageForSelector[selector] + + if let subject = subject { + return subject.asObservable() + } + else { + let subject = MessageDispatcher(selector: selector, delegateProxy: self) + self._sentMessageForSelector[selector] = subject + return subject.asObservable() + } + } + + /** + Returns observable sequence of invoked delegate methods. Elements are sent *after method is invoked*. + + Only methods that have `void` return value can be observed using this method because + those methods are used as a notification mechanism. It doesn't matter if they are optional + or not. Observing is performed by installing a hidden associated `PublishSubject` that is + used to dispatch messages to observers. + + Delegate methods that have non `void` return value can't be observed directly using this method + because: + * those methods are not intended to be used as a notification mechanism, but as a behavior customization mechanism + * there is no sensible automatic way to determine a default return value + + In case observing of delegate methods that have return type is required, it can be done by + manually installing a `PublishSubject` or `BehaviorSubject` and implementing delegate method. + + e.g. + + // delegate proxy part (RxScrollViewDelegateProxy) + + let internalSubject = PublishSubject + + public func requiredDelegateMethod(scrollView: UIScrollView, arg1: CGPoint) -> Bool { + internalSubject.on(.next(arg1)) + return self._forwardToDelegate?.requiredDelegateMethod?(scrollView, arg1: arg1) ?? defaultReturnValue + } + + .... + + // reactive property implementation in a real class (`UIScrollView`) + public var property: Observable { + let proxy = RxScrollViewDelegateProxy.proxy(for: base) + return proxy.internalSubject.asObservable() + } + + **In case calling this method prints "Delegate proxy is already implementing `\(selector)`, + a more performant way of registering might exist.", that means that manual observing method + is required analog to the example above because delegate method has already been implemented.** + + - parameter selector: Selector used to filter observed invocations of delegate methods. + - returns: Observable sequence of arguments passed to `selector` method. + */ + open func methodInvoked(_ selector: Selector) -> Observable<[Any]> { + MainScheduler.ensureRunningOnMainThread() + + let subject = self._methodInvokedForSelector[selector] + + if let subject = subject { + return subject.asObservable() + } + else { + let subject = MessageDispatcher(selector: selector, delegateProxy: self) + self._methodInvokedForSelector[selector] = subject + return subject.asObservable() + } + } + + fileprivate func checkSelectorIsObservable(_ selector: Selector) { + MainScheduler.ensureRunningOnMainThread() + + if self.hasWiredImplementation(for: selector) { + print("⚠️ Delegate proxy is already implementing `\(selector)`, a more performant way of registering might exist.") + return + } + + if self.voidDelegateMethodsContain(selector) { + return + } + + // In case `_forwardToDelegate` is `nil`, it is assumed the check is being done prematurely. + if !(self._forwardToDelegate?.responds(to: selector) ?? true) { + print("⚠️ Using delegate proxy dynamic interception method but the target delegate object doesn't respond to the requested selector. " + + "In case pure Swift delegate proxy is being used please use manual observing method by using`PublishSubject`s. " + + " (selector: `\(selector)`, forwardToDelegate: `\(self._forwardToDelegate ?? self)`)") + } + } + + // proxy + + open override func _sentMessage(_ selector: Selector, withArguments arguments: [Any]) { + self._sentMessageForSelector[selector]?.on(.next(arguments)) + } + + open override func _methodInvoked(_ selector: Selector, withArguments arguments: [Any]) { + self._methodInvokedForSelector[selector]?.on(.next(arguments)) + } + + /// Returns reference of normal delegate that receives all forwarded messages + /// through `self`. + /// + /// - returns: Value of reference if set or nil. + open func forwardToDelegate() -> Delegate? { + return castOptionalOrFatalError(self._forwardToDelegate) + } + + /// Sets reference of normal delegate that receives all forwarded messages + /// through `self`. + /// + /// - parameter delegate: Reference of delegate that receives all messages through `self`. + /// - parameter retainDelegate: Should `self` retain `forwardToDelegate`. + open func setForwardToDelegate(_ delegate: Delegate?, retainDelegate: Bool) { + #if DEBUG // 4.0 all configurations + MainScheduler.ensureRunningOnMainThread() + #endif + self._setForwardToDelegate(delegate, retainDelegate: retainDelegate) + + let sentSelectors: [Selector] = self._sentMessageForSelector.values.filter { $0.hasObservers }.map { $0.selector } + let invokedSelectors: [Selector] = self._methodInvokedForSelector.values.filter { $0.hasObservers }.map { $0.selector } + let allUsedSelectors = sentSelectors + invokedSelectors + + for selector in Set(allUsedSelectors) { + self.checkSelectorIsObservable(selector) + } + + self.reset() + } + + private func hasObservers(selector: Selector) -> Bool { + return (self._sentMessageForSelector[selector]?.hasObservers ?? false) + || (self._methodInvokedForSelector[selector]?.hasObservers ?? false) + } + + override open func responds(to aSelector: Selector!) -> Bool { + guard let aSelector = aSelector else { return false } + return super.responds(to: aSelector) + || (self._forwardToDelegate?.responds(to: aSelector) ?? false) + || (self.voidDelegateMethodsContain(aSelector) && self.hasObservers(selector: aSelector)) + } + + fileprivate func reset() { + guard let parentObject = self._parentObject else { return } + + let maybeCurrentDelegate = self._currentDelegateFor(parentObject) + + if maybeCurrentDelegate === self { + self._setCurrentDelegateTo(nil, parentObject) + self._setCurrentDelegateTo(castOrFatalError(self), parentObject) + } + } + + deinit { + for v in self._sentMessageForSelector.values { + v.on(.completed) + } + for v in self._methodInvokedForSelector.values { + v.on(.completed) + } + #if TRACE_RESOURCES + _ = Resources.decrementTotal() + #endif + } + + + } + + private let mainScheduler = MainScheduler() + + private final class MessageDispatcher { + private let dispatcher: PublishSubject<[Any]> + private let result: Observable<[Any]> + + fileprivate let selector: Selector + + init(selector: Selector, delegateProxy _delegateProxy: DelegateProxy) { + weak var weakDelegateProxy = _delegateProxy + + let dispatcher = PublishSubject<[Any]>() + self.dispatcher = dispatcher + self.selector = selector + + self.result = dispatcher + .do(onSubscribed: { weakDelegateProxy?.checkSelectorIsObservable(selector); weakDelegateProxy?.reset() }, onDispose: { weakDelegateProxy?.reset() }) + .share() + .subscribe(on: mainScheduler) + } + + var on: (Event<[Any]>) -> Void { + return self.dispatcher.on + } + + var hasObservers: Bool { + return self.dispatcher.hasObservers + } + + func asObservable() -> Observable<[Any]> { + return self.result + } + } + +#endif diff --git a/Pods/RxCocoa/RxCocoa/Common/DelegateProxyType.swift b/Pods/RxCocoa/RxCocoa/Common/DelegateProxyType.swift new file mode 100644 index 0000000..7ca9c97 --- /dev/null +++ b/Pods/RxCocoa/RxCocoa/Common/DelegateProxyType.swift @@ -0,0 +1,435 @@ +// +// DelegateProxyType.swift +// RxCocoa +// +// Created by Krunoslav Zaher on 6/15/15. +// Copyright © 2015 Krunoslav Zaher. All rights reserved. +// + +#if !os(Linux) + + import Foundation + import RxSwift + +/** +`DelegateProxyType` protocol enables using both normal delegates and Rx observable sequences with +views that can have only one delegate/datasource registered. + +`Proxies` store information about observers, subscriptions and delegates +for specific views. + +Type implementing `DelegateProxyType` should never be initialized directly. + +To fetch initialized instance of type implementing `DelegateProxyType`, `proxy` method +should be used. + +This is more or less how it works. + + + + +-------------------------------------------+ + | | + | UIView subclass (UIScrollView) | + | | + +-----------+-------------------------------+ + | + | Delegate + | + | + +-----------v-------------------------------+ + | | + | Delegate proxy : DelegateProxyType +-----+----> Observable + | , UIScrollViewDelegate | | + +-----------+-------------------------------+ +----> Observable + | | + | +----> Observable + | | + | forwards events | + | to custom delegate | + | v + +-----------v-------------------------------+ + | | + | Custom delegate (UIScrollViewDelegate) | + | | + +-------------------------------------------+ + + +Since RxCocoa needs to automagically create those Proxies and because views that have delegates can be hierarchical + + UITableView : UIScrollView : UIView + +.. and corresponding delegates are also hierarchical + + UITableViewDelegate : UIScrollViewDelegate : NSObject + +... this mechanism can be extended by using the following snippet in `registerKnownImplementations` or in some other + part of your app that executes before using `rx.*` (e.g. appDidFinishLaunching). + + RxScrollViewDelegateProxy.register { RxTableViewDelegateProxy(parentObject: $0) } + +*/ +public protocol DelegateProxyType: AnyObject { + associatedtype ParentObject: AnyObject + associatedtype Delegate + + /// It is require that enumerate call `register` of the extended DelegateProxy subclasses here. + static func registerKnownImplementations() + + /// Unique identifier for delegate + static var identifier: UnsafeRawPointer { get } + + /// Returns designated delegate property for object. + /// + /// Objects can have multiple delegate properties. + /// + /// Each delegate property needs to have it's own type implementing `DelegateProxyType`. + /// + /// It's abstract method. + /// + /// - parameter object: Object that has delegate property. + /// - returns: Value of delegate property. + static func currentDelegate(for object: ParentObject) -> Delegate? + + /// Sets designated delegate property for object. + /// + /// Objects can have multiple delegate properties. + /// + /// Each delegate property needs to have it's own type implementing `DelegateProxyType`. + /// + /// It's abstract method. + /// + /// - parameter delegate: Delegate value. + /// - parameter object: Object that has delegate property. + static func setCurrentDelegate(_ delegate: Delegate?, to object: ParentObject) + + /// Returns reference of normal delegate that receives all forwarded messages + /// through `self`. + /// + /// - returns: Value of reference if set or nil. + func forwardToDelegate() -> Delegate? + + /// Sets reference of normal delegate that receives all forwarded messages + /// through `self`. + /// + /// - parameter forwardToDelegate: Reference of delegate that receives all messages through `self`. + /// - parameter retainDelegate: Should `self` retain `forwardToDelegate`. + func setForwardToDelegate(_ forwardToDelegate: Delegate?, retainDelegate: Bool) +} + +// default implementations +extension DelegateProxyType { + /// Unique identifier for delegate + public static var identifier: UnsafeRawPointer { + let delegateIdentifier = ObjectIdentifier(Delegate.self) + let integerIdentifier = Int(bitPattern: delegateIdentifier) + return UnsafeRawPointer(bitPattern: integerIdentifier)! + } +} + +// workaround of Delegate: class +extension DelegateProxyType { + static func _currentDelegate(for object: ParentObject) -> AnyObject? { + currentDelegate(for: object).map { $0 as AnyObject } + } + + static func _setCurrentDelegate(_ delegate: AnyObject?, to object: ParentObject) { + setCurrentDelegate(castOptionalOrFatalError(delegate), to: object) + } + + func _forwardToDelegate() -> AnyObject? { + self.forwardToDelegate().map { $0 as AnyObject } + } + + func _setForwardToDelegate(_ forwardToDelegate: AnyObject?, retainDelegate: Bool) { + self.setForwardToDelegate(castOptionalOrFatalError(forwardToDelegate), retainDelegate: retainDelegate) + } +} + +extension DelegateProxyType { + + /// Store DelegateProxy subclass to factory. + /// When make 'Rx*DelegateProxy' subclass, call 'Rx*DelegateProxySubclass.register(for:_)' 1 time, or use it in DelegateProxyFactory + /// 'Rx*DelegateProxy' can have one subclass implementation per concrete ParentObject type. + /// Should call it from concrete DelegateProxy type, not generic. + public static func register(make: @escaping (Parent) -> Self) { + self.factory.extend(make: make) + } + + /// Creates new proxy for target object. + /// Should not call this function directory, use 'DelegateProxy.proxy(for:)' + public static func createProxy(for object: AnyObject) -> Self { + castOrFatalError(factory.createProxy(for: object)) + } + + /// Returns existing proxy for object or installs new instance of delegate proxy. + /// + /// - parameter object: Target object on which to install delegate proxy. + /// - returns: Installed instance of delegate proxy. + /// + /// + /// extension Reactive where Base: UISearchBar { + /// + /// public var delegate: DelegateProxy { + /// return RxSearchBarDelegateProxy.proxy(for: base) + /// } + /// + /// public var text: ControlProperty { + /// let source: Observable = self.delegate.observe(#selector(UISearchBarDelegate.searchBar(_:textDidChange:))) + /// ... + /// } + /// } + public static func proxy(for object: ParentObject) -> Self { + MainScheduler.ensureRunningOnMainThread() + + let maybeProxy = self.assignedProxy(for: object) + + let proxy: AnyObject + if let existingProxy = maybeProxy { + proxy = existingProxy + } + else { + proxy = castOrFatalError(self.createProxy(for: object)) + self.assignProxy(proxy, toObject: object) + assert(self.assignedProxy(for: object) === proxy) + } + let currentDelegate = self._currentDelegate(for: object) + let delegateProxy: Self = castOrFatalError(proxy) + + if currentDelegate !== delegateProxy { + delegateProxy._setForwardToDelegate(currentDelegate, retainDelegate: false) + assert(delegateProxy._forwardToDelegate() === currentDelegate) + self._setCurrentDelegate(proxy, to: object) + assert(self._currentDelegate(for: object) === proxy) + assert(delegateProxy._forwardToDelegate() === currentDelegate) + } + + return delegateProxy + } + + /// Sets forward delegate for `DelegateProxyType` associated with a specific object and return disposable that can be used to unset the forward to delegate. + /// Using this method will also make sure that potential original object cached selectors are cleared and will report any accidental forward delegate mutations. + /// + /// - parameter forwardDelegate: Delegate object to set. + /// - parameter retainDelegate: Retain `forwardDelegate` while it's being set. + /// - parameter onProxyForObject: Object that has `delegate` property. + /// - returns: Disposable object that can be used to clear forward delegate. + public static func installForwardDelegate(_ forwardDelegate: Delegate, retainDelegate: Bool, onProxyForObject object: ParentObject) -> Disposable { + weak var weakForwardDelegate: AnyObject? = forwardDelegate as AnyObject + let proxy = self.proxy(for: object) + + assert(proxy._forwardToDelegate() === nil, "This is a feature to warn you that there is already a delegate (or data source) set somewhere previously. The action you are trying to perform will clear that delegate (data source) and that means that some of your features that depend on that delegate (data source) being set will likely stop working.\n" + + "If you are ok with this, try to set delegate (data source) to `nil` in front of this operation.\n" + + " This is the source object value: \(object)\n" + + " This is the original delegate (data source) value: \(proxy.forwardToDelegate()!)\n" + + "Hint: Maybe delegate was already set in xib or storyboard and now it's being overwritten in code.\n") + + proxy.setForwardToDelegate(forwardDelegate, retainDelegate: retainDelegate) + + return Disposables.create { + MainScheduler.ensureRunningOnMainThread() + + let delegate: AnyObject? = weakForwardDelegate + + assert(delegate == nil || proxy._forwardToDelegate() === delegate, "Delegate was changed from time it was first set. Current \(String(describing: proxy.forwardToDelegate())), and it should have been \(proxy)") + + proxy.setForwardToDelegate(nil, retainDelegate: retainDelegate) + } + } +} + + +// private extensions +extension DelegateProxyType { + private static var factory: DelegateProxyFactory { + DelegateProxyFactory.sharedFactory(for: self) + } + + private static func assignedProxy(for object: ParentObject) -> AnyObject? { + let maybeDelegate = objc_getAssociatedObject(object, self.identifier) + return castOptionalOrFatalError(maybeDelegate) + } + + private static func assignProxy(_ proxy: AnyObject, toObject object: ParentObject) { + objc_setAssociatedObject(object, self.identifier, proxy, .OBJC_ASSOCIATION_RETAIN) + } +} + +/// Describes an object that has a delegate. +public protocol HasDelegate: AnyObject { + /// Delegate type + associatedtype Delegate + + /// Delegate + var delegate: Delegate? { get set } +} + +extension DelegateProxyType where ParentObject: HasDelegate, Self.Delegate == ParentObject.Delegate { + public static func currentDelegate(for object: ParentObject) -> Delegate? { + object.delegate + } + + public static func setCurrentDelegate(_ delegate: Delegate?, to object: ParentObject) { + object.delegate = delegate + } +} + +/// Describes an object that has a data source. +public protocol HasDataSource: AnyObject { + /// Data source type + associatedtype DataSource + + /// Data source + var dataSource: DataSource? { get set } +} + +extension DelegateProxyType where ParentObject: HasDataSource, Self.Delegate == ParentObject.DataSource { + public static func currentDelegate(for object: ParentObject) -> Delegate? { + object.dataSource + } + + public static func setCurrentDelegate(_ delegate: Delegate?, to object: ParentObject) { + object.dataSource = delegate + } +} + +/// Describes an object that has a prefetch data source. +@available(iOS 10.0, tvOS 10.0, *) +public protocol HasPrefetchDataSource: AnyObject { + /// Prefetch data source type + associatedtype PrefetchDataSource + + /// Prefetch data source + var prefetchDataSource: PrefetchDataSource? { get set } +} + +@available(iOS 10.0, tvOS 10.0, *) +extension DelegateProxyType where ParentObject: HasPrefetchDataSource, Self.Delegate == ParentObject.PrefetchDataSource { + public static func currentDelegate(for object: ParentObject) -> Delegate? { + object.prefetchDataSource + } + + public static func setCurrentDelegate(_ delegate: Delegate?, to object: ParentObject) { + object.prefetchDataSource = delegate + } +} + + #if os(iOS) || os(tvOS) + import UIKit + + extension ObservableType { + func subscribeProxyDataSource(ofObject object: DelegateProxy.ParentObject, dataSource: DelegateProxy.Delegate, retainDataSource: Bool, binding: @escaping (DelegateProxy, Event) -> Void) + -> Disposable + where DelegateProxy.ParentObject: UIView + , DelegateProxy.Delegate: AnyObject { + let proxy = DelegateProxy.proxy(for: object) + let unregisterDelegate = DelegateProxy.installForwardDelegate(dataSource, retainDelegate: retainDataSource, onProxyForObject: object) + + // Do not perform layoutIfNeeded if the object is still not in the view hierarchy + if object.window != nil { + // this is needed to flush any delayed old state (https://github.com/RxSwiftCommunity/RxDataSources/pull/75) + object.layoutIfNeeded() + } + + let subscription = self.asObservable() + .observe(on:MainScheduler()) + .catch { error in + bindingError(error) + return Observable.empty() + } + // source can never end, otherwise it would release the subscriber, and deallocate the data source + .concat(Observable.never()) + .take(until: object.rx.deallocated) + .subscribe { [weak object] (event: Event) in + + if let object = object { + assert(proxy === DelegateProxy.currentDelegate(for: object), "Proxy changed from the time it was first set.\nOriginal: \(proxy)\nExisting: \(String(describing: DelegateProxy.currentDelegate(for: object)))") + } + + binding(proxy, event) + + switch event { + case .error(let error): + bindingError(error) + unregisterDelegate.dispose() + case .completed: + unregisterDelegate.dispose() + default: + break + } + } + + return Disposables.create { [weak object] in + subscription.dispose() + + if object?.window != nil { + object?.layoutIfNeeded() + } + + unregisterDelegate.dispose() + } + } + } + + #endif + + /** + + To add delegate proxy subclasses call `DelegateProxySubclass.register()` in `registerKnownImplementations` or in some other + part of your app that executes before using `rx.*` (e.g. appDidFinishLaunching). + + class RxScrollViewDelegateProxy: DelegateProxy { + public static func registerKnownImplementations() { + self.register { RxTableViewDelegateProxy(parentObject: $0) } + } + ... + + + */ + private class DelegateProxyFactory { + private static var _sharedFactories: [UnsafeRawPointer: DelegateProxyFactory] = [:] + + fileprivate static func sharedFactory(for proxyType: DelegateProxy.Type) -> DelegateProxyFactory { + MainScheduler.ensureRunningOnMainThread() + let identifier = DelegateProxy.identifier + if let factory = _sharedFactories[identifier] { + return factory + } + let factory = DelegateProxyFactory(for: proxyType) + _sharedFactories[identifier] = factory + DelegateProxy.registerKnownImplementations() + return factory + } + + private var _factories: [ObjectIdentifier: ((AnyObject) -> AnyObject)] + private var _delegateProxyType: Any.Type + private var _identifier: UnsafeRawPointer + + private init(for proxyType: DelegateProxy.Type) { + self._factories = [:] + self._delegateProxyType = proxyType + self._identifier = proxyType.identifier + } + + fileprivate func extend(make: @escaping (ParentObject) -> DelegateProxy) { + MainScheduler.ensureRunningOnMainThread() + precondition(self._identifier == DelegateProxy.identifier, "Delegate proxy has inconsistent identifier") + guard self._factories[ObjectIdentifier(ParentObject.self)] == nil else { + rxFatalError("The factory of \(ParentObject.self) is duplicated. DelegateProxy is not allowed of duplicated base object type.") + } + self._factories[ObjectIdentifier(ParentObject.self)] = { make(castOrFatalError($0)) } + } + + fileprivate func createProxy(for object: AnyObject) -> AnyObject { + MainScheduler.ensureRunningOnMainThread() + var maybeMirror: Mirror? = Mirror(reflecting: object) + while let mirror = maybeMirror { + if let factory = self._factories[ObjectIdentifier(mirror.subjectType)] { + return factory(object) + } + maybeMirror = mirror.superclassMirror + } + rxFatalError("DelegateProxy has no factory of \(object). Implement DelegateProxy subclass for \(object) first.") + } + } + +#endif diff --git a/Pods/RxCocoa/RxCocoa/Common/Infallible+Bind.swift b/Pods/RxCocoa/RxCocoa/Common/Infallible+Bind.swift new file mode 100644 index 0000000..9622c98 --- /dev/null +++ b/Pods/RxCocoa/RxCocoa/Common/Infallible+Bind.swift @@ -0,0 +1,148 @@ +// +// Infallible+Bind.swift +// RxCocoa +// +// Created by Shai Mishali on 27/08/2020. +// Copyright © 2020 Krunoslav Zaher. All rights reserved. +// + +import RxSwift + +extension InfallibleType { + /** + Creates new subscription and sends elements to observer(s). + In this form, it's equivalent to the `subscribe` method, but it better conveys intent, and enables + writing more consistent binding code. + - parameter observers: Observers to receives events. + - returns: Disposable object that can be used to unsubscribe the observers. + */ + public func bind(to observers: Observer...) -> Disposable where Observer.Element == Element { + self.subscribe { event in + observers.forEach { $0.on(event) } + } + } + + /** + Creates new subscription and sends elements to observer(s). + In this form, it's equivalent to the `subscribe` method, but it better conveys intent, and enables + writing more consistent binding code. + - parameter observers: Observers to receives events. + - returns: Disposable object that can be used to unsubscribe the observers. + */ + public func bind(to observers: Observer...) -> Disposable where Observer.Element == Element? { + self.map { $0 as Element? } + .subscribe { event in + observers.forEach { $0.on(event) } + } + } + + /** + Subscribes to observable sequence using custom binder function. + + - parameter binder: Function used to bind elements from `self`. + - returns: Object representing subscription. + */ + public func bind(to binder: (Self) -> Result) -> Result { + binder(self) + } + + /** + Subscribes to observable sequence using custom binder function and final parameter passed to binder function + after `self` is passed. + + public func bind(to binder: Self -> R1 -> R2, curriedArgument: R1) -> R2 { + return binder(self)(curriedArgument) + } + + - parameter binder: Function used to bind elements from `self`. + - parameter curriedArgument: Final argument passed to `binder` to finish binding process. + - returns: Object representing subscription. + */ + public func bind(to binder: (Self) -> (R1) -> R2, curriedArgument: R1) -> R2 { + binder(self)(curriedArgument) + } + + /** + Subscribes an element handler to an observable sequence. + In case error occurs in debug mode, `fatalError` will be raised. + In case error occurs in release mode, `error` will be logged. + + - parameter onNext: Action to invoke for each element in the observable sequence. + - returns: Subscription object used to unsubscribe from the observable sequence. + */ + public func bind(onNext: @escaping (Element) -> Void) -> Disposable { + self.subscribe(onNext: onNext) + } + + /** + Creates new subscription and sends elements to `BehaviorRelay`. + + - parameter relays: Target relay for sequence elements. + - returns: Disposable object that can be used to unsubscribe the observer from the relay. + */ + public func bind(to relays: BehaviorRelay...) -> Disposable { + return self.subscribe(onNext: { e in + relays.forEach { $0.accept(e) } + }) + } + + /** + Creates new subscription and sends elements to `BehaviorRelay`. + + - parameter relays: Target relay for sequence elements. + - returns: Disposable object that can be used to unsubscribe the observer from the relay. + */ + public func bind(to relays: BehaviorRelay...) -> Disposable { + return self.subscribe(onNext: { e in + relays.forEach { $0.accept(e) } + }) + } + + /** + Creates new subscription and sends elements to `PublishRelay`. + + - parameter relays: Target relay for sequence elements. + - returns: Disposable object that can be used to unsubscribe the observer from the relay. + */ + public func bind(to relays: PublishRelay...) -> Disposable { + return self.subscribe(onNext: { e in + relays.forEach { $0.accept(e) } + }) + } + + /** + Creates new subscription and sends elements to `PublishRelay`. + + - parameter relays: Target relay for sequence elements. + - returns: Disposable object that can be used to unsubscribe the observer from the relay. + */ + public func bind(to relays: PublishRelay...) -> Disposable { + return self.subscribe(onNext: { e in + relays.forEach { $0.accept(e) } + }) + } + + /** + Creates new subscription and sends elements to `ReplayRelay`. + + - parameter relays: Target relay for sequence elements. + - returns: Disposable object that can be used to unsubscribe the observer from the relay. + */ + public func bind(to relays: ReplayRelay...) -> Disposable { + return self.subscribe(onNext: { e in + relays.forEach { $0.accept(e) } + }) + } + + /** + Creates new subscription and sends elements to `ReplayRelay`. + + - parameter relays: Target relay for sequence elements. + - returns: Disposable object that can be used to unsubscribe the observer from the relay. + */ + public func bind(to relays: ReplayRelay...) -> Disposable { + return self.subscribe(onNext: { e in + relays.forEach { $0.accept(e) } + }) + } +} diff --git a/Pods/RxCocoa/RxCocoa/Common/Observable+Bind.swift b/Pods/RxCocoa/RxCocoa/Common/Observable+Bind.swift new file mode 100644 index 0000000..500154a --- /dev/null +++ b/Pods/RxCocoa/RxCocoa/Common/Observable+Bind.swift @@ -0,0 +1,103 @@ +// +// Observable+Bind.swift +// RxCocoa +// +// Created by Krunoslav Zaher on 8/29/15. +// Copyright © 2015 Krunoslav Zaher. All rights reserved. +// + +import RxSwift + +extension ObservableType { + /** + Creates new subscription and sends elements to observer(s). + In this form, it's equivalent to the `subscribe` method, but it better conveys intent, and enables + writing more consistent binding code. + - parameter observers: Observers to receives events. + - returns: Disposable object that can be used to unsubscribe the observers. + */ + public func bind(to observers: Observer...) -> Disposable where Observer.Element == Element { + self.subscribe { event in + observers.forEach { $0.on(event) } + } + } + + /** + Creates new subscription and sends elements to observer(s). + In this form, it's equivalent to the `subscribe` method, but it better conveys intent, and enables + writing more consistent binding code. + - parameter observers: Observers to receives events. + - returns: Disposable object that can be used to unsubscribe the observers. + */ + public func bind(to observers: Observer...) -> Disposable where Observer.Element == Element? { + self.map { $0 as Element? } + .subscribe { event in + observers.forEach { $0.on(event) } + } + } + + /** + Subscribes to observable sequence using custom binder function. + + - parameter binder: Function used to bind elements from `self`. + - returns: Object representing subscription. + */ + public func bind(to binder: (Self) -> Result) -> Result { + binder(self) + } + + /** + Subscribes to observable sequence using custom binder function and final parameter passed to binder function + after `self` is passed. + + public func bind(to binder: Self -> R1 -> R2, curriedArgument: R1) -> R2 { + return binder(self)(curriedArgument) + } + + - parameter binder: Function used to bind elements from `self`. + - parameter curriedArgument: Final argument passed to `binder` to finish binding process. + - returns: Object representing subscription. + */ + public func bind(to binder: (Self) -> (R1) -> R2, curriedArgument: R1) -> R2 { + binder(self)(curriedArgument) + } + + /** + Subscribes an element handler to an observable sequence. + In case error occurs in debug mode, `fatalError` will be raised. + In case error occurs in release mode, `error` will be logged. + + - Note: If `object` can't be retained, none of the other closures will be invoked. + + - parameter object: The object to provide an unretained reference on. + - parameter onNext: Action to invoke for each element in the observable sequence. + - returns: Subscription object used to unsubscribe from the observable sequence. + */ + public func bind( + with object: Object, + onNext: @escaping (Object, Element) -> Void + ) -> Disposable { + self.subscribe(onNext: { [weak object] in + guard let object = object else { return } + onNext(object, $0) + }, + onError: { error in + rxFatalErrorInDebug("Binding error: \(error)") + }) + } + + /** + Subscribes an element handler to an observable sequence. + In case error occurs in debug mode, `fatalError` will be raised. + In case error occurs in release mode, `error` will be logged. + + - parameter onNext: Action to invoke for each element in the observable sequence. + - returns: Subscription object used to unsubscribe from the observable sequence. + */ + public func bind(onNext: @escaping (Element) -> Void) -> Disposable { + self.subscribe(onNext: onNext, + onError: { error in + rxFatalErrorInDebug("Binding error: \(error)") + }) + } +} diff --git a/Pods/RxCocoa/RxCocoa/Common/RxCocoaObjCRuntimeError+Extensions.swift b/Pods/RxCocoa/RxCocoa/Common/RxCocoaObjCRuntimeError+Extensions.swift new file mode 100644 index 0000000..4abf880 --- /dev/null +++ b/Pods/RxCocoa/RxCocoa/Common/RxCocoaObjCRuntimeError+Extensions.swift @@ -0,0 +1,161 @@ +// +// RxCocoaObjCRuntimeError+Extensions.swift +// RxCocoa +// +// Created by Krunoslav Zaher on 10/9/16. +// Copyright © 2016 Krunoslav Zaher. All rights reserved. +// + +#if SWIFT_PACKAGE && !DISABLE_SWIZZLING && !os(Linux) + import RxCocoaRuntime +#endif + +#if !DISABLE_SWIZZLING && !os(Linux) + /// RxCocoa ObjC runtime interception mechanism. + public enum RxCocoaInterceptionMechanism { + /// Unknown message interception mechanism. + case unknown + /// Key value observing interception mechanism. + case kvo + } + + /// RxCocoa ObjC runtime modification errors. + public enum RxCocoaObjCRuntimeError + : Swift.Error + , CustomDebugStringConvertible { + /// Unknown error has occurred. + case unknown(target: AnyObject) + + /** + If the object is reporting a different class then it's real class, that means that there is probably + already some interception mechanism in place or something weird is happening. + + The most common case when this would happen is when using a combination of KVO (`observe`) and `sentMessage`. + + This error is easily resolved by just using `sentMessage` observing before `observe`. + + The reason why the other way around could create issues is because KVO will unregister it's interceptor + class and restore original class. Unfortunately that will happen no matter was there another interceptor + subclass registered in hierarchy or not. + + Failure scenario: + * KVO sets class to be `__KVO__OriginalClass` (subclass of `OriginalClass`) + * `sentMessage` sets object class to be `_RX_namespace___KVO__OriginalClass` (subclass of `__KVO__OriginalClass`) + * then unobserving with KVO will restore class to be `OriginalClass` -> failure point (possibly a bug in KVO) + + The reason why changing order of observing works is because any interception method on unregistration + should return object's original real class (if that doesn't happen then it's really easy to argue that's a bug + in that interception mechanism). + + This library won't remove registered interceptor even if there aren't any observers left because + it's highly unlikely it would have any benefit in real world use cases, and it's even more + dangerous. + */ + case objectMessagesAlreadyBeingIntercepted(target: AnyObject, interceptionMechanism: RxCocoaInterceptionMechanism) + + /// Trying to observe messages for selector that isn't implemented. + case selectorNotImplemented(target: AnyObject) + + /// Core Foundation classes are usually toll free bridged. Those classes crash the program in case + /// `object_setClass` is performed on them. + /// + /// There is a possibility to just swizzle methods on original object, but since those won't be usual use + /// cases for this library, then an error will just be reported for now. + case cantInterceptCoreFoundationTollFreeBridgedObjects(target: AnyObject) + + /// Two libraries have simultaneously tried to modify ObjC runtime and that was detected. This can only + /// happen in scenarios where multiple interception libraries are used. + /// + /// To synchronize other libraries intercepting messages for an object, use `synchronized` on target object and + /// it's meta-class. + case threadingCollisionWithOtherInterceptionMechanism(target: AnyObject) + + /// For some reason saving original method implementation under RX namespace failed. + case savingOriginalForwardingMethodFailed(target: AnyObject) + + /// Intercepting a sent message by replacing a method implementation with `_objc_msgForward` failed for some reason. + case replacingMethodWithForwardingImplementation(target: AnyObject) + + /// Attempt to intercept one of the performance sensitive methods: + /// * class + /// * respondsToSelector: + /// * methodSignatureForSelector: + /// * forwardingTargetForSelector: + case observingPerformanceSensitiveMessages(target: AnyObject) + + /// Message implementation has unsupported return type (for example large struct). The reason why this is a error + /// is because in some cases intercepting sent messages requires replacing implementation with `_objc_msgForward_stret` + /// instead of `_objc_msgForward`. + /// + /// The unsupported cases should be fairly uncommon. + case observingMessagesWithUnsupportedReturnType(target: AnyObject) + } + + extension RxCocoaObjCRuntimeError { + /// A textual representation of `self`, suitable for debugging. + public var debugDescription: String { + switch self { + case let .unknown(target): + return "Unknown error occurred.\nTarget: `\(target)`" + case let .objectMessagesAlreadyBeingIntercepted(target, interceptionMechanism): + let interceptionMechanismDescription = interceptionMechanism == .kvo ? "KVO" : "other interception mechanism" + return "Collision between RxCocoa interception mechanism and \(interceptionMechanismDescription)." + + " To resolve this conflict please use this interception mechanism first.\nTarget: \(target)" + case let .selectorNotImplemented(target): + return "Trying to observe messages for selector that isn't implemented.\nTarget: \(target)" + case let .cantInterceptCoreFoundationTollFreeBridgedObjects(target): + return "Interception of messages sent to Core Foundation isn't supported.\nTarget: \(target)" + case let .threadingCollisionWithOtherInterceptionMechanism(target): + return "Detected a conflict while modifying ObjC runtime.\nTarget: \(target)" + case let .savingOriginalForwardingMethodFailed(target): + return "Saving original method implementation failed.\nTarget: \(target)" + case let .replacingMethodWithForwardingImplementation(target): + return "Intercepting a sent message by replacing a method implementation with `_objc_msgForward` failed for some reason.\nTarget: \(target)" + case let .observingPerformanceSensitiveMessages(target): + return "Attempt to intercept one of the performance sensitive methods. \nTarget: \(target)" + case let .observingMessagesWithUnsupportedReturnType(target): + return "Attempt to intercept a method with unsupported return type. \nTarget: \(target)" + } + } + } + + // MARK: Conversions `NSError` > `RxCocoaObjCRuntimeError` + + extension Error { + func rxCocoaErrorForTarget(_ target: AnyObject) -> RxCocoaObjCRuntimeError { + let error = self as NSError + + if error.domain == RXObjCRuntimeErrorDomain { + let errorCode = RXObjCRuntimeError(rawValue: error.code) ?? .unknown + + switch errorCode { + case .unknown: + return .unknown(target: target) + case .objectMessagesAlreadyBeingIntercepted: + let isKVO = (error.userInfo[RXObjCRuntimeErrorIsKVOKey] as? NSNumber)?.boolValue ?? false + return .objectMessagesAlreadyBeingIntercepted(target: target, interceptionMechanism: isKVO ? .kvo : .unknown) + case .selectorNotImplemented: + return .selectorNotImplemented(target: target) + case .cantInterceptCoreFoundationTollFreeBridgedObjects: + return .cantInterceptCoreFoundationTollFreeBridgedObjects(target: target) + case .threadingCollisionWithOtherInterceptionMechanism: + return .threadingCollisionWithOtherInterceptionMechanism(target: target) + case .savingOriginalForwardingMethodFailed: + return .savingOriginalForwardingMethodFailed(target: target) + case .replacingMethodWithForwardingImplementation: + return .replacingMethodWithForwardingImplementation(target: target) + case .observingPerformanceSensitiveMessages: + return .observingPerformanceSensitiveMessages(target: target) + case .observingMessagesWithUnsupportedReturnType: + return .observingMessagesWithUnsupportedReturnType(target: target) + @unknown default: + fatalError("Unhandled Objective C Runtime Error") + } + } + + return RxCocoaObjCRuntimeError.unknown(target: target) + } + } + +#endif + diff --git a/Pods/RxCocoa/RxCocoa/Common/RxTarget.swift b/Pods/RxCocoa/RxCocoa/Common/RxTarget.swift new file mode 100644 index 0000000..5a2c464 --- /dev/null +++ b/Pods/RxCocoa/RxCocoa/Common/RxTarget.swift @@ -0,0 +1,43 @@ +// +// RxTarget.swift +// RxCocoa +// +// Created by Krunoslav Zaher on 7/12/15. +// Copyright © 2015 Krunoslav Zaher. All rights reserved. +// + +import Foundation + +import RxSwift + +class RxTarget : NSObject + , Disposable { + + private var retainSelf: RxTarget? + + override init() { + super.init() + self.retainSelf = self + +#if TRACE_RESOURCES + _ = Resources.incrementTotal() +#endif + +#if DEBUG + MainScheduler.ensureRunningOnMainThread() +#endif + } + + func dispose() { +#if DEBUG + MainScheduler.ensureRunningOnMainThread() +#endif + self.retainSelf = nil + } + +#if TRACE_RESOURCES + deinit { + _ = Resources.decrementTotal() + } +#endif +} diff --git a/Pods/RxCocoa/RxCocoa/Common/SectionedViewDataSourceType.swift b/Pods/RxCocoa/RxCocoa/Common/SectionedViewDataSourceType.swift new file mode 100644 index 0000000..5c3cf3c --- /dev/null +++ b/Pods/RxCocoa/RxCocoa/Common/SectionedViewDataSourceType.swift @@ -0,0 +1,20 @@ +// +// SectionedViewDataSourceType.swift +// RxCocoa +// +// Created by Krunoslav Zaher on 1/10/16. +// Copyright © 2016 Krunoslav Zaher. All rights reserved. +// + +import Foundation + +/// Data source with access to underlying sectioned model. +public protocol SectionedViewDataSourceType { + /// Returns model at index path. + /// + /// In case data source doesn't contain any sections when this method is being called, `RxCocoaError.ItemsNotYetBound(object: self)` is thrown. + + /// - parameter indexPath: Model index path + /// - returns: Model at index path. + func model(at indexPath: IndexPath) throws -> Any +} diff --git a/Pods/RxCocoa/RxCocoa/Common/TextInput.swift b/Pods/RxCocoa/RxCocoa/Common/TextInput.swift new file mode 100644 index 0000000..2268882 --- /dev/null +++ b/Pods/RxCocoa/RxCocoa/Common/TextInput.swift @@ -0,0 +1,78 @@ +// +// TextInput.swift +// RxCocoa +// +// Created by Krunoslav Zaher on 5/12/16. +// Copyright © 2016 Krunoslav Zaher. All rights reserved. +// + +import RxSwift + +#if os(iOS) || os(tvOS) + import UIKit + + /// Represents text input with reactive extensions. + public struct TextInput { + /// Base text input to extend. + public let base: Base + + /// Reactive wrapper for `text` property. + public let text: ControlProperty + + /// Initializes new text input. + /// + /// - parameter base: Base object. + /// - parameter text: Textual control property. + public init(base: Base, text: ControlProperty) { + self.base = base + self.text = text + } + } + + extension Reactive where Base: UITextField { + /// Reactive text input. + public var textInput: TextInput { + return TextInput(base: base, text: self.text) + } + } + + extension Reactive where Base: UITextView { + /// Reactive text input. + public var textInput: TextInput { + return TextInput(base: base, text: self.text) + } + } + +#endif + +#if os(macOS) + import Cocoa + + /// Represents text input with reactive extensions. + public struct TextInput { + /// Base text input to extend. + public let base: Base + + /// Reactive wrapper for `text` property. + public let text: ControlProperty + + /// Initializes new text input. + /// + /// - parameter base: Base object. + /// - parameter text: Textual control property. + public init(base: Base, text: ControlProperty) { + self.base = base + self.text = text + } + } + + extension Reactive where Base: NSTextField, Base: NSTextInputClient { + /// Reactive text input. + public var textInput: TextInput { + return TextInput(base: self.base, text: self.text) + } + } + +#endif + + diff --git a/Pods/RxCocoa/RxCocoa/Foundation/KVORepresentable+CoreGraphics.swift b/Pods/RxCocoa/RxCocoa/Foundation/KVORepresentable+CoreGraphics.swift new file mode 100644 index 0000000..30026bf --- /dev/null +++ b/Pods/RxCocoa/RxCocoa/Foundation/KVORepresentable+CoreGraphics.swift @@ -0,0 +1,68 @@ +// +// KVORepresentable+CoreGraphics.swift +// RxCocoa +// +// Created by Krunoslav Zaher on 11/14/15. +// Copyright © 2015 Krunoslav Zaher. All rights reserved. +// + +#if !os(Linux) + +import RxSwift +import CoreGraphics + +import Foundation + +#if arch(x86_64) || arch(arm64) + let CGRectType = "{CGRect={CGPoint=dd}{CGSize=dd}}" + let CGSizeType = "{CGSize=dd}" + let CGPointType = "{CGPoint=dd}" +#elseif arch(i386) || arch(arm) || os(watchOS) + let CGRectType = "{CGRect={CGPoint=ff}{CGSize=ff}}" + let CGSizeType = "{CGSize=ff}" + let CGPointType = "{CGPoint=ff}" +#endif + +extension CGRect : KVORepresentable { + public typealias KVOType = NSValue + + /// Constructs self from `NSValue`. + public init?(KVOValue: KVOType) { + if strcmp(KVOValue.objCType, CGRectType) != 0 { + return nil + } + var typedValue = CGRect(x: 0, y: 0, width: 0, height: 0) + KVOValue.getValue(&typedValue) + self = typedValue + } +} + +extension CGPoint : KVORepresentable { + public typealias KVOType = NSValue + + /// Constructs self from `NSValue`. + public init?(KVOValue: KVOType) { + if strcmp(KVOValue.objCType, CGPointType) != 0 { + return nil + } + var typedValue = CGPoint(x: 0, y: 0) + KVOValue.getValue(&typedValue) + self = typedValue + } +} + +extension CGSize : KVORepresentable { + public typealias KVOType = NSValue + + /// Constructs self from `NSValue`. + public init?(KVOValue: KVOType) { + if strcmp(KVOValue.objCType, CGSizeType) != 0 { + return nil + } + var typedValue = CGSize(width: 0, height: 0) + KVOValue.getValue(&typedValue) + self = typedValue + } +} + +#endif diff --git a/Pods/RxCocoa/RxCocoa/Foundation/KVORepresentable+Swift.swift b/Pods/RxCocoa/RxCocoa/Foundation/KVORepresentable+Swift.swift new file mode 100644 index 0000000..00d53dd --- /dev/null +++ b/Pods/RxCocoa/RxCocoa/Foundation/KVORepresentable+Swift.swift @@ -0,0 +1,88 @@ +// +// KVORepresentable+Swift.swift +// RxCocoa +// +// Created by Krunoslav Zaher on 11/14/15. +// Copyright © 2015 Krunoslav Zaher. All rights reserved. +// + +import Foundation + +extension Int : KVORepresentable { + public typealias KVOType = NSNumber + + /// Constructs `Self` using KVO value. + public init?(KVOValue: KVOType) { + self.init(KVOValue.int32Value) + } +} + +extension Int32 : KVORepresentable { + public typealias KVOType = NSNumber + + /// Constructs `Self` using KVO value. + public init?(KVOValue: KVOType) { + self.init(KVOValue.int32Value) + } +} + +extension Int64 : KVORepresentable { + public typealias KVOType = NSNumber + + /// Constructs `Self` using KVO value. + public init?(KVOValue: KVOType) { + self.init(KVOValue.int64Value) + } +} + +extension UInt : KVORepresentable { + public typealias KVOType = NSNumber + + /// Constructs `Self` using KVO value. + public init?(KVOValue: KVOType) { + self.init(KVOValue.uintValue) + } +} + +extension UInt32 : KVORepresentable { + public typealias KVOType = NSNumber + + /// Constructs `Self` using KVO value. + public init?(KVOValue: KVOType) { + self.init(KVOValue.uint32Value) + } +} + +extension UInt64 : KVORepresentable { + public typealias KVOType = NSNumber + + /// Constructs `Self` using KVO value. + public init?(KVOValue: KVOType) { + self.init(KVOValue.uint64Value) + } +} + +extension Bool : KVORepresentable { + public typealias KVOType = NSNumber + + /// Constructs `Self` using KVO value. + public init?(KVOValue: KVOType) { + self.init(KVOValue.boolValue) + } +} + + +extension RawRepresentable where RawValue: KVORepresentable { + /// Constructs `Self` using optional KVO value. + init?(KVOValue: RawValue.KVOType?) { + guard let KVOValue = KVOValue else { + return nil + } + + guard let rawValue = RawValue(KVOValue: KVOValue) else { + return nil + } + + self.init(rawValue: rawValue) + } +} diff --git a/Pods/RxCocoa/RxCocoa/Foundation/KVORepresentable.swift b/Pods/RxCocoa/RxCocoa/Foundation/KVORepresentable.swift new file mode 100644 index 0000000..be12b33 --- /dev/null +++ b/Pods/RxCocoa/RxCocoa/Foundation/KVORepresentable.swift @@ -0,0 +1,28 @@ +// +// KVORepresentable.swift +// RxCocoa +// +// Created by Krunoslav Zaher on 11/14/15. +// Copyright © 2015 Krunoslav Zaher. All rights reserved. +// + +/// Type that is KVO representable (KVO mechanism can be used to observe it). +public protocol KVORepresentable { + /// Associated KVO type. + associatedtype KVOType + + /// Constructs `Self` using KVO value. + init?(KVOValue: KVOType) +} + +extension KVORepresentable { + /// Initializes `KVORepresentable` with optional value. + init?(KVOValue: KVOType?) { + guard let KVOValue = KVOValue else { + return nil + } + + self.init(KVOValue: KVOValue) + } +} + diff --git a/Pods/RxCocoa/RxCocoa/Foundation/NSObject+Rx+KVORepresentable.swift b/Pods/RxCocoa/RxCocoa/Foundation/NSObject+Rx+KVORepresentable.swift new file mode 100644 index 0000000..1be5a21 --- /dev/null +++ b/Pods/RxCocoa/RxCocoa/Foundation/NSObject+Rx+KVORepresentable.swift @@ -0,0 +1,60 @@ +// +// NSObject+Rx+KVORepresentable.swift +// RxCocoa +// +// Created by Krunoslav Zaher on 11/14/15. +// Copyright © 2015 Krunoslav Zaher. All rights reserved. +// + +#if !os(Linux) + +import Foundation +import RxSwift + +/// Key value observing options +public struct KeyValueObservingOptions: OptionSet { + /// Raw value + public let rawValue: UInt + + public init(rawValue: UInt) { + self.rawValue = rawValue + } + + /// Whether a sequence element should be sent to the observer immediately, before the subscribe method even returns. + public static let initial = KeyValueObservingOptions(rawValue: 1 << 0) + /// Whether to send updated values. + public static let new = KeyValueObservingOptions(rawValue: 1 << 1) +} + +extension Reactive where Base: NSObject { + + /** + Specialization of generic `observe` method. + + This is a special overload because to observe values of some type (for example `Int`), first values of KVO type + need to be observed (`NSNumber`), and then converted to result type. + + For more information take a look at `observe` method. + */ + public func observe(_ type: Element.Type, _ keyPath: String, options: KeyValueObservingOptions = [.new, .initial], retainSelf: Bool = true) -> Observable { + return self.observe(Element.KVOType.self, keyPath, options: options, retainSelf: retainSelf) + .map(Element.init) + } +} + +#if !DISABLE_SWIZZLING && !os(Linux) + // KVO + extension Reactive where Base: NSObject { + /** + Specialization of generic `observeWeakly` method. + + For more information take a look at `observeWeakly` method. + */ + public func observeWeakly(_ type: Element.Type, _ keyPath: String, options: KeyValueObservingOptions = [.new, .initial]) -> Observable { + return self.observeWeakly(Element.KVOType.self, keyPath, options: options) + .map(Element.init) + } + } +#endif + +#endif diff --git a/Pods/RxCocoa/RxCocoa/Foundation/NSObject+Rx+RawRepresentable.swift b/Pods/RxCocoa/RxCocoa/Foundation/NSObject+Rx+RawRepresentable.swift new file mode 100644 index 0000000..6e47cb2 --- /dev/null +++ b/Pods/RxCocoa/RxCocoa/Foundation/NSObject+Rx+RawRepresentable.swift @@ -0,0 +1,52 @@ +// +// NSObject+Rx+RawRepresentable.swift +// RxCocoa +// +// Created by Krunoslav Zaher on 11/9/15. +// Copyright © 2015 Krunoslav Zaher. All rights reserved. +// + +#if !os(Linux) + +import RxSwift + +import Foundation + +extension Reactive where Base: NSObject { + /** + Specialization of generic `observe` method. + + This specialization first observes `KVORepresentable` value and then converts it to `RawRepresentable` value. + + It is useful for observing bridged ObjC enum values. + + For more information take a look at `observe` method. + */ + public func observe(_ type: Element.Type, _ keyPath: String, options: KeyValueObservingOptions = [.new, .initial], retainSelf: Bool = true) -> Observable where Element.RawValue: KVORepresentable { + return self.observe(Element.RawValue.KVOType.self, keyPath, options: options, retainSelf: retainSelf) + .map(Element.init) + } +} + +#if !DISABLE_SWIZZLING + + // observeWeakly + RawRepresentable + extension Reactive where Base: NSObject { + + /** + Specialization of generic `observeWeakly` method. + + This specialization first observes `KVORepresentable` value and then converts it to `RawRepresentable` value. + + It is useful for observing bridged ObjC enum values. + + For more information take a look at `observeWeakly` method. + */ + public func observeWeakly(_ type: Element.Type, _ keyPath: String, options: KeyValueObservingOptions = [.new, .initial]) -> Observable where Element.RawValue: KVORepresentable { + return self.observeWeakly(Element.RawValue.KVOType.self, keyPath, options: options) + .map(Element.init) + } + } +#endif + +#endif diff --git a/Pods/RxCocoa/RxCocoa/Foundation/NSObject+Rx.swift b/Pods/RxCocoa/RxCocoa/Foundation/NSObject+Rx.swift new file mode 100644 index 0000000..2f15724 --- /dev/null +++ b/Pods/RxCocoa/RxCocoa/Foundation/NSObject+Rx.swift @@ -0,0 +1,569 @@ +// +// NSObject+Rx.swift +// RxCocoa +// +// Created by Krunoslav Zaher on 2/21/15. +// Copyright © 2015 Krunoslav Zaher. All rights reserved. +// + +#if !os(Linux) + +import Foundation +import RxSwift +#if SWIFT_PACKAGE && !DISABLE_SWIZZLING && !os(Linux) + import RxCocoaRuntime +#endif + +#if !DISABLE_SWIZZLING && !os(Linux) +private var deallocatingSubjectTriggerContext: UInt8 = 0 +private var deallocatingSubjectContext: UInt8 = 0 +#endif +private var deallocatedSubjectTriggerContext: UInt8 = 0 +private var deallocatedSubjectContext: UInt8 = 0 + +#if !os(Linux) + +/** +KVO is a tricky mechanism. + +When observing child in a ownership hierarchy, usually retaining observing target is wanted behavior. +When observing parent in a ownership hierarchy, usually retaining target isn't wanter behavior. + +KVO with weak references is especially tricky. For it to work, some kind of swizzling is required. +That can be done by + * replacing object class dynamically (like KVO does) + * by swizzling `dealloc` method on all instances for a class. + * some third method ... + +Both approaches can fail in certain scenarios: + * problems arise when swizzlers return original object class (like KVO does when nobody is observing) + * Problems can arise because replacing dealloc method isn't atomic operation (get implementation, + set implementation). + +Second approach is chosen. It can fail in case there are multiple libraries dynamically trying +to replace dealloc method. In case that isn't the case, it should be ok. +*/ +extension Reactive where Base: NSObject { + + + /** + Observes values on `keyPath` starting from `self` with `options` and retains `self` if `retainSelf` is set. + + `observe` is just a simple and performant wrapper around KVO mechanism. + + * it can be used to observe paths starting from `self` or from ancestors in ownership graph (`retainSelf = false`) + * it can be used to observe paths starting from descendants in ownership graph (`retainSelf = true`) + * the paths have to consist only of `strong` properties, otherwise you are risking crashing the system by not unregistering KVO observer before dealloc. + + If support for weak properties is needed or observing arbitrary or unknown relationships in the + ownership tree, `observeWeakly` is the preferred option. + - parameter type: Optional type hint of the observed sequence elements. + - parameter keyPath: Key path of property names to observe. + - parameter options: KVO mechanism notification options. + - parameter retainSelf: Retains self during observation if set `true`. + - returns: Observable sequence of objects on `keyPath`. + */ + public func observe(_ type: Element.Type, + _ keyPath: String, + options: KeyValueObservingOptions = [.new, .initial], + retainSelf: Bool = true) -> Observable { + KVOObservable(object: self.base, keyPath: keyPath, options: options, retainTarget: retainSelf).asObservable() + } + + /** + Observes values at the provided key path using the provided options. + + - parameter keyPath: A key path between the object and one of its properties. + - parameter options: Key-value observation options, defaults to `.new` and `.initial`. + + - note: When the object is deallocated, a completion event is emitted. + + - returns: An observable emitting value changes at the provided key path. + */ + public func observe(_ keyPath: KeyPath, + options: NSKeyValueObservingOptions = [.new, .initial]) -> Observable { + Observable.create { [weak base] observer in + let observation = base?.observe(keyPath, options: options) { obj, _ in + observer.on(.next(obj[keyPath: keyPath])) + } + + return Disposables.create { observation?.invalidate() } + } + .take(until: base.rx.deallocated) + } +} + +#endif + +#if !DISABLE_SWIZZLING && !os(Linux) +// KVO +extension Reactive where Base: NSObject { + /** + Observes values on `keyPath` starting from `self` with `options` and doesn't retain `self`. + + It can be used in all cases where `observe` can be used and additionally + + * because it won't retain observed target, it can be used to observe arbitrary object graph whose ownership relation is unknown + * it can be used to observe `weak` properties + + **Since it needs to intercept object deallocation process it needs to perform swizzling of `dealloc` method on observed object.** + - parameter type: Optional type hint of the observed sequence elements. + - parameter keyPath: Key path of property names to observe. + - parameter options: KVO mechanism notification options. + - returns: Observable sequence of objects on `keyPath`. + */ + public func observeWeakly(_ type: Element.Type, _ keyPath: String, options: KeyValueObservingOptions = [.new, .initial]) -> Observable { + return observeWeaklyKeyPathFor(self.base, keyPath: keyPath, options: options) + .map { n in + return n as? Element + } + } +} +#endif + +// Dealloc +extension Reactive where Base: AnyObject { + + /** + Observable sequence of object deallocated events. + + After object is deallocated one `()` element will be produced and sequence will immediately complete. + + - returns: Observable sequence of object deallocated events. + */ + public var deallocated: Observable { + return self.synchronized { + if let deallocObservable = objc_getAssociatedObject(self.base, &deallocatedSubjectContext) as? DeallocObservable { + return deallocObservable.subject + } + + let deallocObservable = DeallocObservable() + + objc_setAssociatedObject(self.base, &deallocatedSubjectContext, deallocObservable, .OBJC_ASSOCIATION_RETAIN_NONATOMIC) + return deallocObservable.subject + } + } + +#if !DISABLE_SWIZZLING && !os(Linux) + + /** + Observable sequence of message arguments that completes when object is deallocated. + + Each element is produced before message is invoked on target object. `methodInvoked` + exists in case observing of invoked messages is needed. + + In case an error occurs sequence will fail with `RxCocoaObjCRuntimeError`. + + In case some argument is `nil`, instance of `NSNull()` will be sent. + + - returns: Observable sequence of arguments passed to `selector` method. + */ + public func sentMessage(_ selector: Selector) -> Observable<[Any]> { + return self.synchronized { + // in case of dealloc selector replay subject behavior needs to be used + if selector == deallocSelector { + return self.deallocating.map { _ in [] } + } + + do { + let proxy: MessageSentProxy = try self.registerMessageInterceptor(selector) + return proxy.messageSent.asObservable() + } + catch let e { + return Observable.error(e) + } + } + } + + /** + Observable sequence of message arguments that completes when object is deallocated. + + Each element is produced after message is invoked on target object. `sentMessage` + exists in case interception of sent messages before they were invoked is needed. + + In case an error occurs sequence will fail with `RxCocoaObjCRuntimeError`. + + In case some argument is `nil`, instance of `NSNull()` will be sent. + + - returns: Observable sequence of arguments passed to `selector` method. + */ + public func methodInvoked(_ selector: Selector) -> Observable<[Any]> { + return self.synchronized { + // in case of dealloc selector replay subject behavior needs to be used + if selector == deallocSelector { + return self.deallocated.map { _ in [] } + } + + + do { + let proxy: MessageSentProxy = try self.registerMessageInterceptor(selector) + return proxy.methodInvoked.asObservable() + } + catch let e { + return Observable.error(e) + } + } + } + + /** + Observable sequence of object deallocating events. + + When `dealloc` message is sent to `self` one `()` element will be produced and after object is deallocated sequence + will immediately complete. + + In case an error occurs sequence will fail with `RxCocoaObjCRuntimeError`. + + - returns: Observable sequence of object deallocating events. + */ + public var deallocating: Observable<()> { + return self.synchronized { + do { + let proxy: DeallocatingProxy = try self.registerMessageInterceptor(deallocSelector) + return proxy.messageSent.asObservable() + } + catch let e { + return Observable.error(e) + } + } + } + + private func registerMessageInterceptor(_ selector: Selector) throws -> T { + let rxSelector = RX_selector(selector) + let selectorReference = RX_reference_from_selector(rxSelector) + + let subject: T + if let existingSubject = objc_getAssociatedObject(self.base, selectorReference) as? T { + subject = existingSubject + } + else { + subject = T() + objc_setAssociatedObject( + self.base, + selectorReference, + subject, + .OBJC_ASSOCIATION_RETAIN_NONATOMIC + ) + } + + if subject.isActive { + return subject + } + + var error: NSError? + let targetImplementation = RX_ensure_observing(self.base, selector, &error) + if targetImplementation == nil { + throw error?.rxCocoaErrorForTarget(self.base) ?? RxCocoaError.unknown + } + + subject.targetImplementation = targetImplementation! + + return subject + } +#endif +} + +// MARK: Message interceptors + +#if !DISABLE_SWIZZLING && !os(Linux) + + private protocol MessageInterceptorSubject: AnyObject { + init() + + var isActive: Bool { + get + } + + var targetImplementation: IMP { get set } + } + + private final class DeallocatingProxy + : MessageInterceptorSubject + , RXDeallocatingObserver { + typealias Element = () + + let messageSent = ReplaySubject<()>.create(bufferSize: 1) + + @objc var targetImplementation: IMP = RX_default_target_implementation() + + var isActive: Bool { + return self.targetImplementation != RX_default_target_implementation() + } + + init() { + } + + @objc func deallocating() { + self.messageSent.on(.next(())) + } + + deinit { + self.messageSent.on(.completed) + } + } + + private final class MessageSentProxy + : MessageInterceptorSubject + , RXMessageSentObserver { + typealias Element = [AnyObject] + + let messageSent = PublishSubject<[Any]>() + let methodInvoked = PublishSubject<[Any]>() + + @objc var targetImplementation: IMP = RX_default_target_implementation() + + var isActive: Bool { + return self.targetImplementation != RX_default_target_implementation() + } + + init() { + } + + @objc func messageSent(withArguments arguments: [Any]) { + self.messageSent.on(.next(arguments)) + } + + @objc func methodInvoked(withArguments arguments: [Any]) { + self.methodInvoked.on(.next(arguments)) + } + + deinit { + self.messageSent.on(.completed) + self.methodInvoked.on(.completed) + } + } + +#endif + + +private final class DeallocObservable { + let subject = ReplaySubject.create(bufferSize:1) + + init() { + } + + deinit { + self.subject.on(.next(())) + self.subject.on(.completed) + } +} + +// MARK: KVO + +#if !os(Linux) + +private protocol KVOObservableProtocol { + var target: AnyObject { get } + var keyPath: String { get } + var retainTarget: Bool { get } + var options: KeyValueObservingOptions { get } +} + +private final class KVOObserver + : _RXKVOObserver + , Disposable { + typealias Callback = (Any?) -> Void + + var retainSelf: KVOObserver? + + init(parent: KVOObservableProtocol, callback: @escaping Callback) { + #if TRACE_RESOURCES + _ = Resources.incrementTotal() + #endif + + super.init(target: parent.target, retainTarget: parent.retainTarget, keyPath: parent.keyPath, options: parent.options.nsOptions, callback: callback) + self.retainSelf = self + } + + override func dispose() { + super.dispose() + self.retainSelf = nil + } + + deinit { + #if TRACE_RESOURCES + _ = Resources.decrementTotal() + #endif + } +} + +private final class KVOObservable + : ObservableType + , KVOObservableProtocol { + typealias Element = Element? + + unowned var target: AnyObject + var strongTarget: AnyObject? + + var keyPath: String + var options: KeyValueObservingOptions + var retainTarget: Bool + + init(object: AnyObject, keyPath: String, options: KeyValueObservingOptions, retainTarget: Bool) { + self.target = object + self.keyPath = keyPath + self.options = options + self.retainTarget = retainTarget + if retainTarget { + self.strongTarget = object + } + } + + func subscribe(_ observer: Observer) -> Disposable where Observer.Element == Element? { + let observer = KVOObserver(parent: self) { value in + if value as? NSNull != nil { + observer.on(.next(nil)) + return + } + observer.on(.next(value as? Element)) + } + + return Disposables.create(with: observer.dispose) + } + +} + +private extension KeyValueObservingOptions { + var nsOptions: NSKeyValueObservingOptions { + var result: UInt = 0 + if self.contains(.new) { + result |= NSKeyValueObservingOptions.new.rawValue + } + if self.contains(.initial) { + result |= NSKeyValueObservingOptions.initial.rawValue + } + + return NSKeyValueObservingOptions(rawValue: result) + } +} + +#endif + +#if !DISABLE_SWIZZLING && !os(Linux) + + private func observeWeaklyKeyPathFor(_ target: NSObject, keyPath: String, options: KeyValueObservingOptions) -> Observable { + let components = keyPath.components(separatedBy: ".").filter { $0 != "self" } + + let observable = observeWeaklyKeyPathFor(target, keyPathSections: components, options: options) + .finishWithNilWhenDealloc(target) + + if !options.isDisjoint(with: .initial) { + return observable + } + else { + return observable + .skip(1) + } + } + + // This should work correctly + // Identifiers can't contain `,`, so the only place where `,` can appear + // is as a delimiter. + // This means there is `W` as element in an array of property attributes. + private func isWeakProperty(_ properyRuntimeInfo: String) -> Bool { + properyRuntimeInfo.range(of: ",W,") != nil + } + + private extension ObservableType where Element == AnyObject? { + func finishWithNilWhenDealloc(_ target: NSObject) + -> Observable { + let deallocating = target.rx.deallocating + + return deallocating + .map { _ in + return Observable.just(nil) + } + .startWith(self.asObservable()) + .switchLatest() + } + } + + private func observeWeaklyKeyPathFor( + _ target: NSObject, + keyPathSections: [String], + options: KeyValueObservingOptions + ) -> Observable { + + weak var weakTarget: AnyObject? = target + + let propertyName = keyPathSections[0] + let remainingPaths = Array(keyPathSections[1.. + + // KVO recursion for value changes + return propertyObservable + .flatMapLatest { (nextTarget: AnyObject?) -> Observable in + if nextTarget == nil { + return Observable.just(nil) + } + let nextObject = nextTarget! as? NSObject + + let strongTarget: AnyObject? = weakTarget + + if nextObject == nil { + return Observable.error(RxCocoaError.invalidObjectOnKeyPath(object: nextTarget!, sourceObject: strongTarget ?? NSNull(), propertyName: propertyName)) + } + + // if target is alive, then send change + // if it's deallocated, don't send anything + if strongTarget == nil { + return Observable.empty() + } + + let nextElementsObservable = keyPathSections.count == 1 + ? Observable.just(nextTarget) + : observeWeaklyKeyPathFor(nextObject!, keyPathSections: remainingPaths, options: options) + + if isWeak { + return nextElementsObservable + .finishWithNilWhenDealloc(nextObject!) + } + else { + return nextElementsObservable + } + } + } +#endif + +// MARK: Constants + +private let deallocSelector = NSSelectorFromString("dealloc") + +// MARK: AnyObject + Reactive + +extension Reactive where Base: AnyObject { + func synchronized( _ action: () -> T) -> T { + objc_sync_enter(self.base) + let result = action() + objc_sync_exit(self.base) + return result + } +} + +extension Reactive where Base: AnyObject { + /** + Helper to make sure that `Observable` returned from `createCachedObservable` is only created once. + This is important because there is only one `target` and `action` properties on `NSControl` or `UIBarButtonItem`. + */ + func lazyInstanceObservable(_ key: UnsafeRawPointer, createCachedObservable: () -> T) -> T { + if let value = objc_getAssociatedObject(self.base, key) { + return value as! T + } + + let observable = createCachedObservable() + + objc_setAssociatedObject(self.base, key, observable, .OBJC_ASSOCIATION_RETAIN_NONATOMIC) + + return observable + } +} + +#endif diff --git a/Pods/RxCocoa/RxCocoa/Foundation/NotificationCenter+Rx.swift b/Pods/RxCocoa/RxCocoa/Foundation/NotificationCenter+Rx.swift new file mode 100644 index 0000000..30ffa2b --- /dev/null +++ b/Pods/RxCocoa/RxCocoa/Foundation/NotificationCenter+Rx.swift @@ -0,0 +1,31 @@ +// +// NotificationCenter+Rx.swift +// RxCocoa +// +// Created by Krunoslav Zaher on 5/2/15. +// Copyright © 2015 Krunoslav Zaher. All rights reserved. +// + +import Foundation +import RxSwift + +extension Reactive where Base: NotificationCenter { + /** + Transforms notifications posted to notification center to observable sequence of notifications. + + - parameter name: Optional name used to filter notifications. + - parameter object: Optional object used to filter notifications. + - returns: Observable sequence of posted notifications. + */ + public func notification(_ name: Notification.Name?, object: AnyObject? = nil) -> Observable { + return Observable.create { [weak object] observer in + let nsObserver = self.base.addObserver(forName: name, object: object, queue: nil) { notification in + observer.on(.next(notification)) + } + + return Disposables.create { + self.base.removeObserver(nsObserver) + } + } + } +} diff --git a/Pods/RxCocoa/RxCocoa/Foundation/URLSession+Rx.swift b/Pods/RxCocoa/RxCocoa/Foundation/URLSession+Rx.swift new file mode 100644 index 0000000..93e65cc --- /dev/null +++ b/Pods/RxCocoa/RxCocoa/Foundation/URLSession+Rx.swift @@ -0,0 +1,240 @@ +// +// URLSession+Rx.swift +// RxCocoa +// +// Created by Krunoslav Zaher on 3/23/15. +// Copyright © 2015 Krunoslav Zaher. All rights reserved. +// + +import Foundation +import RxSwift + +#if canImport(FoundationNetworking) +import FoundationNetworking +#endif + +/// RxCocoa URL errors. +public enum RxCocoaURLError + : Swift.Error { + /// Unknown error occurred. + case unknown + /// Response is not NSHTTPURLResponse + case nonHTTPResponse(response: URLResponse) + /// Response is not successful. (not in `200 ..< 300` range) + case httpRequestFailed(response: HTTPURLResponse, data: Data?) + /// Deserialization error. + case deserializationError(error: Swift.Error) +} + +extension RxCocoaURLError + : CustomDebugStringConvertible { + /// A textual representation of `self`, suitable for debugging. + public var debugDescription: String { + switch self { + case .unknown: + return "Unknown error has occurred." + case let .nonHTTPResponse(response): + return "Response is not NSHTTPURLResponse `\(response)`." + case let .httpRequestFailed(response, _): + return "HTTP request failed with `\(response.statusCode)`." + case let .deserializationError(error): + return "Error during deserialization of the response: \(error)" + } + } +} + +private func escapeTerminalString(_ value: String) -> String { + return value.replacingOccurrences(of: "\"", with: "\\\"", options:[], range: nil) +} + +private func convertURLRequestToCurlCommand(_ request: URLRequest) -> String { + let method = request.httpMethod ?? "GET" + var returnValue = "curl -X \(method) " + + if let httpBody = request.httpBody { + let maybeBody = String(data: httpBody, encoding: String.Encoding.utf8) + if let body = maybeBody { + returnValue += "-d \"\(escapeTerminalString(body))\" " + } + } + + for (key, value) in request.allHTTPHeaderFields ?? [:] { + let escapedKey = escapeTerminalString(key as String) + let escapedValue = escapeTerminalString(value as String) + returnValue += "\n -H \"\(escapedKey): \(escapedValue)\" " + } + + let URLString = request.url?.absoluteString ?? "" + + returnValue += "\n\"\(escapeTerminalString(URLString))\"" + + returnValue += " -i -v" + + return returnValue +} + +private func convertResponseToString(_ response: URLResponse?, _ error: NSError?, _ interval: TimeInterval) -> String { + let ms = Int(interval * 1000) + + if let response = response as? HTTPURLResponse { + if 200 ..< 300 ~= response.statusCode { + return "Success (\(ms)ms): Status \(response.statusCode)" + } + else { + return "Failure (\(ms)ms): Status \(response.statusCode)" + } + } + + if let error = error { + if error.domain == NSURLErrorDomain && error.code == NSURLErrorCancelled { + return "Canceled (\(ms)ms)" + } + return "Failure (\(ms)ms): NSError > \(error)" + } + + return "" +} + +extension Reactive where Base: URLSession { + /** + Observable sequence of responses for URL request. + + Performing of request starts after observer is subscribed and not after invoking this method. + + **URL requests will be performed per subscribed observer.** + + Any error during fetching of the response will cause observed sequence to terminate with error. + + - parameter request: URL request. + - returns: Observable sequence of URL responses. + */ + public func response(request: URLRequest) -> Observable<(response: HTTPURLResponse, data: Data)> { + return Observable.create { observer in + + // smart compiler should be able to optimize this out + let d: Date? + + if URLSession.rx.shouldLogRequest(request) { + d = Date() + } + else { + d = nil + } + + let task = self.base.dataTask(with: request) { data, response, error in + + if URLSession.rx.shouldLogRequest(request) { + let interval = Date().timeIntervalSince(d ?? Date()) + print(convertURLRequestToCurlCommand(request)) + #if os(Linux) + print(convertResponseToString(response, error.flatMap { $0 as NSError }, interval)) + #else + print(convertResponseToString(response, error.map { $0 as NSError }, interval)) + #endif + } + + guard let response = response, let data = data else { + observer.on(.error(error ?? RxCocoaURLError.unknown)) + return + } + + guard let httpResponse = response as? HTTPURLResponse else { + observer.on(.error(RxCocoaURLError.nonHTTPResponse(response: response))) + return + } + + observer.on(.next((httpResponse, data))) + observer.on(.completed) + } + + task.resume() + + return Disposables.create(with: task.cancel) + } + } + + /** + Observable sequence of response data for URL request. + + Performing of request starts after observer is subscribed and not after invoking this method. + + **URL requests will be performed per subscribed observer.** + + Any error during fetching of the response will cause observed sequence to terminate with error. + + If response is not HTTP response with status code in the range of `200 ..< 300`, sequence + will terminate with `(RxCocoaErrorDomain, RxCocoaError.NetworkError)`. + + - parameter request: URL request. + - returns: Observable sequence of response data. + */ + public func data(request: URLRequest) -> Observable { + return self.response(request: request).map { pair -> Data in + if 200 ..< 300 ~= pair.0.statusCode { + return pair.1 + } + else { + throw RxCocoaURLError.httpRequestFailed(response: pair.0, data: pair.1) + } + } + } + + /** + Observable sequence of response JSON for URL request. + + Performing of request starts after observer is subscribed and not after invoking this method. + + **URL requests will be performed per subscribed observer.** + + Any error during fetching of the response will cause observed sequence to terminate with error. + + If response is not HTTP response with status code in the range of `200 ..< 300`, sequence + will terminate with `(RxCocoaErrorDomain, RxCocoaError.NetworkError)`. + + If there is an error during JSON deserialization observable sequence will fail with that error. + + - parameter request: URL request. + - returns: Observable sequence of response JSON. + */ + public func json(request: URLRequest, options: JSONSerialization.ReadingOptions = []) -> Observable { + return self.data(request: request).map { data -> Any in + do { + return try JSONSerialization.jsonObject(with: data, options: options) + } catch let error { + throw RxCocoaURLError.deserializationError(error: error) + } + } + } + + /** + Observable sequence of response JSON for GET request with `URL`. + + Performing of request starts after observer is subscribed and not after invoking this method. + + **URL requests will be performed per subscribed observer.** + + Any error during fetching of the response will cause observed sequence to terminate with error. + + If response is not HTTP response with status code in the range of `200 ..< 300`, sequence + will terminate with `(RxCocoaErrorDomain, RxCocoaError.NetworkError)`. + + If there is an error during JSON deserialization observable sequence will fail with that error. + + - parameter url: URL of `NSURLRequest` request. + - returns: Observable sequence of response JSON. + */ + public func json(url: Foundation.URL) -> Observable { + self.json(request: URLRequest(url: url)) + } +} + +extension Reactive where Base == URLSession { + /// Log URL requests to standard output in curl format. + public static var shouldLogRequest: (URLRequest) -> Bool = { _ in + #if DEBUG + return true + #else + return false + #endif + } +} diff --git a/Pods/RxCocoa/RxCocoa/Runtime/_RX.m b/Pods/RxCocoa/RxCocoa/Runtime/_RX.m new file mode 100644 index 0000000..cffbfbc --- /dev/null +++ b/Pods/RxCocoa/RxCocoa/Runtime/_RX.m @@ -0,0 +1,10 @@ +// +// _RX.m +// RxCocoa +// +// Created by Krunoslav Zaher on 7/12/15. +// Copyright © 2015 Krunoslav Zaher. All rights reserved. +// + +#import "include/_RX.h" + diff --git a/Pods/RxCocoa/RxCocoa/Runtime/_RXDelegateProxy.m b/Pods/RxCocoa/RxCocoa/Runtime/_RXDelegateProxy.m new file mode 100644 index 0000000..36338a5 --- /dev/null +++ b/Pods/RxCocoa/RxCocoa/Runtime/_RXDelegateProxy.m @@ -0,0 +1,147 @@ +// +// _RXDelegateProxy.m +// RxCocoa +// +// Created by Krunoslav Zaher on 7/4/15. +// Copyright © 2015 Krunoslav Zaher. All rights reserved. +// + +#import "include/_RXDelegateProxy.h" +#import "include/_RX.h" +#import "include/_RXObjCRuntime.h" + +@interface _RXDelegateProxy () { + id __weak __forwardToDelegate; +} + +@property (nonatomic, strong) id strongForwardDelegate; + +@end + +static NSMutableDictionary *voidSelectorsPerClass = nil; + +@implementation _RXDelegateProxy + ++(NSSet*)collectVoidSelectorsForProtocol:(Protocol *)protocol { + NSMutableSet *selectors = [NSMutableSet set]; + + unsigned int protocolMethodCount = 0; + struct objc_method_description *pMethods = protocol_copyMethodDescriptionList(protocol, NO, YES, &protocolMethodCount); + + for (unsigned int i = 0; i < protocolMethodCount; ++i) { + struct objc_method_description method = pMethods[i]; + if (RX_is_method_with_description_void(method)) { + [selectors addObject:SEL_VALUE(method.name)]; + } + } + + free(pMethods); + + unsigned int numberOfBaseProtocols = 0; + Protocol * __unsafe_unretained * pSubprotocols = protocol_copyProtocolList(protocol, &numberOfBaseProtocols); + + for (unsigned int i = 0; i < numberOfBaseProtocols; ++i) { + [selectors unionSet:[self collectVoidSelectorsForProtocol:pSubprotocols[i]]]; + } + + free(pSubprotocols); + + return selectors; +} + ++(void)initialize { + @synchronized (_RXDelegateProxy.class) { + if (voidSelectorsPerClass == nil) { + voidSelectorsPerClass = [[NSMutableDictionary alloc] init]; + } + + NSMutableSet *voidSelectors = [NSMutableSet set]; + +#define CLASS_HIERARCHY_MAX_DEPTH 100 + + NSInteger classHierarchyDepth = 0; + Class targetClass = NULL; + + for (classHierarchyDepth = 0, targetClass = self; + classHierarchyDepth < CLASS_HIERARCHY_MAX_DEPTH && targetClass != nil; + ++classHierarchyDepth, targetClass = class_getSuperclass(targetClass) + ) { + unsigned int count; + Protocol *__unsafe_unretained *pProtocols = class_copyProtocolList(targetClass, &count); + + for (unsigned int i = 0; i < count; i++) { + NSSet *selectorsForProtocol = [self collectVoidSelectorsForProtocol:pProtocols[i]]; + [voidSelectors unionSet:selectorsForProtocol]; + } + + free(pProtocols); + } + + if (classHierarchyDepth == CLASS_HIERARCHY_MAX_DEPTH) { + NSLog(@"Detected weird class hierarchy with depth over %d. Starting with this class -> %@", CLASS_HIERARCHY_MAX_DEPTH, self); +#if DEBUG + abort(); +#endif + } + + voidSelectorsPerClass[CLASS_VALUE(self)] = voidSelectors; + } +} + +-(id)_forwardToDelegate { + return __forwardToDelegate; +} + +-(void)_setForwardToDelegate:(id __nullable)forwardToDelegate retainDelegate:(BOOL)retainDelegate { + __forwardToDelegate = forwardToDelegate; + if (retainDelegate) { + self.strongForwardDelegate = forwardToDelegate; + } + else { + self.strongForwardDelegate = nil; + } +} + +-(BOOL)hasWiredImplementationForSelector:(SEL)selector { + return [super respondsToSelector:selector]; +} + +-(BOOL)voidDelegateMethodsContain:(SEL)selector { + @synchronized(_RXDelegateProxy.class) { + NSSet *voidSelectors = voidSelectorsPerClass[CLASS_VALUE(self.class)]; + NSAssert(voidSelectors != nil, @"Set of allowed methods not initialized"); + return [voidSelectors containsObject:SEL_VALUE(selector)]; + } +} + +-(void)forwardInvocation:(NSInvocation *)anInvocation { + BOOL isVoid = RX_is_method_signature_void(anInvocation.methodSignature); + NSArray *arguments = nil; + if (isVoid) { + arguments = RX_extract_arguments(anInvocation); + [self _sentMessage:anInvocation.selector withArguments:arguments]; + } + + if (self._forwardToDelegate && [self._forwardToDelegate respondsToSelector:anInvocation.selector]) { + [anInvocation invokeWithTarget:self._forwardToDelegate]; + } + + if (isVoid) { + [self _methodInvoked:anInvocation.selector withArguments:arguments]; + } +} + +// abstract method +-(void)_sentMessage:(SEL)selector withArguments:(NSArray *)arguments { + +} + +// abstract method +-(void)_methodInvoked:(SEL)selector withArguments:(NSArray *)arguments { + +} + +-(void)dealloc { +} + +@end diff --git a/Pods/RxCocoa/RxCocoa/Runtime/_RXKVOObserver.m b/Pods/RxCocoa/RxCocoa/Runtime/_RXKVOObserver.m new file mode 100644 index 0000000..fc8fb75 --- /dev/null +++ b/Pods/RxCocoa/RxCocoa/Runtime/_RXKVOObserver.m @@ -0,0 +1,54 @@ +// +// _RXKVOObserver.m +// RxCocoa +// +// Created by Krunoslav Zaher on 7/11/15. +// Copyright © 2015 Krunoslav Zaher. All rights reserved. +// + +#import "include/_RXKVOObserver.h" + +@interface _RXKVOObserver () + +@property (nonatomic, unsafe_unretained) id target; +@property (nonatomic, strong ) id retainedTarget; +@property (nonatomic, copy ) NSString *keyPath; +@property (nonatomic, copy ) void (^callback)(id); + +@end + +@implementation _RXKVOObserver + +-(instancetype)initWithTarget:(id)target + retainTarget:(BOOL)retainTarget + keyPath:(NSString*)keyPath + options:(NSKeyValueObservingOptions)options + callback:(void (^)(id))callback { + self = [super init]; + if (!self) return nil; + + self.target = target; + if (retainTarget) { + self.retainedTarget = target; + } + self.keyPath = keyPath; + self.callback = callback; + + [self.target addObserver:self forKeyPath:self.keyPath options:options context:nil]; + + return self; +} + +-(void)observeValueForKeyPath:(NSString *)keyPath ofObject:(id)object change:(NSDictionary *)change context:(void *)context { + @synchronized(self) { + self.callback(change[NSKeyValueChangeNewKey]); + } +} + +-(void)dispose { + [self.target removeObserver:self forKeyPath:self.keyPath context:nil]; + self.target = nil; + self.retainedTarget = nil; +} + +@end diff --git a/Pods/RxCocoa/RxCocoa/Runtime/_RXObjCRuntime.m b/Pods/RxCocoa/RxCocoa/Runtime/_RXObjCRuntime.m new file mode 100644 index 0000000..2e685aa --- /dev/null +++ b/Pods/RxCocoa/RxCocoa/Runtime/_RXObjCRuntime.m @@ -0,0 +1,1062 @@ +// +// _RXObjCRuntime.m +// RxCocoa +// +// Created by Krunoslav Zaher on 7/11/15. +// Copyright © 2015 Krunoslav Zaher. All rights reserved. +// + +#import +#import +#import +#import +#import +#import + +#import "include/_RX.h" +#import "include/_RXObjCRuntime.h" + +// self + cmd +#define HIDDEN_ARGUMENT_COUNT 2 + +#if !DISABLE_SWIZZLING + +#define NSErrorParam NSError *__autoreleasing __nullable * __nullable + +@class RXObjCRuntime; + +BOOL RXAbortOnThreadingHazard = NO; + +typedef NSInvocation *NSInvocationRef; +typedef NSMethodSignature *NSMethodSignatureRef; +typedef unsigned char rx_uchar; +typedef unsigned short rx_ushort; +typedef unsigned int rx_uint; +typedef unsigned long rx_ulong; +typedef id (^rx_block)(id); +typedef BOOL (^RXInterceptWithOptimizedObserver)(RXObjCRuntime * __nonnull self, Class __nonnull class, SEL __nonnull selector, NSErrorParam error); + +static CFTypeID defaultTypeID; +static SEL deallocSelector; + +static int RxSwizzlingTargetClassKey = 0; + +#if TRACE_RESOURCES +_Atomic static int32_t numberOInterceptedMethods = 0; +_Atomic static int32_t numberOfForwardedMethods = 0; +#endif + +#define THREADING_HAZARD(class) \ + NSLog(@"There was a problem swizzling on `%@`.\nYou have probably two libraries performing swizzling in runtime.\nWe didn't want to crash your program, but this is not good ...\nYou an solve this problem by either not using swizzling in this library, removing one of those other libraries, or making sure that swizzling parts are synchronized (only perform them on main thread).\nAnd yes, this message will self destruct when you clear the console, and since it's non deterministic, the problem could still exist and it will be hard for you to reproduce it.", NSStringFromClass(class)); ABORT_IN_DEBUG if (RXAbortOnThreadingHazard) { abort(); } + +#define ALWAYS(condition, message) if (!(condition)) { [NSException raise:@"RX Invalid Operator" format:@"%@", message]; } +#define ALWAYS_WITH_INFO(condition, message) NSAssert((condition), @"%@ [%@] > %@", NSStringFromClass(class), NSStringFromSelector(selector), (message)) +#define C_ALWAYS(condition, message) NSCAssert((condition), @"%@ [%@] > %@", NSStringFromClass(class), NSStringFromSelector(selector), (message)) + +#define RX_PREFIX @"_RX_namespace_" + +#define RX_ARG_id(value) ((value) ?: [NSNull null]) +#define RX_ARG_char(value) [NSNumber numberWithChar:value] +#define RX_ARG_short(value) [NSNumber numberWithShort:value] +#define RX_ARG_int(value) [NSNumber numberWithInt:value] +#define RX_ARG_long(value) [NSNumber numberWithLong:value] +#define RX_ARG_BOOL(value) [NSNumber numberWithBool:value] +#define RX_ARG_SEL(value) [NSNumber valueWithPointer:value] +#define RX_ARG_rx_uchar(value) [NSNumber numberWithUnsignedInt:value] +#define RX_ARG_rx_ushort(value) [NSNumber numberWithUnsignedInt:value] +#define RX_ARG_rx_uint(value) [NSNumber numberWithUnsignedInt:value] +#define RX_ARG_rx_ulong(value) [NSNumber numberWithUnsignedLong:value] +#define RX_ARG_rx_block(value) ((id)(value) ?: [NSNull null]) +#define RX_ARG_float(value) [NSNumber numberWithFloat:value] +#define RX_ARG_double(value) [NSNumber numberWithDouble:value] + +typedef struct supported_type { + const char *encoding; +} supported_type_t; + +static supported_type_t supported_types[] = { + { .encoding = @encode(void)}, + { .encoding = @encode(id)}, + { .encoding = @encode(Class)}, + { .encoding = @encode(void (^)(void))}, + { .encoding = @encode(char)}, + { .encoding = @encode(short)}, + { .encoding = @encode(int)}, + { .encoding = @encode(long)}, + { .encoding = @encode(long long)}, + { .encoding = @encode(unsigned char)}, + { .encoding = @encode(unsigned short)}, + { .encoding = @encode(unsigned int)}, + { .encoding = @encode(unsigned long)}, + { .encoding = @encode(unsigned long long)}, + { .encoding = @encode(float)}, + { .encoding = @encode(double)}, + { .encoding = @encode(BOOL)}, + { .encoding = @encode(const char*)}, +}; + +NSString * __nonnull const RXObjCRuntimeErrorDomain = @"RXObjCRuntimeErrorDomain"; +NSString * __nonnull const RXObjCRuntimeErrorIsKVOKey = @"RXObjCRuntimeErrorIsKVOKey"; + +BOOL RX_return_type_is_supported(const char *type) { + if (type == nil) { + return NO; + } + + for (int i = 0; i < sizeof(supported_types) / sizeof(supported_type_t); ++i) { + if (supported_types[i].encoding[0] != type[0]) { + continue; + } + if (strcmp(supported_types[i].encoding, type) == 0) { + return YES; + } + } + + return NO; +} + +static BOOL RX_method_has_supported_return_type(Method method) { + const char *rawEncoding = method_getTypeEncoding(method); + ALWAYS(rawEncoding != nil, @"Example encoding method is nil."); + + NSMethodSignature *methodSignature = [NSMethodSignature signatureWithObjCTypes:rawEncoding]; + ALWAYS(methodSignature != nil, @"Method signature method is nil."); + + return RX_return_type_is_supported(methodSignature.methodReturnType); +} + +SEL __nonnull RX_selector(SEL __nonnull selector) { + NSString *selectorString = NSStringFromSelector(selector); + return NSSelectorFromString([RX_PREFIX stringByAppendingString:selectorString]); +} + +#endif + +BOOL RX_is_method_signature_void(NSMethodSignature * __nonnull methodSignature) { + const char *methodReturnType = methodSignature.methodReturnType; + return strcmp(methodReturnType, @encode(void)) == 0; +} + +BOOL RX_is_method_with_description_void(struct objc_method_description method) { + return strncmp(method.types, @encode(void), 1) == 0; +} + +id __nonnull RX_extract_argument_at_index(NSInvocation * __nonnull invocation, NSUInteger index) { + const char *argumentType = [invocation.methodSignature getArgumentTypeAtIndex:index]; + +#define RETURN_VALUE(type) \ + else if (strcmp(argumentType, @encode(type)) == 0) {\ + type val = 0; \ + [invocation getArgument:&val atIndex:index]; \ + return @(val); \ + } + + // Skip const type qualifier. + if (argumentType[0] == 'r') { + argumentType++; + } + + if (strcmp(argumentType, @encode(id)) == 0 + || strcmp(argumentType, @encode(Class)) == 0 + || strcmp(argumentType, @encode(void (^)(void))) == 0 + ) { + __unsafe_unretained id argument = nil; + [invocation getArgument:&argument atIndex:index]; + return argument; + } + RETURN_VALUE(char) + RETURN_VALUE(short) + RETURN_VALUE(int) + RETURN_VALUE(long) + RETURN_VALUE(long long) + RETURN_VALUE(unsigned char) + RETURN_VALUE(unsigned short) + RETURN_VALUE(unsigned int) + RETURN_VALUE(unsigned long) + RETURN_VALUE(unsigned long long) + RETURN_VALUE(float) + RETURN_VALUE(double) + RETURN_VALUE(BOOL) + RETURN_VALUE(const char *) + else { + NSUInteger size = 0; + NSGetSizeAndAlignment(argumentType, &size, NULL); + NSCParameterAssert(size > 0); + uint8_t data[size]; + [invocation getArgument:&data atIndex:index]; + + return [NSValue valueWithBytes:&data objCType:argumentType]; + } +} + +NSArray *RX_extract_arguments(NSInvocation *invocation) { + NSUInteger numberOfArguments = invocation.methodSignature.numberOfArguments; + NSUInteger numberOfVisibleArguments = numberOfArguments - HIDDEN_ARGUMENT_COUNT; + + NSCParameterAssert(numberOfVisibleArguments >= 0); + + NSMutableArray *arguments = [NSMutableArray arrayWithCapacity:numberOfVisibleArguments]; + + for (NSUInteger index = HIDDEN_ARGUMENT_COUNT; index < numberOfArguments; ++index) { + [arguments addObject:RX_extract_argument_at_index(invocation, index) ?: [NSNull null]]; + } + + return arguments; +} + +IMP __nonnull RX_default_target_implementation(void) { + return _objc_msgForward; +} + +#if !DISABLE_SWIZZLING + +void * __nonnull RX_reference_from_selector(SEL __nonnull selector) { + return selector; +} + +static BOOL RX_forward_invocation(id __nonnull __unsafe_unretained self, NSInvocation *invocation) { + SEL originalSelector = RX_selector(invocation.selector); + + id messageSentObserver = objc_getAssociatedObject(self, originalSelector); + + if (messageSentObserver != nil) { + NSArray *arguments = RX_extract_arguments(invocation); + [messageSentObserver messageSentWithArguments:arguments]; + } + + if ([self respondsToSelector:originalSelector]) { + invocation.selector = originalSelector; + [invocation invokeWithTarget:self]; + + if (messageSentObserver != nil) { + NSArray *arguments = RX_extract_arguments(invocation); + [messageSentObserver methodInvokedWithArguments:arguments]; + } + + return YES; + } + + return NO; +} + +static BOOL RX_responds_to_selector(id __nonnull __unsafe_unretained self, SEL selector) { + Class class = object_getClass(self); + if (class == nil) { return NO; } + + Method m = class_getInstanceMethod(class, selector); + return m != nil; + +} + +static NSMethodSignatureRef RX_method_signature(id __nonnull __unsafe_unretained self, SEL selector) { + Class class = object_getClass(self); + if (class == nil) { return nil; } + + Method method = class_getInstanceMethod(class, selector); + if (method == nil) { return nil; } + + const char *encoding = method_getTypeEncoding(method); + if (encoding == nil) { return nil; } + + return [NSMethodSignature signatureWithObjCTypes:encoding]; +} + +static NSString * __nonnull RX_method_encoding(Method __nonnull method) { + const char *typeEncoding = method_getTypeEncoding(method); + ALWAYS(typeEncoding != nil, @"Method encoding is nil."); + + NSString *encoding = [NSString stringWithCString:typeEncoding encoding:NSASCIIStringEncoding]; + ALWAYS(encoding != nil, @"Can't convert encoding to NSString."); + return encoding; +} + +@interface RXObjCRuntime: NSObject + +@property (nonatomic, assign) pthread_mutex_t lock; + +@property (nonatomic, strong) NSMutableSet *classesThatSupportObservingByForwarding; +@property (nonatomic, strong) NSMutableDictionary *> *forwardedSelectorsByClass; + +@property (nonatomic, strong) NSMutableDictionary *dynamicSubclassByRealClass; +@property (nonatomic, strong) NSMutableDictionary*> *interceptorIMPbySelectorsByClass; + ++(RXObjCRuntime*)instance; + +-(void)performLocked:(void (^)(RXObjCRuntime* __nonnull))action; +-(IMP __nullable)ensurePrepared:(id __nonnull)target forObserving:(SEL __nonnull)selector error:(NSErrorParam)error; +-(BOOL)ensureSwizzledSelector:(SEL __nonnull)selector + ofClass:(Class __nonnull)class + newImplementationGenerator:(IMP(^)(void))newImplementationGenerator +replacementImplementationGenerator:(IMP (^)(IMP originalImplementation))replacementImplementationGenerator + error:(NSErrorParam)error; + + ++(void)registerOptimizedObserver:(RXInterceptWithOptimizedObserver)registration encodedAs:(SEL)selector; + +@end + +/** + All API methods perform work on locked instance of `RXObjCRuntime`. In that way it's easy to prove + that every action is properly locked. + */ +IMP __nullable RX_ensure_observing(id __nonnull target, SEL __nonnull selector, NSErrorParam error) { + __block IMP targetImplementation = nil; + // Target is the second object that needs to be synchronized to TRY to make sure other swizzling framework + // won't do something in parallel. + // Even though this is too fine grained locking and more coarse grained locks should exist, this is just in case + // someone calls this method directly without any external lock. + @synchronized(target) { + // The only other resource that all other swizzling libraries have in common without introducing external + // dependencies is class object. + // + // It is polite to try to synchronize it in hope other unknown entities will also attempt to do so. + // It's like trying to figure out how to communicate with aliens without actually communicating, + // save for the fact that aliens are people, programmers, authors of swizzling libraries. + @synchronized([target class]) { + [[RXObjCRuntime instance] performLocked:^(RXObjCRuntime * __nonnull self) { + targetImplementation = [self ensurePrepared:target + forObserving:selector + error:error]; + }]; + } + } + + return targetImplementation; +} + +// bodies + +#define FORWARD_BODY(invocation) if (RX_forward_invocation(self, NAME_CAT(_, 0, invocation))) { return; } + +#define RESPONDS_TO_SELECTOR_BODY(selector) if (RX_responds_to_selector(self, NAME_CAT(_, 0, selector))) return YES; + +#define CLASS_BODY(...) return actAsClass; + +#define METHOD_SIGNATURE_FOR_SELECTOR_BODY(selector) \ + NSMethodSignatureRef methodSignature = RX_method_signature(self, NAME_CAT(_, 0, selector)); \ + if (methodSignature != nil) { \ + return methodSignature; \ + } + +#define DEALLOCATING_BODY(...) \ + id observer = objc_getAssociatedObject(self, rxSelector); \ + if (observer != nil && observer.targetImplementation == thisIMP) { \ + [observer deallocating]; \ + } + +#define OBSERVE_BODY(...) \ + id observer = objc_getAssociatedObject(self, rxSelector); \ + \ + if (observer != nil && observer.targetImplementation == thisIMP) { \ + [observer messageSentWithArguments:@[COMMA_DELIMITED_ARGUMENTS(__VA_ARGS__)]]; \ + } \ + + +#define OBSERVE_INVOKED_BODY(...) \ + if (observer != nil && observer.targetImplementation == thisIMP) { \ + [observer methodInvokedWithArguments:@[COMMA_DELIMITED_ARGUMENTS(__VA_ARGS__)]]; \ + } \ + + +#define BUILD_ARG_WRAPPER(type) RX_ARG_ ## type //RX_ARG_ ## type + +#define CAT(_1, _2, head, tail) RX_CAT2(head, tail) +#define SEPARATE_BY_COMMA(_1, _2, head, tail) head, tail +#define SEPARATE_BY_SPACE(_1, _2, head, tail) head tail +#define SEPARATE_BY_UNDERSCORE(head, tail) RX_CAT2(RX_CAT2(head, _), tail) + +#define UNDERSCORE_TYPE_CAT(_1, index, type) RX_CAT2(_, type) // generates -> _type +#define NAME_CAT(_1, index, type) SEPARATE_BY_UNDERSCORE(type, index) // generates -> type_0 +#define TYPE_AND_NAME_CAT(_1, index, type) type SEPARATE_BY_UNDERSCORE(type, index) // generates -> type type_0 +#define NOT_NULL_ARGUMENT_CAT(_1, index, type) BUILD_ARG_WRAPPER(type)(NAME_CAT(_1, index, type)) // generates -> ((id)(type_0) ?: [NSNull null]) +#define EXAMPLE_PARAMETER(_1, index, type) RX_CAT2(_, type):(type)SEPARATE_BY_UNDERSCORE(type, index) // generates -> _type:(type)type_0 +#define SELECTOR_PART(_1, index, type) RX_CAT2(_, type:) // generates -> _type: + +#define COMMA_DELIMITED_ARGUMENTS(...) RX_FOREACH(_, SEPARATE_BY_COMMA, NOT_NULL_ARGUMENT_CAT, ## __VA_ARGS__) +#define ARGUMENTS(...) RX_FOREACH_COMMA(_, NAME_CAT, ## __VA_ARGS__) +#define DECLARE_ARGUMENTS(...) RX_FOREACH_COMMA(_, TYPE_AND_NAME_CAT, ## __VA_ARGS__) + +// optimized observe methods + +#define GENERATE_SELECTOR_IDENTIFIER(...) RX_CAT2(exampleSelector, RX_FOREACH(_, CAT, UNDERSCORE_TYPE_CAT, ## __VA_ARGS__)) + +#define GENERATE_METHOD_IDENTIFIER(...) RX_CAT2(swizzle, RX_FOREACH(_, CAT, UNDERSCORE_TYPE_CAT, ## __VA_ARGS__)) + +#define GENERATE_OBSERVE_METHOD_DECLARATION(...) \ + -(BOOL)GENERATE_METHOD_IDENTIFIER(__VA_ARGS__):(Class __nonnull)class \ + selector:(SEL)selector \ + error:(NSErrorParam)error { \ + + +#define BUILD_EXAMPLE_METHOD(return_value, ...) \ + +(return_value)RX_CAT2(RX_CAT2(example_, return_value), RX_FOREACH(_, SEPARATE_BY_SPACE, EXAMPLE_PARAMETER, ## __VA_ARGS__)) {} + +#define BUILD_EXAMPLE_METHOD_SELECTOR(return_value, ...) \ + RX_CAT2(RX_CAT2(example_, return_value), RX_FOREACH(_, SEPARATE_BY_SPACE, SELECTOR_PART, ## __VA_ARGS__)) + +#define SWIZZLE_OBSERVE_METHOD_DEFINITIONS(return_value, ...) \ + BUILD_EXAMPLE_METHOD(return_value, ## __VA_ARGS__) \ + SWIZZLE_METHOD(return_value, GENERATE_OBSERVE_METHOD_DECLARATION(return_value, ## __VA_ARGS__), OBSERVE_BODY, OBSERVE_INVOKED_BODY, ## __VA_ARGS__) \ + +#define SWIZZLE_OBSERVE_METHOD_BODY(return_value, ...) \ + __unused SEL GENERATE_SELECTOR_IDENTIFIER(return_value, ## __VA_ARGS__) = @selector(BUILD_EXAMPLE_METHOD_SELECTOR(return_value, ## __VA_ARGS__)); \ + [self registerOptimizedObserver:^BOOL(RXObjCRuntime * __nonnull self, Class __nonnull class, \ + SEL __nonnull selector, NSErrorParam error) { \ + return [self GENERATE_METHOD_IDENTIFIER(return_value, ## __VA_ARGS__):class selector:selector error:error]; \ + } encodedAs:GENERATE_SELECTOR_IDENTIFIER(return_value, ## __VA_ARGS__)]; \ + +// infrastructure method + +#define NO_BODY(...) + +#define SWIZZLE_INFRASTRUCTURE_METHOD(return_value, method_name, parameters, method_selector, body, ...) \ + SWIZZLE_METHOD(return_value, -(BOOL)method_name:(Class __nonnull)class parameters error:(NSErrorParam)error \ + { \ + SEL selector = method_selector; , body, NO_BODY, __VA_ARGS__) \ + + +// common base + +#define SWIZZLE_METHOD(return_value, method_prototype, body, invoked_body, ...) \ +method_prototype \ + __unused SEL rxSelector = RX_selector(selector); \ + IMP (^newImplementationGenerator)(void) = ^() { \ + __block IMP thisIMP = nil; \ + id newImplementation = ^return_value(__unsafe_unretained id self DECLARE_ARGUMENTS(__VA_ARGS__)) { \ + body(__VA_ARGS__) \ + \ + struct objc_super superInfo = { \ + .receiver = self, \ + .super_class = class_getSuperclass(class) \ + }; \ + \ + return_value (*msgSend)(struct objc_super *, SEL DECLARE_ARGUMENTS(__VA_ARGS__)) \ + = (__typeof__(msgSend))objc_msgSendSuper; \ + @try { \ + return msgSend(&superInfo, selector ARGUMENTS(__VA_ARGS__)); \ + } \ + @finally { invoked_body(__VA_ARGS__) } \ + }; \ + \ + thisIMP = imp_implementationWithBlock(newImplementation); \ + return thisIMP; \ + }; \ + \ + IMP (^replacementImplementationGenerator)(IMP) = ^(IMP originalImplementation) { \ + __block return_value (*originalImplementationTyped)(__unsafe_unretained id, SEL DECLARE_ARGUMENTS(__VA_ARGS__) ) \ + = (__typeof__(originalImplementationTyped))(originalImplementation); \ + \ + __block IMP thisIMP = nil; \ + id implementationReplacement = ^return_value(__unsafe_unretained id self DECLARE_ARGUMENTS(__VA_ARGS__) ) { \ + body(__VA_ARGS__) \ + @try { \ + return originalImplementationTyped(self, selector ARGUMENTS(__VA_ARGS__)); \ + } \ + @finally { invoked_body(__VA_ARGS__) } \ + }; \ + \ + thisIMP = imp_implementationWithBlock(implementationReplacement); \ + return thisIMP; \ + }; \ + \ + return [self ensureSwizzledSelector:selector \ + ofClass:class \ + newImplementationGenerator:newImplementationGenerator \ + replacementImplementationGenerator:replacementImplementationGenerator \ + error:error]; \ + } \ + + +@interface RXObjCRuntime (InfrastructureMethods) +@end + +// MARK: Infrastructure Methods + +@implementation RXObjCRuntime (InfrastructureMethods) + +SWIZZLE_INFRASTRUCTURE_METHOD( + void, + swizzleForwardInvocation, + , + @selector(forwardInvocation:), + FORWARD_BODY, + NSInvocationRef +) +SWIZZLE_INFRASTRUCTURE_METHOD( + BOOL, + swizzleRespondsToSelector, + , + @selector(respondsToSelector:), + RESPONDS_TO_SELECTOR_BODY, + SEL +) +SWIZZLE_INFRASTRUCTURE_METHOD( + Class __nonnull, + swizzleClass, + toActAs:(Class)actAsClass, + @selector(class), + CLASS_BODY +) +SWIZZLE_INFRASTRUCTURE_METHOD( + NSMethodSignatureRef, + swizzleMethodSignatureForSelector, + , + @selector(methodSignatureForSelector:), + METHOD_SIGNATURE_FOR_SELECTOR_BODY, + SEL +) +SWIZZLE_INFRASTRUCTURE_METHOD( + void, + swizzleDeallocating, + , + deallocSelector, + DEALLOCATING_BODY +) + +@end + +// MARK: Optimized intercepting methods for specific combination of parameter types + +@interface RXObjCRuntime (swizzle) + +@end + +@implementation RXObjCRuntime(swizzle) + +SWIZZLE_OBSERVE_METHOD_DEFINITIONS(void) + +SWIZZLE_OBSERVE_METHOD_DEFINITIONS(void, id) +SWIZZLE_OBSERVE_METHOD_DEFINITIONS(void, char) +SWIZZLE_OBSERVE_METHOD_DEFINITIONS(void, short) +SWIZZLE_OBSERVE_METHOD_DEFINITIONS(void, int) +SWIZZLE_OBSERVE_METHOD_DEFINITIONS(void, long) +SWIZZLE_OBSERVE_METHOD_DEFINITIONS(void, rx_uchar) +SWIZZLE_OBSERVE_METHOD_DEFINITIONS(void, rx_ushort) +SWIZZLE_OBSERVE_METHOD_DEFINITIONS(void, rx_uint) +SWIZZLE_OBSERVE_METHOD_DEFINITIONS(void, rx_ulong) +SWIZZLE_OBSERVE_METHOD_DEFINITIONS(void, rx_block) +SWIZZLE_OBSERVE_METHOD_DEFINITIONS(void, float) +SWIZZLE_OBSERVE_METHOD_DEFINITIONS(void, double) +SWIZZLE_OBSERVE_METHOD_DEFINITIONS(void, SEL) + +SWIZZLE_OBSERVE_METHOD_DEFINITIONS(void, id, id) +SWIZZLE_OBSERVE_METHOD_DEFINITIONS(void, id, char) +SWIZZLE_OBSERVE_METHOD_DEFINITIONS(void, id, short) +SWIZZLE_OBSERVE_METHOD_DEFINITIONS(void, id, int) +SWIZZLE_OBSERVE_METHOD_DEFINITIONS(void, id, long) +SWIZZLE_OBSERVE_METHOD_DEFINITIONS(void, id, rx_uchar) +SWIZZLE_OBSERVE_METHOD_DEFINITIONS(void, id, rx_ushort) +SWIZZLE_OBSERVE_METHOD_DEFINITIONS(void, id, rx_uint) +SWIZZLE_OBSERVE_METHOD_DEFINITIONS(void, id, rx_ulong) +SWIZZLE_OBSERVE_METHOD_DEFINITIONS(void, id, rx_block) +SWIZZLE_OBSERVE_METHOD_DEFINITIONS(void, id, float) +SWIZZLE_OBSERVE_METHOD_DEFINITIONS(void, id, double) +SWIZZLE_OBSERVE_METHOD_DEFINITIONS(void, id, SEL) + ++(void)load { + SWIZZLE_OBSERVE_METHOD_BODY(void) + + SWIZZLE_OBSERVE_METHOD_BODY(void, id) + SWIZZLE_OBSERVE_METHOD_BODY(void, char) + SWIZZLE_OBSERVE_METHOD_BODY(void, short) + SWIZZLE_OBSERVE_METHOD_BODY(void, int) + SWIZZLE_OBSERVE_METHOD_BODY(void, long) + SWIZZLE_OBSERVE_METHOD_BODY(void, rx_uchar) + SWIZZLE_OBSERVE_METHOD_BODY(void, rx_ushort) + SWIZZLE_OBSERVE_METHOD_BODY(void, rx_uint) + SWIZZLE_OBSERVE_METHOD_BODY(void, rx_ulong) + SWIZZLE_OBSERVE_METHOD_BODY(void, rx_block) + SWIZZLE_OBSERVE_METHOD_BODY(void, float) + SWIZZLE_OBSERVE_METHOD_BODY(void, double) + SWIZZLE_OBSERVE_METHOD_BODY(void, SEL) + + SWIZZLE_OBSERVE_METHOD_BODY(void, id, id) + SWIZZLE_OBSERVE_METHOD_BODY(void, id, char) + SWIZZLE_OBSERVE_METHOD_BODY(void, id, short) + SWIZZLE_OBSERVE_METHOD_BODY(void, id, int) + SWIZZLE_OBSERVE_METHOD_BODY(void, id, long) + SWIZZLE_OBSERVE_METHOD_BODY(void, id, rx_uchar) + SWIZZLE_OBSERVE_METHOD_BODY(void, id, rx_ushort) + SWIZZLE_OBSERVE_METHOD_BODY(void, id, rx_uint) + SWIZZLE_OBSERVE_METHOD_BODY(void, id, rx_ulong) + SWIZZLE_OBSERVE_METHOD_BODY(void, id, rx_block) + SWIZZLE_OBSERVE_METHOD_BODY(void, id, float) + SWIZZLE_OBSERVE_METHOD_BODY(void, id, double) + SWIZZLE_OBSERVE_METHOD_BODY(void, id, SEL) +} + +@end + +// MARK: RXObjCRuntime + +@implementation RXObjCRuntime + +static RXObjCRuntime *_instance = nil; +static NSMutableDictionary *optimizedObserversByMethodEncoding = nil; + ++(RXObjCRuntime*)instance { + return _instance; +} + ++(void)initialize { + _instance = [[RXObjCRuntime alloc] init]; + defaultTypeID = CFGetTypeID((CFTypeRef)RXObjCRuntime.class); // just need a reference of some object not from CF + deallocSelector = NSSelectorFromString(@"dealloc"); + NSAssert(_instance != nil, @"Failed to initialize swizzling"); +} + +-(instancetype)init { + self = [super init]; + if (!self) return nil; + + self.classesThatSupportObservingByForwarding = [NSMutableSet set]; + self.forwardedSelectorsByClass = [NSMutableDictionary dictionary]; + + self.dynamicSubclassByRealClass = [NSMutableDictionary dictionary]; + self.interceptorIMPbySelectorsByClass = [NSMutableDictionary dictionary]; + + pthread_mutexattr_t lock_attr; + pthread_mutexattr_init(&lock_attr); + pthread_mutexattr_settype(&lock_attr, PTHREAD_MUTEX_RECURSIVE); + pthread_mutex_init(&_lock, &lock_attr); + pthread_mutexattr_destroy(&lock_attr); + + return self; +} + +-(void)performLocked:(void (^)(RXObjCRuntime* __nonnull))action { + pthread_mutex_lock(&_lock); + action(self); + pthread_mutex_unlock(&_lock); +} + ++(void)registerOptimizedObserver:(RXInterceptWithOptimizedObserver)registration encodedAs:(SEL)selector { + Method exampleEncodingMethod = class_getClassMethod(self, selector); + ALWAYS(exampleEncodingMethod != nil, @"Example encoding method is nil."); + + NSString *methodEncoding = RX_method_encoding(exampleEncodingMethod); + + if (optimizedObserversByMethodEncoding == nil) { + optimizedObserversByMethodEncoding = [NSMutableDictionary dictionary]; + } + + DLOG(@"Added optimized method: %@ (%@)", methodEncoding, NSStringFromSelector(selector)); + ALWAYS(optimizedObserversByMethodEncoding[methodEncoding] == nil, @"Optimized observer already registered") + optimizedObserversByMethodEncoding[methodEncoding] = registration; +} + +/** + This is the main entry point for observing messages sent to arbitrary objects. + */ +-(IMP __nullable)ensurePrepared:(id __nonnull)target forObserving:(SEL __nonnull)selector error:(NSErrorParam)error { + Method instanceMethod = class_getInstanceMethod([target class], selector); + if (instanceMethod == nil) { + RX_THROW_ERROR([NSError errorWithDomain:RXObjCRuntimeErrorDomain + code:RXObjCRuntimeErrorSelectorNotImplemented + userInfo:nil], nil); + } + + if (selector == @selector(class) + || selector == @selector(forwardingTargetForSelector:) + || selector == @selector(methodSignatureForSelector:) + || selector == @selector(respondsToSelector:)) { + RX_THROW_ERROR([NSError errorWithDomain:RXObjCRuntimeErrorDomain + code:RXObjCRuntimeErrorObservingPerformanceSensitiveMessages + userInfo:nil], nil); + } + + // For `dealloc` message, original implementation will be swizzled. + // This is a special case because observing `dealloc` message is performed when `observeWeakly` is used. + // + // Some toll free bridged classes don't handle `object_setClass` well and cause crashes. + // + // To make `deallocating` as robust as possible, original implementation will be replaced. + if (selector == deallocSelector) { + Class __nonnull deallocSwizzingTarget = [target class]; + IMP interceptorIMPForSelector = [self interceptorImplementationForSelector:selector forClass:deallocSwizzingTarget]; + if (interceptorIMPForSelector != nil) { + return interceptorIMPForSelector; + } + + if (![self swizzleDeallocating:deallocSwizzingTarget error:error]) { + return nil; + } + + interceptorIMPForSelector = [self interceptorImplementationForSelector:selector forClass:deallocSwizzingTarget]; + if (interceptorIMPForSelector != nil) { + return interceptorIMPForSelector; + } + } + else { + Class __nullable swizzlingImplementorClass = [self prepareTargetClassForObserving:target error:error]; + if (swizzlingImplementorClass == nil) { + return nil; + } + + NSString *methodEncoding = RX_method_encoding(instanceMethod); + RXInterceptWithOptimizedObserver optimizedIntercept = optimizedObserversByMethodEncoding[methodEncoding]; + + if (!RX_method_has_supported_return_type(instanceMethod)) { + RX_THROW_ERROR([NSError errorWithDomain:RXObjCRuntimeErrorDomain + code:RXObjCRuntimeErrorObservingMessagesWithUnsupportedReturnType + userInfo:nil], nil); + } + + // optimized interception method + if (optimizedIntercept != nil) { + IMP interceptorIMPForSelector = [self interceptorImplementationForSelector:selector forClass:swizzlingImplementorClass]; + if (interceptorIMPForSelector != nil) { + return interceptorIMPForSelector; + } + + if (!optimizedIntercept(self, swizzlingImplementorClass, selector, error)) { + return nil; + } + + interceptorIMPForSelector = [self interceptorImplementationForSelector:selector forClass:swizzlingImplementorClass]; + if (interceptorIMPForSelector != nil) { + return interceptorIMPForSelector; + } + } + // default fallback to observing by forwarding messages + else { + if ([self forwardingSelector:selector forClass:swizzlingImplementorClass]) { + return RX_default_target_implementation(); + } + + if (![self observeByForwardingMessages:swizzlingImplementorClass + selector:selector + target:target + error:error]) { + return nil; + } + + if ([self forwardingSelector:selector forClass:swizzlingImplementorClass]) { + return RX_default_target_implementation(); + } + } + } + + RX_THROW_ERROR([NSError errorWithDomain:RXObjCRuntimeErrorDomain + code:RXObjCRuntimeErrorUnknown + userInfo:nil], nil); +} + +-(Class __nullable)prepareTargetClassForObserving:(id __nonnull)target error:(NSErrorParam)error { + Class swizzlingClass = objc_getAssociatedObject(target, &RxSwizzlingTargetClassKey); + if (swizzlingClass != nil) { + return swizzlingClass; + } + + Class __nonnull wannaBeClass = [target class]; + /** + Core Foundation classes are usually toll free bridged. Those classes crash the program in case + `object_setClass` is performed on them. + + There is a possibility to just swizzle methods on original object, but since those won't be usual use + cases for this library, then an error will just be reported for now. + */ + BOOL isThisTollFreeFoundationClass = CFGetTypeID((CFTypeRef)target) != defaultTypeID; + + if (isThisTollFreeFoundationClass) { + RX_THROW_ERROR([NSError errorWithDomain:RXObjCRuntimeErrorDomain + code:RXObjCRuntimeErrorCantInterceptCoreFoundationTollFreeBridgedObjects + userInfo:nil], nil); + } + + /** + If the object is reporting a different class then what it's real class, that means that there is probably + already some interception mechanism in place or something weird is happening. + + Most common case when this would happen is when using KVO (`observe`) and `sentMessage`. + + This error is easily resolved by just using `sentMessage` observing before `observe`. + + The reason why other way around could create issues is because KVO will unregister it's interceptor + class and restore original class. Unfortunately that will happen no matter was there another interceptor + subclass registered in hierarchy or not. + + Failure scenario: + * KVO sets class to be `__KVO__OriginalClass` (subclass of `OriginalClass`) + * `sentMessage` sets object class to be `_RX_namespace___KVO__OriginalClass` (subclass of `__KVO__OriginalClass`) + * then unobserving with KVO will restore class to be `OriginalClass` -> failure point + + The reason why changing order of observing works is because any interception method should return + object's original real class (if that doesn't happen then it's really easy to argue that's a bug + in that other library). + + This library won't remove registered interceptor even if there aren't any observers left because + it's highly unlikely it would have any benefit in real world use cases, and it's even more + dangerous. + */ + if ([target class] != object_getClass(target)) { + BOOL isKVO = [target respondsToSelector:NSSelectorFromString(@"_isKVOA")]; + + RX_THROW_ERROR([NSError errorWithDomain:RXObjCRuntimeErrorDomain + code:RXObjCRuntimeErrorObjectMessagesAlreadyBeingIntercepted + userInfo:@{ + RXObjCRuntimeErrorIsKVOKey : @(isKVO) + }], nil); + } + + Class __nullable dynamicFakeSubclass = [self ensureHasDynamicFakeSubclass:wannaBeClass error:error]; + + if (dynamicFakeSubclass == nil) { + return nil; + } + + Class previousClass = object_setClass(target, dynamicFakeSubclass); + if (previousClass != wannaBeClass) { + THREADING_HAZARD(wannaBeClass); + RX_THROW_ERROR([NSError errorWithDomain:RXObjCRuntimeErrorDomain + code:RXObjCRuntimeErrorThreadingCollisionWithOtherInterceptionMechanism + userInfo:nil], nil); + } + + objc_setAssociatedObject(target, &RxSwizzlingTargetClassKey, dynamicFakeSubclass, OBJC_ASSOCIATION_RETAIN_NONATOMIC); + return dynamicFakeSubclass; +} + + +-(BOOL)forwardingSelector:(SEL)selector forClass:(Class __nonnull)class { + return [self.forwardedSelectorsByClass[CLASS_VALUE(class)] containsObject:SEL_VALUE(selector)]; +} + +-(void)registerForwardedSelector:(SEL)selector forClass:(Class __nonnull)class { + NSValue *classValue = CLASS_VALUE(class); + + NSMutableSet *forwardedSelectors = self.forwardedSelectorsByClass[classValue]; + + if (forwardedSelectors == nil) { + forwardedSelectors = [NSMutableSet set]; + self.forwardedSelectorsByClass[classValue] = forwardedSelectors; + } + + [forwardedSelectors addObject:SEL_VALUE(selector)]; +} + +-(BOOL)observeByForwardingMessages:(Class __nonnull)swizzlingImplementorClass + selector:(SEL)selector + target:(id __nonnull)target + error:(NSErrorParam)error { + if (![self ensureForwardingMethodsAreSwizzled:swizzlingImplementorClass error:error]) { + return NO; + } + + ALWAYS(![self forwardingSelector:selector forClass:swizzlingImplementorClass], @"Already observing selector for class"); + +#if TRACE_RESOURCES + atomic_fetch_add(&numberOfForwardedMethods, 1); +#endif + SEL rxSelector = RX_selector(selector); + + Method instanceMethod = class_getInstanceMethod(swizzlingImplementorClass, selector); + ALWAYS(instanceMethod != nil, @"Instance method is nil"); + + const char* methodEncoding = method_getTypeEncoding(instanceMethod); + ALWAYS(methodEncoding != nil, @"Method encoding is nil."); + NSMethodSignature *methodSignature = [NSMethodSignature signatureWithObjCTypes:methodEncoding]; + ALWAYS(methodSignature != nil, @"Method signature is invalid."); + + IMP implementation = method_getImplementation(instanceMethod); + + if (implementation == nil) { + RX_THROW_ERROR([NSError errorWithDomain:RXObjCRuntimeErrorDomain + code:RXObjCRuntimeErrorSelectorNotImplemented + userInfo:nil], NO); + } + + if (!class_addMethod(swizzlingImplementorClass, rxSelector, implementation, methodEncoding)) { + RX_THROW_ERROR([NSError errorWithDomain:RXObjCRuntimeErrorDomain + code:RXObjCRuntimeErrorSavingOriginalForwardingMethodFailed + userInfo:nil], NO); + } + + if (!class_addMethod(swizzlingImplementorClass, selector, _objc_msgForward, methodEncoding)) { + if (implementation != method_setImplementation(instanceMethod, _objc_msgForward)) { + THREADING_HAZARD(swizzlingImplementorClass); + RX_THROW_ERROR([NSError errorWithDomain:RXObjCRuntimeErrorDomain + code:RXObjCRuntimeErrorReplacingMethodWithForwardingImplementation + userInfo:nil], NO); + } + } + + DLOG(@"Rx uses forwarding to observe `%@` for `%@`.", NSStringFromSelector(selector), swizzlingImplementorClass); + [self registerForwardedSelector:selector forClass:swizzlingImplementorClass]; + + return YES; +} + +/** + If object don't have some weird behavior, claims it's the same class that runtime shows, + then dynamic subclass is created (only this instance will have performance hit). + + In case something weird is detected, then original base class is being swizzled and all instances + will have somewhat reduced performance. + + This is especially handy optimization for weak KVO. Nobody will swizzle for example `NSString`, + but to know when instance of a `NSString` was deallocated, performance hit will be only felt on a + single instance of `NSString`, not all instances of `NSString`s. + */ +-(Class __nullable)ensureHasDynamicFakeSubclass:(Class __nonnull)class error:(NSErrorParam)error { + Class dynamicFakeSubclass = self.dynamicSubclassByRealClass[CLASS_VALUE(class)]; + if (dynamicFakeSubclass != nil) { + return dynamicFakeSubclass; + } + + NSString *dynamicFakeSubclassName = [RX_PREFIX stringByAppendingString:NSStringFromClass(class)]; + const char *dynamicFakeSubclassNameRaw = dynamicFakeSubclassName.UTF8String; + dynamicFakeSubclass = objc_allocateClassPair(class, dynamicFakeSubclassNameRaw, 0); + ALWAYS(dynamicFakeSubclass != nil, @"Class not generated"); + + if (![self swizzleClass:dynamicFakeSubclass toActAs:class error:error]) { + return nil; + } + + objc_registerClassPair(dynamicFakeSubclass); + + [self.dynamicSubclassByRealClass setObject:dynamicFakeSubclass forKey:CLASS_VALUE(class)]; + ALWAYS(self.dynamicSubclassByRealClass[CLASS_VALUE(class)] != nil, @"Class not registered"); + + return dynamicFakeSubclass; +} + +-(BOOL)ensureForwardingMethodsAreSwizzled:(Class __nonnull)class error:(NSErrorParam)error { + NSValue *classValue = CLASS_VALUE(class); + if ([self.classesThatSupportObservingByForwarding containsObject:classValue]) { + return YES; + } + + if (![self swizzleForwardInvocation:class error:error]) { return NO; } + if (![self swizzleMethodSignatureForSelector:class error:error]) { return NO; } + if (![self swizzleRespondsToSelector:class error:error]) { return NO; } + + [self.classesThatSupportObservingByForwarding addObject:classValue]; + + return YES; +} + +-(void)registerInterceptedSelector:(SEL)selector implementation:(IMP)implementation forClass:(Class)class { + NSValue * __nonnull classValue = CLASS_VALUE(class); + NSValue * __nonnull selectorValue = SEL_VALUE(selector); + + NSMutableDictionary *swizzledIMPBySelectorsForClass = self.interceptorIMPbySelectorsByClass[classValue]; + + if (swizzledIMPBySelectorsForClass == nil) { + swizzledIMPBySelectorsForClass = [NSMutableDictionary dictionary]; + self.interceptorIMPbySelectorsByClass[classValue] = swizzledIMPBySelectorsForClass; + } + + swizzledIMPBySelectorsForClass[selectorValue] = IMP_VALUE(implementation); + + ALWAYS([self interceptorImplementationForSelector:selector forClass:class] != nil, @"Class should have been swizzled"); +} + +-(IMP)interceptorImplementationForSelector:(SEL)selector forClass:(Class)class { + NSValue * __nonnull classValue = CLASS_VALUE(class); + NSValue * __nonnull selectorValue = SEL_VALUE(selector); + + NSMutableDictionary *swizzledIMPBySelectorForClass = self.interceptorIMPbySelectorsByClass[classValue]; + + NSValue *impValue = swizzledIMPBySelectorForClass[selectorValue]; + return impValue.pointerValue; +} + +-(BOOL)ensureSwizzledSelector:(SEL __nonnull)selector + ofClass:(Class __nonnull)class + newImplementationGenerator:(IMP(^)(void))newImplementationGenerator +replacementImplementationGenerator:(IMP (^)(IMP originalImplementation))replacementImplementationGenerator + error:(NSErrorParam)error { + if ([self interceptorImplementationForSelector:selector forClass:class] != nil) { + DLOG(@"Trying to register same intercept at least once, this sounds like a possible bug"); + return YES; + } + +#if TRACE_RESOURCES + atomic_fetch_add(&numberOInterceptedMethods, 1); +#endif + + DLOG(@"Rx is swizzling `%@` for `%@`", NSStringFromSelector(selector), class); + + Method existingMethod = class_getInstanceMethod(class, selector); + ALWAYS(existingMethod != nil, @"Method doesn't exist"); + + const char *encoding = method_getTypeEncoding(existingMethod); + ALWAYS(encoding != nil, @"Encoding is nil"); + + IMP newImplementation = newImplementationGenerator(); + + if (class_addMethod(class, selector, newImplementation, encoding)) { + // new method added, job done + [self registerInterceptedSelector:selector implementation:newImplementation forClass:class]; + + return YES; + } + + imp_removeBlock(newImplementation); + + // if add fails, that means that method already exists on targetClass + Method existingMethodOnTargetClass = existingMethod; + + IMP originalImplementation = method_getImplementation(existingMethodOnTargetClass); + ALWAYS(originalImplementation != nil, @"Method must exist."); + IMP implementationReplacementIMP = replacementImplementationGenerator(originalImplementation); + ALWAYS(implementationReplacementIMP != nil, @"Method must exist."); + IMP originalImplementationAfterChange = method_setImplementation(existingMethodOnTargetClass, implementationReplacementIMP); + ALWAYS(originalImplementation != nil, @"Method must exist."); + + // If method replacing failed, who knows what happened, better not trying again, otherwise program can get + // corrupted. + [self registerInterceptedSelector:selector implementation:implementationReplacementIMP forClass:class]; + + // ¯\_(ツ)_/¯ + if (originalImplementationAfterChange != originalImplementation) { + THREADING_HAZARD(class); + return NO; + } + + return YES; +} + +@end + +#if TRACE_RESOURCES + +NSInteger RX_number_of_dynamic_subclasses(void) { + __block NSInteger count = 0; + [[RXObjCRuntime instance] performLocked:^(RXObjCRuntime * __nonnull self) { + count = self.dynamicSubclassByRealClass.count; + }]; + + return count; +} + +NSInteger RX_number_of_forwarding_enabled_classes(void) { + __block NSInteger count = 0; + [[RXObjCRuntime instance] performLocked:^(RXObjCRuntime * __nonnull self) { + count = self.classesThatSupportObservingByForwarding.count; + }]; + + return count; +} + +NSInteger RX_number_of_intercepting_classes(void) { + __block NSInteger count = 0; + [[RXObjCRuntime instance] performLocked:^(RXObjCRuntime * __nonnull self) { + count = self.interceptorIMPbySelectorsByClass.count; + }]; + + return count; +} + +NSInteger RX_number_of_forwarded_methods(void) { + return numberOfForwardedMethods; +} + +NSInteger RX_number_of_swizzled_methods(void) { + return numberOInterceptedMethods; +} + +#endif + +#endif diff --git a/Pods/RxCocoa/RxCocoa/Runtime/include/RxCocoaRuntime.h b/Pods/RxCocoa/RxCocoa/Runtime/include/RxCocoaRuntime.h new file mode 100644 index 0000000..8cf762e --- /dev/null +++ b/Pods/RxCocoa/RxCocoa/Runtime/include/RxCocoaRuntime.h @@ -0,0 +1,19 @@ +// +// RxCocoaRuntime.h +// RxCocoa +// +// Created by Krunoslav Zaher on 2/21/15. +// Copyright © 2015 Krunoslav Zaher. All rights reserved. +// + +#import +#import "_RX.h" +#import "_RXDelegateProxy.h" +#import "_RXKVOObserver.h" +#import "_RXObjCRuntime.h" + +//! Project version number for RxCocoa. +FOUNDATION_EXPORT double RxCocoaVersionNumber; + +//! Project version string for RxCocoa. +FOUNDATION_EXPORT const unsigned char RxCocoaVersionString[]; diff --git a/Pods/RxCocoa/RxCocoa/Runtime/include/_RX.h b/Pods/RxCocoa/RxCocoa/Runtime/include/_RX.h new file mode 100644 index 0000000..b868ac9 --- /dev/null +++ b/Pods/RxCocoa/RxCocoa/Runtime/include/_RX.h @@ -0,0 +1,93 @@ +// +// _RX.h +// RxCocoa +// +// Created by Krunoslav Zaher on 7/12/15. +// Copyright © 2015 Krunoslav Zaher. All rights reserved. +// + +#import +#import + +/** + ################################################################################ + This file is part of RX private API + ################################################################################ + */ + +#if TRACE_RESOURCES >= 2 +# define DLOG(...) NSLog(__VA_ARGS__) +#else +# define DLOG(...) +#endif + +#if DEBUG +# define ABORT_IN_DEBUG abort(); +#else +# define ABORT_IN_DEBUG +#endif + + +#define SEL_VALUE(x) [NSValue valueWithPointer:(x)] +#define CLASS_VALUE(x) [NSValue valueWithNonretainedObject:(x)] +#define IMP_VALUE(x) [NSValue valueWithPointer:(x)] + +/** + Checks that the local `error` instance exists before assigning it's value by reference. + This macro exists to work around static analysis warnings — `NSError` is always assumed to be `nullable`, even though we explicitly define the method parameter as `nonnull`. See http://www.openradar.me/21766176 for more details. + */ +#define RX_THROW_ERROR(errorValue, returnValue) if (error != nil) { *error = (errorValue); } return (returnValue); + +#define RX_CAT2(_1, _2) _RX_CAT2(_1, _2) +#define _RX_CAT2(_1, _2) _1 ## _2 + +#define RX_ELEMENT_AT(n, ...) RX_CAT2(_RX_ELEMENT_AT_, n)(__VA_ARGS__) +#define _RX_ELEMENT_AT_0(x, ...) x +#define _RX_ELEMENT_AT_1(_0, x, ...) x +#define _RX_ELEMENT_AT_2(_0, _1, x, ...) x +#define _RX_ELEMENT_AT_3(_0, _1, _2, x, ...) x +#define _RX_ELEMENT_AT_4(_0, _1, _2, _3, x, ...) x +#define _RX_ELEMENT_AT_5(_0, _1, _2, _3, _4, x, ...) x +#define _RX_ELEMENT_AT_6(_0, _1, _2, _3, _4, _5, x, ...) x + +#define RX_COUNT(...) RX_ELEMENT_AT(6, ## __VA_ARGS__, 6, 5, 4, 3, 2, 1, 0) +#define RX_EMPTY(...) RX_ELEMENT_AT(6, ## __VA_ARGS__, 0, 0, 0, 0, 0, 0, 1) + +/** + #define SUM(context, index, head, tail) head + tail + #define MAP(context, index, element) (context)[index] * (element) + + RX_FOR(numbers, SUM, MAP, b0, b1, b2); + + (numbers)[0] * (b0) + (numbers)[1] * (b1) + (numbers[2]) * (b2) + */ + +#define RX_FOREACH(context, concat, map, ...) RX_FOR_MAX(RX_COUNT(__VA_ARGS__), _RX_FOREACH_CONCAT, _RX_FOREACH_MAP, context, concat, map, __VA_ARGS__) +#define _RX_FOREACH_CONCAT(index, head, tail, context, concat, map, ...) concat(context, index, head, tail) +#define _RX_FOREACH_MAP(index, context, concat, map, ...) map(context, index, RX_ELEMENT_AT(index, __VA_ARGS__)) + +/** + #define MAP(context, index, item) (context)[index] * (item) + + RX_FOR_COMMA(numbers, MAP, b0, b1); + + ,(numbers)[0] * b0, (numbers)[1] * b1 + */ +#define RX_FOREACH_COMMA(context, map, ...) RX_CAT2(_RX_FOREACH_COMMA_EMPTY_, RX_EMPTY(__VA_ARGS__))(context, map, ## __VA_ARGS__) +#define _RX_FOREACH_COMMA_EMPTY_1(context, map, ...) +#define _RX_FOREACH_COMMA_EMPTY_0(context, map, ...) , RX_FOR_MAX(RX_COUNT(__VA_ARGS__), _RX_FOREACH_COMMA_CONCAT, _RX_FOREACH_COMMA_MAP, context, map, __VA_ARGS__) +#define _RX_FOREACH_COMMA_CONCAT(index, head, tail, context, map, ...) head, tail +#define _RX_FOREACH_COMMA_MAP(index, context, map, ...) map(context, index, RX_ELEMENT_AT(index, __VA_ARGS__)) + +// rx for + +#define RX_FOR_MAX(max, concat, map, ...) RX_CAT2(RX_FOR_, max)(concat, map, ## __VA_ARGS__) + +#define RX_FOR_0(concat, map, ...) +#define RX_FOR_1(concat, map, ...) map(0, __VA_ARGS__) +#define RX_FOR_2(concat, map, ...) concat(1, RX_FOR_1(concat, map, ## __VA_ARGS__), map(1, __VA_ARGS__), __VA_ARGS__) +#define RX_FOR_3(concat, map, ...) concat(2, RX_FOR_2(concat, map, ## __VA_ARGS__), map(2, __VA_ARGS__), __VA_ARGS__) +#define RX_FOR_4(concat, map, ...) concat(3, RX_FOR_3(concat, map, ## __VA_ARGS__), map(3, __VA_ARGS__), __VA_ARGS__) +#define RX_FOR_5(concat, map, ...) concat(4, RX_FOR_4(concat, map, ## __VA_ARGS__), map(4, __VA_ARGS__), __VA_ARGS__) +#define RX_FOR_6(concat, map, ...) concat(5, RX_FOR_5(concat, map, ## __VA_ARGS__), map(5, __VA_ARGS__), __VA_ARGS__) + diff --git a/Pods/RxCocoa/RxCocoa/Runtime/include/_RXDelegateProxy.h b/Pods/RxCocoa/RxCocoa/Runtime/include/_RXDelegateProxy.h new file mode 100644 index 0000000..e1cc207 --- /dev/null +++ b/Pods/RxCocoa/RxCocoa/Runtime/include/_RXDelegateProxy.h @@ -0,0 +1,27 @@ +// +// _RXDelegateProxy.h +// RxCocoa +// +// Created by Krunoslav Zaher on 7/4/15. +// Copyright © 2015 Krunoslav Zaher. All rights reserved. +// + +#import + +NS_ASSUME_NONNULL_BEGIN + +@interface _RXDelegateProxy : NSObject + +@property (nonatomic, weak, readonly) id _forwardToDelegate; + +-(void)_setForwardToDelegate:(id __nullable)forwardToDelegate retainDelegate:(BOOL)retainDelegate NS_SWIFT_NAME(_setForwardToDelegate(_:retainDelegate:)) ; + +-(BOOL)hasWiredImplementationForSelector:(SEL)selector; +-(BOOL)voidDelegateMethodsContain:(SEL)selector; + +-(void)_sentMessage:(SEL)selector withArguments:(NSArray*)arguments; +-(void)_methodInvoked:(SEL)selector withArguments:(NSArray*)arguments; + +@end + +NS_ASSUME_NONNULL_END diff --git a/Pods/RxCocoa/RxCocoa/Runtime/include/_RXKVOObserver.h b/Pods/RxCocoa/RxCocoa/Runtime/include/_RXKVOObserver.h new file mode 100644 index 0000000..adcfd0a --- /dev/null +++ b/Pods/RxCocoa/RxCocoa/Runtime/include/_RXKVOObserver.h @@ -0,0 +1,28 @@ +// +// _RXKVOObserver.h +// RxCocoa +// +// Created by Krunoslav Zaher on 7/11/15. +// Copyright © 2015 Krunoslav Zaher. All rights reserved. +// + +#import + +/** + ################################################################################ + This file is part of RX private API + ################################################################################ + */ + +// Exists because if written in Swift, reading unowned is disabled during dealloc process +@interface _RXKVOObserver : NSObject + +-(instancetype)initWithTarget:(id)target + retainTarget:(BOOL)retainTarget + keyPath:(NSString*)keyPath + options:(NSKeyValueObservingOptions)options + callback:(void (^)(id))callback; + +-(void)dispose; + +@end diff --git a/Pods/RxCocoa/RxCocoa/Runtime/include/_RXObjCRuntime.h b/Pods/RxCocoa/RxCocoa/Runtime/include/_RXObjCRuntime.h new file mode 100644 index 0000000..bc6a76a --- /dev/null +++ b/Pods/RxCocoa/RxCocoa/Runtime/include/_RXObjCRuntime.h @@ -0,0 +1,102 @@ +// +// _RXObjCRuntime.h +// RxCocoa +// +// Created by Krunoslav Zaher on 7/11/15. +// Copyright © 2015 Krunoslav Zaher. All rights reserved. +// + +#import + +#if !DISABLE_SWIZZLING + +/** + ################################################################################ + This file is part of RX private API + ################################################################################ + */ + +/** + This flag controls `RELEASE` configuration behavior in case race was detecting while modifying + ObjC runtime. + + In case this value is set to `YES`, after runtime race is detected, `abort()` will be called. + Otherwise, only error will be reported using normal error reporting mechanism. + + In `DEBUG` mode `abort` will be always called in case race is detected. + + Races can't happen in case this is the only library modifying ObjC runtime, but in case there are multiple libraries + changing ObjC runtime, race conditions can occur because there is no way to synchronize multiple libraries unaware of + each other. + + To help remedy this situation this library will use `synchronized` on target object and it's meta-class, but + there aren't any guarantees of how other libraries will behave. + + Default value is `NO`. + + */ +extern BOOL RXAbortOnThreadingHazard; + +/// Error domain for RXObjCRuntime. +extern NSString * __nonnull const RXObjCRuntimeErrorDomain; + +/// `userInfo` key with additional information is interceptor probably KVO. +extern NSString * __nonnull const RXObjCRuntimeErrorIsKVOKey; + +typedef NS_ENUM(NSInteger, RXObjCRuntimeError) { + RXObjCRuntimeErrorUnknown = 1, + RXObjCRuntimeErrorObjectMessagesAlreadyBeingIntercepted = 2, + RXObjCRuntimeErrorSelectorNotImplemented = 3, + RXObjCRuntimeErrorCantInterceptCoreFoundationTollFreeBridgedObjects = 4, + RXObjCRuntimeErrorThreadingCollisionWithOtherInterceptionMechanism = 5, + RXObjCRuntimeErrorSavingOriginalForwardingMethodFailed = 6, + RXObjCRuntimeErrorReplacingMethodWithForwardingImplementation = 7, + RXObjCRuntimeErrorObservingPerformanceSensitiveMessages = 8, + RXObjCRuntimeErrorObservingMessagesWithUnsupportedReturnType = 9, +}; + +/// Transforms normal selector into a selector with RX prefix. +SEL _Nonnull RX_selector(SEL _Nonnull selector); + +/// Transforms selector into a unique pointer (because of Swift conversion rules) +void * __nonnull RX_reference_from_selector(SEL __nonnull selector); + +/// Protocol that interception observers must implement. +@protocol RXMessageSentObserver + +/// In case the same selector is being intercepted for a pair of base/sub classes, +/// this property will differentiate between interceptors that need to fire. +@property (nonatomic, assign, readonly) IMP __nonnull targetImplementation; + +-(void)messageSentWithArguments:(NSArray* __nonnull)arguments; +-(void)methodInvokedWithArguments:(NSArray* __nonnull)arguments; + +@end + +/// Protocol that deallocating observer must implement. +@protocol RXDeallocatingObserver + +/// In case the same selector is being intercepted for a pair of base/sub classes, +/// this property will differentiate between interceptors that need to fire. +@property (nonatomic, assign, readonly) IMP __nonnull targetImplementation; + +-(void)deallocating; + +@end + +/// Ensures interceptor is installed on target object. +IMP __nullable RX_ensure_observing(id __nonnull target, SEL __nonnull selector, NSError *__autoreleasing __nullable * __nullable error); + +#endif + +/// Extracts arguments for `invocation`. +NSArray * __nonnull RX_extract_arguments(NSInvocation * __nonnull invocation); + +/// Returns `YES` in case method has `void` return type. +BOOL RX_is_method_with_description_void(struct objc_method_description method); + +/// Returns `YES` in case methodSignature has `void` return type. +BOOL RX_is_method_signature_void(NSMethodSignature * __nonnull methodSignature); + +/// Default value for `RXInterceptionObserver.targetImplementation`. +IMP __nonnull RX_default_target_implementation(void); diff --git a/Pods/RxCocoa/RxCocoa/RxCocoa.h b/Pods/RxCocoa/RxCocoa/RxCocoa.h new file mode 100644 index 0000000..0bca1bc --- /dev/null +++ b/Pods/RxCocoa/RxCocoa/RxCocoa.h @@ -0,0 +1,19 @@ +// +// RxCocoa.h +// RxCocoa +// +// Created by Krunoslav Zaher on 2/21/15. +// Copyright © 2015 Krunoslav Zaher. All rights reserved. +// + +#import +#import +#import +#import +#import + +//! Project version number for RxCocoa. +FOUNDATION_EXPORT double RxCocoaVersionNumber; + +//! Project version string for RxCocoa. +FOUNDATION_EXPORT const unsigned char RxCocoaVersionString[]; diff --git a/Pods/RxCocoa/RxCocoa/RxCocoa.swift b/Pods/RxCocoa/RxCocoa/RxCocoa.swift new file mode 100644 index 0000000..5e569fc --- /dev/null +++ b/Pods/RxCocoa/RxCocoa/RxCocoa.swift @@ -0,0 +1,155 @@ +// +// RxCocoa.swift +// RxCocoa +// +// Created by Krunoslav Zaher on 2/21/15. +// Copyright © 2015 Krunoslav Zaher. All rights reserved. +// + +import Foundation + +// Importing RxCocoa also imports RxRelay +@_exported import RxRelay + +import RxSwift +#if os(iOS) + import UIKit +#endif + +/// RxCocoa errors. +public enum RxCocoaError + : Swift.Error + , CustomDebugStringConvertible { + /// Unknown error has occurred. + case unknown + /// Invalid operation was attempted. + case invalidOperation(object: Any) + /// Items are not yet bound to user interface but have been requested. + case itemsNotYetBound(object: Any) + /// Invalid KVO Path. + case invalidPropertyName(object: Any, propertyName: String) + /// Invalid object on key path. + case invalidObjectOnKeyPath(object: Any, sourceObject: AnyObject, propertyName: String) + /// Error during swizzling. + case errorDuringSwizzling + /// Casting error. + case castingError(object: Any, targetType: Any.Type) +} + + +// MARK: Debug descriptions + +extension RxCocoaError { + /// A textual representation of `self`, suitable for debugging. + public var debugDescription: String { + switch self { + case .unknown: + return "Unknown error occurred." + case let .invalidOperation(object): + return "Invalid operation was attempted on `\(object)`." + case let .itemsNotYetBound(object): + return "Data source is set, but items are not yet bound to user interface for `\(object)`." + case let .invalidPropertyName(object, propertyName): + return "Object `\(object)` doesn't have a property named `\(propertyName)`." + case let .invalidObjectOnKeyPath(object, sourceObject, propertyName): + return "Unobservable object `\(object)` was observed as `\(propertyName)` of `\(sourceObject)`." + case .errorDuringSwizzling: + return "Error during swizzling." + case let .castingError(object, targetType): + return "Error casting `\(object)` to `\(targetType)`" + } + } +} + + + +// MARK: Error binding policies + +func bindingError(_ error: Swift.Error) { + let error = "Binding error: \(error)" +#if DEBUG + rxFatalError(error) +#else + print(error) +#endif +} + +/// Swift does not implement abstract methods. This method is used as a runtime check to ensure that methods which intended to be abstract (i.e., they should be implemented in subclasses) are not called directly on the superclass. +func rxAbstractMethod(message: String = "Abstract method", file: StaticString = #file, line: UInt = #line) -> Swift.Never { + rxFatalError(message, file: file, line: line) +} + +func rxFatalError(_ lastMessage: @autoclosure () -> String, file: StaticString = #file, line: UInt = #line) -> Swift.Never { + // The temptation to comment this line is great, but please don't, it's for your own good. The choice is yours. + fatalError(lastMessage(), file: file, line: line) +} + +func rxFatalErrorInDebug(_ lastMessage: @autoclosure () -> String, file: StaticString = #file, line: UInt = #line) { + #if DEBUG + fatalError(lastMessage(), file: file, line: line) + #else + print("\(file):\(line): \(lastMessage())") + #endif +} + +// MARK: casts or fatal error + +// workaround for Swift compiler bug, cheers compiler team :) +func castOptionalOrFatalError(_ value: Any?) -> T? { + if value == nil { + return nil + } + let v: T = castOrFatalError(value) + return v +} + +func castOrThrow(_ resultType: T.Type, _ object: Any) throws -> T { + guard let returnValue = object as? T else { + throw RxCocoaError.castingError(object: object, targetType: resultType) + } + + return returnValue +} + +func castOptionalOrThrow(_ resultType: T.Type, _ object: AnyObject) throws -> T? { + if NSNull().isEqual(object) { + return nil + } + + guard let returnValue = object as? T else { + throw RxCocoaError.castingError(object: object, targetType: resultType) + } + + return returnValue +} + +func castOrFatalError(_ value: AnyObject!, message: String) -> T { + let maybeResult: T? = value as? T + guard let result = maybeResult else { + rxFatalError(message) + } + + return result +} + +func castOrFatalError(_ value: Any!) -> T { + let maybeResult: T? = value as? T + guard let result = maybeResult else { + rxFatalError("Failure converting from \(String(describing: value)) to \(T.self)") + } + + return result +} + +// MARK: Error messages + +let dataSourceNotSet = "DataSource not set" +let delegateNotSet = "Delegate not set" + +// MARK: Shared with RxSwift + +func rxFatalError(_ lastMessage: String) -> Never { + // The temptation to comment this line is great, but please don't, it's for your own good. The choice is yours. + fatalError(lastMessage) +} + diff --git a/Pods/RxCocoa/RxCocoa/Traits/ControlEvent.swift b/Pods/RxCocoa/RxCocoa/Traits/ControlEvent.swift new file mode 100644 index 0000000..bea1d83 --- /dev/null +++ b/Pods/RxCocoa/RxCocoa/Traits/ControlEvent.swift @@ -0,0 +1,68 @@ +// +// ControlEvent.swift +// RxCocoa +// +// Created by Krunoslav Zaher on 8/28/15. +// Copyright © 2015 Krunoslav Zaher. All rights reserved. +// + +import RxSwift + +/// A protocol that extends `ControlEvent`. +public protocol ControlEventType : ObservableType { + + /// - returns: `ControlEvent` interface + func asControlEvent() -> ControlEvent +} + +/** + A trait for `Observable`/`ObservableType` that represents an event on a UI element. + + Properties: + + - it doesn’t send any initial value on subscription, + - it `Complete`s the sequence when the control deallocates, + - it never errors out + - it delivers events on `MainScheduler.instance`. + + **The implementation of `ControlEvent` will ensure that sequence of events is being subscribed on main scheduler + (`subscribe(on: ConcurrentMainScheduler.instance)` behavior).** + + **It is the implementor’s responsibility to make sure that all other properties enumerated above are satisfied.** + + **If they aren’t, using this trait will communicate wrong properties, and could potentially break someone’s code.** + + **If the `events` observable sequence passed into the initializer doesn’t satisfy all enumerated + properties, don’t use this trait.** +*/ +public struct ControlEvent : ControlEventType { + public typealias Element = PropertyType + + let events: Observable + + /// Initializes control event with a observable sequence that represents events. + /// + /// - parameter events: Observable sequence that represents events. + /// - returns: Control event created with a observable sequence of events. + public init(events: Ev) where Ev.Element == Element { + self.events = events.subscribe(on: ConcurrentMainScheduler.instance) + } + + /// Subscribes an observer to control events. + /// + /// - parameter observer: Observer to subscribe to events. + /// - returns: Disposable object that can be used to unsubscribe the observer from receiving control events. + public func subscribe(_ observer: Observer) -> Disposable where Observer.Element == Element { + self.events.subscribe(observer) + } + + /// - returns: `Observable` interface. + public func asObservable() -> Observable { + self.events + } + + /// - returns: `ControlEvent` interface. + public func asControlEvent() -> ControlEvent { + self + } +} diff --git a/Pods/RxCocoa/RxCocoa/Traits/ControlProperty.swift b/Pods/RxCocoa/RxCocoa/Traits/ControlProperty.swift new file mode 100644 index 0000000..5ff48ca --- /dev/null +++ b/Pods/RxCocoa/RxCocoa/Traits/ControlProperty.swift @@ -0,0 +1,118 @@ +// +// ControlProperty.swift +// RxCocoa +// +// Created by Krunoslav Zaher on 8/28/15. +// Copyright © 2015 Krunoslav Zaher. All rights reserved. +// + +import RxSwift + +/// Protocol that enables extension of `ControlProperty`. +public protocol ControlPropertyType : ObservableType, ObserverType { + + /// - returns: `ControlProperty` interface + func asControlProperty() -> ControlProperty +} + +/** + Trait for `Observable`/`ObservableType` that represents property of UI element. + + Sequence of values only represents initial control value and user initiated value changes. + Programmatic value changes won't be reported. + + It's properties are: + + - `shareReplay(1)` behavior + - it's stateful, upon subscription (calling subscribe) last element is immediately replayed if it was produced + - it will `Complete` sequence on control being deallocated + - it never errors out + - it delivers events on `MainScheduler.instance` + + **The implementation of `ControlProperty` will ensure that sequence of values is being subscribed on main scheduler + (`subscribe(on: ConcurrentMainScheduler.instance)` behavior).** + + **It is implementor's responsibility to make sure that that all other properties enumerated above are satisfied.** + + **If they aren't, then using this trait communicates wrong properties and could potentially break someone's code.** + + **In case `values` observable sequence that is being passed into initializer doesn't satisfy all enumerated + properties, please don't use this trait.** +*/ +public struct ControlProperty : ControlPropertyType { + public typealias Element = PropertyType + + let values: Observable + let valueSink: AnyObserver + + /// Initializes control property with a observable sequence that represents property values and observer that enables + /// binding values to property. + /// + /// - parameter values: Observable sequence that represents property values. + /// - parameter valueSink: Observer that enables binding values to control property. + /// - returns: Control property created with a observable sequence of values and an observer that enables binding values + /// to property. + public init(values: Values, valueSink: Sink) where Element == Values.Element, Element == Sink.Element { + self.values = values.subscribe(on: ConcurrentMainScheduler.instance) + self.valueSink = valueSink.asObserver() + } + + /// Subscribes an observer to control property values. + /// + /// - parameter observer: Observer to subscribe to property values. + /// - returns: Disposable object that can be used to unsubscribe the observer from receiving control property values. + public func subscribe(_ observer: Observer) -> Disposable where Observer.Element == Element { + self.values.subscribe(observer) + } + + /// `ControlEvent` of user initiated value changes. Every time user updates control value change event + /// will be emitted from `changed` event. + /// + /// Programmatic changes to control value won't be reported. + /// + /// It contains all control property values except for first one. + /// + /// The name only implies that sequence element will be generated once user changes a value and not that + /// adjacent sequence values need to be different (e.g. because of interaction between programmatic and user updates, + /// or for any other reason). + public var changed: ControlEvent { + ControlEvent(events: self.values.skip(1)) + } + + /// - returns: `Observable` interface. + public func asObservable() -> Observable { + self.values + } + + /// - returns: `ControlProperty` interface. + public func asControlProperty() -> ControlProperty { + self + } + + /// Binds event to user interface. + /// + /// - In case next element is received, it is being set to control value. + /// - In case error is received, DEBUG builds raise fatal error, RELEASE builds log event to standard output. + /// - In case sequence completes, nothing happens. + public func on(_ event: Event) { + switch event { + case .error(let error): + bindingError(error) + case .next: + self.valueSink.on(event) + case .completed: + self.valueSink.on(event) + } + } +} + +extension ControlPropertyType where Element == String? { + /// Transforms control property of type `String?` into control property of type `String`. + public var orEmpty: ControlProperty { + let original: ControlProperty = self.asControlProperty() + + let values: Observable = original.values.map { $0 ?? "" } + let valueSink: AnyObserver = original.valueSink.mapObserver { $0 } + return ControlProperty(values: values, valueSink: valueSink) + } +} diff --git a/Pods/RxCocoa/RxCocoa/Traits/Driver/BehaviorRelay+Driver.swift b/Pods/RxCocoa/RxCocoa/Traits/Driver/BehaviorRelay+Driver.swift new file mode 100644 index 0000000..76d960f --- /dev/null +++ b/Pods/RxCocoa/RxCocoa/Traits/Driver/BehaviorRelay+Driver.swift @@ -0,0 +1,21 @@ +// +// BehaviorRelay+Driver.swift +// RxCocoa +// +// Created by Krunoslav Zaher on 10/7/17. +// Copyright © 2017 Krunoslav Zaher. All rights reserved. +// + +import RxSwift +import RxRelay + +extension BehaviorRelay { + /// Converts `BehaviorRelay` to `Driver`. + /// + /// - returns: Observable sequence. + public func asDriver() -> Driver { + let source = self.asObservable() + .observe(on:DriverSharingStrategy.scheduler) + return SharedSequence(source) + } +} diff --git a/Pods/RxCocoa/RxCocoa/Traits/Driver/ControlEvent+Driver.swift b/Pods/RxCocoa/RxCocoa/Traits/Driver/ControlEvent+Driver.swift new file mode 100644 index 0000000..b59c753 --- /dev/null +++ b/Pods/RxCocoa/RxCocoa/Traits/Driver/ControlEvent+Driver.swift @@ -0,0 +1,24 @@ +// +// ControlEvent+Driver.swift +// RxCocoa +// +// Created by Krunoslav Zaher on 9/19/15. +// Copyright © 2015 Krunoslav Zaher. All rights reserved. +// + +import RxSwift + +extension ControlEvent { + /// Converts `ControlEvent` to `Driver` trait. + /// + /// `ControlEvent` already can't fail, so no special case needs to be handled. + public func asDriver() -> Driver { + return self.asDriver { _ -> Driver in + #if DEBUG + rxFatalError("Somehow driver received error from a source that shouldn't fail.") + #else + return Driver.empty() + #endif + } + } +} diff --git a/Pods/RxCocoa/RxCocoa/Traits/Driver/ControlProperty+Driver.swift b/Pods/RxCocoa/RxCocoa/Traits/Driver/ControlProperty+Driver.swift new file mode 100644 index 0000000..7904529 --- /dev/null +++ b/Pods/RxCocoa/RxCocoa/Traits/Driver/ControlProperty+Driver.swift @@ -0,0 +1,24 @@ +// +// ControlProperty+Driver.swift +// RxCocoa +// +// Created by Krunoslav Zaher on 9/19/15. +// Copyright © 2015 Krunoslav Zaher. All rights reserved. +// + +import RxSwift + +extension ControlProperty { + /// Converts `ControlProperty` to `Driver` trait. + /// + /// `ControlProperty` already can't fail, so no special case needs to be handled. + public func asDriver() -> Driver { + return self.asDriver { _ -> Driver in + #if DEBUG + rxFatalError("Somehow driver received error from a source that shouldn't fail.") + #else + return Driver.empty() + #endif + } + } +} diff --git a/Pods/RxCocoa/RxCocoa/Traits/Driver/Driver+Subscription.swift b/Pods/RxCocoa/RxCocoa/Traits/Driver/Driver+Subscription.swift new file mode 100644 index 0000000..0b9024c --- /dev/null +++ b/Pods/RxCocoa/RxCocoa/Traits/Driver/Driver+Subscription.swift @@ -0,0 +1,203 @@ +// +// Driver+Subscription.swift +// RxCocoa +// +// Created by Krunoslav Zaher on 9/19/15. +// Copyright © 2015 Krunoslav Zaher. All rights reserved. +// + +import RxSwift +import RxRelay + +private let errorMessage = "`drive*` family of methods can be only called from `MainThread`.\n" + +"This is required to ensure that the last replayed `Driver` element is delivered on `MainThread`.\n" + +extension SharedSequenceConvertibleType where SharingStrategy == DriverSharingStrategy { + /** + Creates new subscription and sends elements to observer. + This method can be only called from `MainThread`. + + In this form it's equivalent to `subscribe` method, but it communicates intent better. + + - parameter observers: Observers that receives events. + - returns: Disposable object that can be used to unsubscribe the observer from the subject. + */ + public func drive(_ observers: Observer...) -> Disposable where Observer.Element == Element { + MainScheduler.ensureRunningOnMainThread(errorMessage: errorMessage) + return self.asSharedSequence() + .asObservable() + .subscribe { e in + observers.forEach { $0.on(e) } + } + } + + /** + Creates new subscription and sends elements to observer. + This method can be only called from `MainThread`. + + In this form it's equivalent to `subscribe` method, but it communicates intent better. + + - parameter observers: Observers that receives events. + - returns: Disposable object that can be used to unsubscribe the observer from the subject. + */ + public func drive(_ observers: Observer...) -> Disposable where Observer.Element == Element? { + MainScheduler.ensureRunningOnMainThread(errorMessage: errorMessage) + return self.asSharedSequence() + .asObservable() + .map { $0 as Element? } + .subscribe { e in + observers.forEach { $0.on(e) } + } + } + + /** + Creates new subscription and sends elements to `BehaviorRelay`. + This method can be only called from `MainThread`. + + - parameter relays: Target relays for sequence elements. + - returns: Disposable object that can be used to unsubscribe the observer from the relay. + */ + public func drive(_ relays: BehaviorRelay...) -> Disposable { + MainScheduler.ensureRunningOnMainThread(errorMessage: errorMessage) + return self.drive(onNext: { e in + relays.forEach { $0.accept(e) } + }) + } + + /** + Creates new subscription and sends elements to `BehaviorRelay`. + This method can be only called from `MainThread`. + + - parameter relays: Target relays for sequence elements. + - returns: Disposable object that can be used to unsubscribe the observer from the relay. + */ + public func drive(_ relays: BehaviorRelay...) -> Disposable { + MainScheduler.ensureRunningOnMainThread(errorMessage: errorMessage) + return self.drive(onNext: { e in + relays.forEach { $0.accept(e) } + }) + } + + /** + Creates new subscription and sends elements to `ReplayRelay`. + This method can be only called from `MainThread`. + + - parameter relays: Target relays for sequence elements. + - returns: Disposable object that can be used to unsubscribe the observer from the relay. + */ + public func drive(_ relays: ReplayRelay...) -> Disposable { + MainScheduler.ensureRunningOnMainThread(errorMessage: errorMessage) + return self.drive(onNext: { e in + relays.forEach { $0.accept(e) } + }) + } + + /** + Creates new subscription and sends elements to `ReplayRelay`. + This method can be only called from `MainThread`. + + - parameter relays: Target relays for sequence elements. + - returns: Disposable object that can be used to unsubscribe the observer from the relay. + */ + public func drive(_ relays: ReplayRelay...) -> Disposable { + MainScheduler.ensureRunningOnMainThread(errorMessage: errorMessage) + return self.drive(onNext: { e in + relays.forEach { $0.accept(e) } + }) + } + + /** + Subscribes to observable sequence using custom binder function. + This method can be only called from `MainThread`. + + - parameter transformation: Function used to bind elements from `self`. + - returns: Object representing subscription. + */ + public func drive(_ transformation: (Observable) -> Result) -> Result { + MainScheduler.ensureRunningOnMainThread(errorMessage: errorMessage) + return transformation(self.asObservable()) + } + + /** + Subscribes to observable sequence using custom binder function and final parameter passed to binder function + after `self` is passed. + + public func drive(with: Self -> R1 -> R2, curriedArgument: R1) -> R2 { + return with(self)(curriedArgument) + } + + This method can be only called from `MainThread`. + + - parameter with: Function used to bind elements from `self`. + - parameter curriedArgument: Final argument passed to `binder` to finish binding process. + - returns: Object representing subscription. + */ + public func drive(_ with: (Observable) -> (R1) -> R2, curriedArgument: R1) -> R2 { + MainScheduler.ensureRunningOnMainThread(errorMessage: errorMessage) + return with(self.asObservable())(curriedArgument) + } + + /** + Subscribes an element handler, a completion handler and disposed handler to an observable sequence. + This method can be only called from `MainThread`. + + Also, take in an object and provide an unretained, safe to use (i.e. not implicitly unwrapped), reference to it along with the events emitted by the sequence. + + Error callback is not exposed because `Driver` can't error out. + + - Note: If `object` can't be retained, none of the other closures will be invoked. + + - parameter object: The object to provide an unretained reference on. + - parameter onNext: Action to invoke for each element in the observable sequence. + - parameter onCompleted: Action to invoke upon graceful termination of the observable sequence. + gracefully completed, errored, or if the generation is canceled by disposing subscription) + - parameter onDisposed: Action to invoke upon any type of termination of sequence (if the sequence has + gracefully completed, errored, or if the generation is canceled by disposing subscription) + - returns: Subscription object used to unsubscribe from the observable sequence. + */ + public func drive( + with object: Object, + onNext: ((Object, Element) -> Void)? = nil, + onCompleted: ((Object) -> Void)? = nil, + onDisposed: ((Object) -> Void)? = nil + ) -> Disposable { + MainScheduler.ensureRunningOnMainThread(errorMessage: errorMessage) + return self.asObservable().subscribe(with: object, onNext: onNext, onCompleted: onCompleted, onDisposed: onDisposed) + } + + /** + Subscribes an element handler, a completion handler and disposed handler to an observable sequence. + This method can be only called from `MainThread`. + + Error callback is not exposed because `Driver` can't error out. + + - parameter onNext: Action to invoke for each element in the observable sequence. + - parameter onCompleted: Action to invoke upon graceful termination of the observable sequence. + gracefully completed, errored, or if the generation is canceled by disposing subscription) + - parameter onDisposed: Action to invoke upon any type of termination of sequence (if the sequence has + gracefully completed, errored, or if the generation is canceled by disposing subscription) + - returns: Subscription object used to unsubscribe from the observable sequence. + */ + public func drive( + onNext: ((Element) -> Void)? = nil, + onCompleted: (() -> Void)? = nil, + onDisposed: (() -> Void)? = nil + ) -> Disposable { + MainScheduler.ensureRunningOnMainThread(errorMessage: errorMessage) + return self.asObservable().subscribe(onNext: onNext, onCompleted: onCompleted, onDisposed: onDisposed) + } + + /** + Subscribes to this `Driver` with a no-op. + This method can be only called from `MainThread`. + + - note: This is an alias of `drive(onNext: nil, onCompleted: nil, onDisposed: nil)` used to fix an ambiguity bug in Swift: https://bugs.swift.org/browse/SR-13657 + + - returns: Subscription object used to unsubscribe from the observable sequence. + */ + public func drive() -> Disposable { + drive(onNext: nil, onCompleted: nil, onDisposed: nil) + } +} + + diff --git a/Pods/RxCocoa/RxCocoa/Traits/Driver/Driver.swift b/Pods/RxCocoa/RxCocoa/Traits/Driver/Driver.swift new file mode 100644 index 0000000..5de8b3a --- /dev/null +++ b/Pods/RxCocoa/RxCocoa/Traits/Driver/Driver.swift @@ -0,0 +1,53 @@ +// +// Driver.swift +// RxCocoa +// +// Created by Krunoslav Zaher on 9/26/16. +// Copyright © 2016 Krunoslav Zaher. All rights reserved. +// + +import RxSwift + +/** + Trait that represents observable sequence with following properties: + + - it never fails + - it delivers events on `MainScheduler.instance` + - `share(replay: 1, scope: .whileConnected)` sharing strategy + + Additional explanation: + - all observers share sequence computation resources + - it's stateful, upon subscription (calling subscribe) last element is immediately replayed if it was produced + - computation of elements is reference counted with respect to the number of observers + - if there are no subscribers, it will release sequence computation resources + + In case trait that models event bus is required, please check `Signal`. + + `Driver` can be considered a builder pattern for observable sequences that drive the application. + + If observable sequence has produced at least one element, after new subscription is made last produced element will be + immediately replayed on the same thread on which the subscription was made. + + When using `drive*`, `subscribe*` and `bind*` family of methods, they should always be called from main thread. + + If `drive*`, `subscribe*` and `bind*` are called from background thread, it is possible that initial replay + will happen on background thread, and subsequent events will arrive on main thread. + + To find out more about traits and how to use them, please visit `Documentation/Traits.md`. + */ +public typealias Driver = SharedSequence + +public struct DriverSharingStrategy: SharingStrategyProtocol { + public static var scheduler: SchedulerType { SharingScheduler.make() } + public static func share(_ source: Observable) -> Observable { + source.share(replay: 1, scope: .whileConnected) + } +} + +extension SharedSequenceConvertibleType where SharingStrategy == DriverSharingStrategy { + /// Adds `asDriver` to `SharingSequence` with `DriverSharingStrategy`. + public func asDriver() -> Driver { + self.asSharedSequence() + } +} + diff --git a/Pods/RxCocoa/RxCocoa/Traits/Driver/ObservableConvertibleType+Driver.swift b/Pods/RxCocoa/RxCocoa/Traits/Driver/ObservableConvertibleType+Driver.swift new file mode 100644 index 0000000..bcac66b --- /dev/null +++ b/Pods/RxCocoa/RxCocoa/Traits/Driver/ObservableConvertibleType+Driver.swift @@ -0,0 +1,57 @@ +// +// ObservableConvertibleType+Driver.swift +// RxCocoa +// +// Created by Krunoslav Zaher on 9/19/15. +// Copyright © 2015 Krunoslav Zaher. All rights reserved. +// + +import RxSwift + +extension ObservableConvertibleType { + /** + Converts observable sequence to `Driver` trait. + + - parameter onErrorJustReturn: Element to return in case of error and after that complete the sequence. + - returns: Driver trait. + */ + public func asDriver(onErrorJustReturn: Element) -> Driver { + let source = self + .asObservable() + .observe(on:DriverSharingStrategy.scheduler) + .catchAndReturn(onErrorJustReturn) + return Driver(source) + } + + /** + Converts observable sequence to `Driver` trait. + + - parameter onErrorDriveWith: Driver that continues to drive the sequence in case of error. + - returns: Driver trait. + */ + public func asDriver(onErrorDriveWith: Driver) -> Driver { + let source = self + .asObservable() + .observe(on:DriverSharingStrategy.scheduler) + .catch { _ in + onErrorDriveWith.asObservable() + } + return Driver(source) + } + + /** + Converts observable sequence to `Driver` trait. + + - parameter onErrorRecover: Calculates driver that continues to drive the sequence in case of error. + - returns: Driver trait. + */ + public func asDriver(onErrorRecover: @escaping (_ error: Swift.Error) -> Driver) -> Driver { + let source = self + .asObservable() + .observe(on:DriverSharingStrategy.scheduler) + .catch { error in + onErrorRecover(error).asObservable() + } + return Driver(source) + } +} diff --git a/Pods/RxCocoa/RxCocoa/Traits/SharedSequence/ObservableConvertibleType+SharedSequence.swift b/Pods/RxCocoa/RxCocoa/Traits/SharedSequence/ObservableConvertibleType+SharedSequence.swift new file mode 100644 index 0000000..20ddf86 --- /dev/null +++ b/Pods/RxCocoa/RxCocoa/Traits/SharedSequence/ObservableConvertibleType+SharedSequence.swift @@ -0,0 +1,57 @@ +// +// ObservableConvertibleType+SharedSequence.swift +// RxCocoa +// +// Created by Krunoslav Zaher on 11/1/17. +// Copyright © 2017 Krunoslav Zaher. All rights reserved. +// + +import RxSwift + +extension ObservableConvertibleType { + /** + Converts anything convertible to `Observable` to `SharedSequence` unit. + + - parameter onErrorJustReturn: Element to return in case of error and after that complete the sequence. + - returns: Driving observable sequence. + */ + public func asSharedSequence(sharingStrategy: S.Type = S.self, onErrorJustReturn: Element) -> SharedSequence { + let source = self + .asObservable() + .observe(on:S.scheduler) + .catchAndReturn(onErrorJustReturn) + return SharedSequence(source) + } + + /** + Converts anything convertible to `Observable` to `SharedSequence` unit. + + - parameter onErrorDriveWith: SharedSequence that provides elements of the sequence in case of error. + - returns: Driving observable sequence. + */ + public func asSharedSequence(sharingStrategy: S.Type = S.self, onErrorDriveWith: SharedSequence) -> SharedSequence { + let source = self + .asObservable() + .observe(on:S.scheduler) + .catch { _ in + onErrorDriveWith.asObservable() + } + return SharedSequence(source) + } + + /** + Converts anything convertible to `Observable` to `SharedSequence` unit. + + - parameter onErrorRecover: Calculates driver that continues to drive the sequence in case of error. + - returns: Driving observable sequence. + */ + public func asSharedSequence(sharingStrategy: S.Type = S.self, onErrorRecover: @escaping (_ error: Swift.Error) -> SharedSequence) -> SharedSequence { + let source = self + .asObservable() + .observe(on:S.scheduler) + .catch { error in + onErrorRecover(error).asObservable() + } + return SharedSequence(source) + } +} diff --git a/Pods/RxCocoa/RxCocoa/Traits/SharedSequence/SchedulerType+SharedSequence.swift b/Pods/RxCocoa/RxCocoa/Traits/SharedSequence/SchedulerType+SharedSequence.swift new file mode 100644 index 0000000..5111e06 --- /dev/null +++ b/Pods/RxCocoa/RxCocoa/Traits/SharedSequence/SchedulerType+SharedSequence.swift @@ -0,0 +1,62 @@ +// +// SchedulerType+SharedSequence.swift +// RxCocoa +// +// Created by Krunoslav Zaher on 8/27/17. +// Copyright © 2017 Krunoslav Zaher. All rights reserved. +// + +import RxSwift + +public enum SharingScheduler { + /// Default scheduler used in SharedSequence based traits. + public private(set) static var make: () -> SchedulerType = { MainScheduler() } + + /** + This method can be used in unit tests to ensure that built in shared sequences are using mock schedulers instead + of main schedulers. + + **This shouldn't be used in normal release builds.** + */ + static public func mock(scheduler: SchedulerType, action: () throws -> Void) rethrows { + return try mock(makeScheduler: { scheduler }, action: action) + } + + /** + This method can be used in unit tests to ensure that built in shared sequences are using mock schedulers instead + of main schedulers. + + **This shouldn't be used in normal release builds.** + */ + static public func mock(makeScheduler: @escaping () -> SchedulerType, action: () throws -> Void) rethrows { + let originalMake = make + make = makeScheduler + defer { + make = originalMake + } + + try action() + + // If you remove this line , compiler buggy optimizations will change behavior of this code + _forceCompilerToStopDoingInsaneOptimizationsThatBreakCode(makeScheduler) + // Scary, I know + } +} + +#if os(Linux) + import Glibc +#else + import Foundation +#endif + +func _forceCompilerToStopDoingInsaneOptimizationsThatBreakCode(_ scheduler: () -> SchedulerType) { + let a: Int32 = 1 +#if os(Linux) + let b = 314 + Int32(Glibc.random() & 1) +#else + let b = 314 + Int32(arc4random() & 1) +#endif + if a == b { + print(scheduler()) + } +} diff --git a/Pods/RxCocoa/RxCocoa/Traits/SharedSequence/SharedSequence+Concurrency.swift b/Pods/RxCocoa/RxCocoa/Traits/SharedSequence/SharedSequence+Concurrency.swift new file mode 100644 index 0000000..c36b575 --- /dev/null +++ b/Pods/RxCocoa/RxCocoa/Traits/SharedSequence/SharedSequence+Concurrency.swift @@ -0,0 +1,42 @@ +// +// SharedSequence+Concurrency.swift +// RxCocoa +// +// Created by Shai Mishali on 22/09/2021. +// Copyright © 2021 Krunoslav Zaher. All rights reserved. +// + +#if swift(>=5.5.2) && canImport(_Concurrency) && !os(Linux) +import Foundation + +// MARK: - Shared Sequence +@available(macOS 10.15, iOS 13.0, watchOS 6.0, tvOS 13.0, *) +public extension SharedSequence { + /// Allows iterating over the values of this Shared Sequence + /// asynchronously via Swift's concurrency features (`async/await`) + /// + /// A sample usage would look like so: + /// + /// ```swift + /// for await value in driver.values { + /// // Handle emitted values + /// } + /// ``` + @MainActor var values: AsyncStream { + AsyncStream { continuation in + // It is safe to ignore the `onError` closure here since + // Shared Sequences (`Driver` and `Signal`) cannot fail + let disposable = self.asObservable() + .subscribe( + onNext: { value in continuation.yield(value) }, + onCompleted: { continuation.finish() }, + onDisposed: { continuation.onTermination?(.cancelled) } + ) + + continuation.onTermination = { @Sendable _ in + disposable.dispose() + } + } + } +} +#endif diff --git a/Pods/RxCocoa/RxCocoa/Traits/SharedSequence/SharedSequence+Operators+arity.swift b/Pods/RxCocoa/RxCocoa/Traits/SharedSequence/SharedSequence+Operators+arity.swift new file mode 100644 index 0000000..4cc967c --- /dev/null +++ b/Pods/RxCocoa/RxCocoa/Traits/SharedSequence/SharedSequence+Operators+arity.swift @@ -0,0 +1,656 @@ +// This file is autogenerated. Take a look at `Preprocessor` target in RxSwift project +// +// SharedSequence+Operators+arity.swift +// RxCocoa +// +// Created by Krunoslav Zaher on 10/14/15. +// Copyright © 2015 Krunoslav Zaher. All rights reserved. +// + +import RxSwift + + + +// 2 + +extension SharedSequence { + /** + Merges the specified observable sequences into one observable sequence by using the selector function whenever all of the observable sequences have produced an element at a corresponding index. + + - parameter resultSelector: Function to invoke for each series of elements at corresponding indexes in the sources. + - returns: An observable sequence containing the result of combining elements of the sources using the specified result selector function. + */ + public static func zip + (_ source1: O1, _ source2: O2, resultSelector: @escaping (O1.Element, O2.Element) throws -> Element) + -> SharedSequence where SharingStrategy == O1.SharingStrategy, + SharingStrategy == O2.SharingStrategy { + let source = Observable.zip( + source1.asSharedSequence().asObservable(), source2.asSharedSequence().asObservable(), + resultSelector: resultSelector + ) + + return SharedSequence(source) + } +} + +extension SharedSequenceConvertibleType where Element == Any { + /** + Merges the specified observable sequences into one observable sequence of element tuples whenever all of the observable sequences have produced an element at a corresponding index. + + - returns: An observable sequence containing the result of combining elements of the sources. + */ + public static func zip + (_ source1: O1, _ source2: O2) + -> SharedSequence where SharingStrategy == O1.SharingStrategy, + SharingStrategy == O2.SharingStrategy { + let source = Observable.zip( + source1.asSharedSequence().asObservable(), source2.asSharedSequence().asObservable() + ) + + return SharedSequence(source) + } +} + +extension SharedSequence { + /** + Merges the specified observable sequences into one observable sequence by using the selector function whenever any of the observable sequences produces an element. + + - parameter resultSelector: Function to invoke whenever any of the sources produces an element. + - returns: An observable sequence containing the result of combining elements of the sources using the specified result selector function. + */ + public static func combineLatest + (_ source1: O1, _ source2: O2, resultSelector: @escaping (O1.Element, O2.Element) throws -> Element) + -> SharedSequence where SharingStrategy == O1.SharingStrategy, + SharingStrategy == O2.SharingStrategy { + let source = Observable.combineLatest( + source1.asSharedSequence().asObservable(), source2.asSharedSequence().asObservable(), + resultSelector: resultSelector + ) + + return SharedSequence(source) + } +} + +extension SharedSequenceConvertibleType where Element == Any { + /** + Merges the specified observable sequences into one observable sequence of element tuples whenever any of the observable sequences produces an element. + + - returns: An observable sequence containing the result of combining elements of the sources. + */ + public static func combineLatest + (_ source1: O1, _ source2: O2) + -> SharedSequence where SharingStrategy == O1.SharingStrategy, + SharingStrategy == O2.SharingStrategy { + let source = Observable.combineLatest( + source1.asSharedSequence().asObservable(), source2.asSharedSequence().asObservable() + ) + + return SharedSequence(source) + } +} + + + +// 3 + +extension SharedSequence { + /** + Merges the specified observable sequences into one observable sequence by using the selector function whenever all of the observable sequences have produced an element at a corresponding index. + + - parameter resultSelector: Function to invoke for each series of elements at corresponding indexes in the sources. + - returns: An observable sequence containing the result of combining elements of the sources using the specified result selector function. + */ + public static func zip + (_ source1: O1, _ source2: O2, _ source3: O3, resultSelector: @escaping (O1.Element, O2.Element, O3.Element) throws -> Element) + -> SharedSequence where SharingStrategy == O1.SharingStrategy, + SharingStrategy == O2.SharingStrategy, + SharingStrategy == O3.SharingStrategy { + let source = Observable.zip( + source1.asSharedSequence().asObservable(), source2.asSharedSequence().asObservable(), source3.asSharedSequence().asObservable(), + resultSelector: resultSelector + ) + + return SharedSequence(source) + } +} + +extension SharedSequenceConvertibleType where Element == Any { + /** + Merges the specified observable sequences into one observable sequence of element tuples whenever all of the observable sequences have produced an element at a corresponding index. + + - returns: An observable sequence containing the result of combining elements of the sources. + */ + public static func zip + (_ source1: O1, _ source2: O2, _ source3: O3) + -> SharedSequence where SharingStrategy == O1.SharingStrategy, + SharingStrategy == O2.SharingStrategy, + SharingStrategy == O3.SharingStrategy { + let source = Observable.zip( + source1.asSharedSequence().asObservable(), source2.asSharedSequence().asObservable(), source3.asSharedSequence().asObservable() + ) + + return SharedSequence(source) + } +} + +extension SharedSequence { + /** + Merges the specified observable sequences into one observable sequence by using the selector function whenever any of the observable sequences produces an element. + + - parameter resultSelector: Function to invoke whenever any of the sources produces an element. + - returns: An observable sequence containing the result of combining elements of the sources using the specified result selector function. + */ + public static func combineLatest + (_ source1: O1, _ source2: O2, _ source3: O3, resultSelector: @escaping (O1.Element, O2.Element, O3.Element) throws -> Element) + -> SharedSequence where SharingStrategy == O1.SharingStrategy, + SharingStrategy == O2.SharingStrategy, + SharingStrategy == O3.SharingStrategy { + let source = Observable.combineLatest( + source1.asSharedSequence().asObservable(), source2.asSharedSequence().asObservable(), source3.asSharedSequence().asObservable(), + resultSelector: resultSelector + ) + + return SharedSequence(source) + } +} + +extension SharedSequenceConvertibleType where Element == Any { + /** + Merges the specified observable sequences into one observable sequence of element tuples whenever any of the observable sequences produces an element. + + - returns: An observable sequence containing the result of combining elements of the sources. + */ + public static func combineLatest + (_ source1: O1, _ source2: O2, _ source3: O3) + -> SharedSequence where SharingStrategy == O1.SharingStrategy, + SharingStrategy == O2.SharingStrategy, + SharingStrategy == O3.SharingStrategy { + let source = Observable.combineLatest( + source1.asSharedSequence().asObservable(), source2.asSharedSequence().asObservable(), source3.asSharedSequence().asObservable() + ) + + return SharedSequence(source) + } +} + + + +// 4 + +extension SharedSequence { + /** + Merges the specified observable sequences into one observable sequence by using the selector function whenever all of the observable sequences have produced an element at a corresponding index. + + - parameter resultSelector: Function to invoke for each series of elements at corresponding indexes in the sources. + - returns: An observable sequence containing the result of combining elements of the sources using the specified result selector function. + */ + public static func zip + (_ source1: O1, _ source2: O2, _ source3: O3, _ source4: O4, resultSelector: @escaping (O1.Element, O2.Element, O3.Element, O4.Element) throws -> Element) + -> SharedSequence where SharingStrategy == O1.SharingStrategy, + SharingStrategy == O2.SharingStrategy, + SharingStrategy == O3.SharingStrategy, + SharingStrategy == O4.SharingStrategy { + let source = Observable.zip( + source1.asSharedSequence().asObservable(), source2.asSharedSequence().asObservable(), source3.asSharedSequence().asObservable(), source4.asSharedSequence().asObservable(), + resultSelector: resultSelector + ) + + return SharedSequence(source) + } +} + +extension SharedSequenceConvertibleType where Element == Any { + /** + Merges the specified observable sequences into one observable sequence of element tuples whenever all of the observable sequences have produced an element at a corresponding index. + + - returns: An observable sequence containing the result of combining elements of the sources. + */ + public static func zip + (_ source1: O1, _ source2: O2, _ source3: O3, _ source4: O4) + -> SharedSequence where SharingStrategy == O1.SharingStrategy, + SharingStrategy == O2.SharingStrategy, + SharingStrategy == O3.SharingStrategy, + SharingStrategy == O4.SharingStrategy { + let source = Observable.zip( + source1.asSharedSequence().asObservable(), source2.asSharedSequence().asObservable(), source3.asSharedSequence().asObservable(), source4.asSharedSequence().asObservable() + ) + + return SharedSequence(source) + } +} + +extension SharedSequence { + /** + Merges the specified observable sequences into one observable sequence by using the selector function whenever any of the observable sequences produces an element. + + - parameter resultSelector: Function to invoke whenever any of the sources produces an element. + - returns: An observable sequence containing the result of combining elements of the sources using the specified result selector function. + */ + public static func combineLatest + (_ source1: O1, _ source2: O2, _ source3: O3, _ source4: O4, resultSelector: @escaping (O1.Element, O2.Element, O3.Element, O4.Element) throws -> Element) + -> SharedSequence where SharingStrategy == O1.SharingStrategy, + SharingStrategy == O2.SharingStrategy, + SharingStrategy == O3.SharingStrategy, + SharingStrategy == O4.SharingStrategy { + let source = Observable.combineLatest( + source1.asSharedSequence().asObservable(), source2.asSharedSequence().asObservable(), source3.asSharedSequence().asObservable(), source4.asSharedSequence().asObservable(), + resultSelector: resultSelector + ) + + return SharedSequence(source) + } +} + +extension SharedSequenceConvertibleType where Element == Any { + /** + Merges the specified observable sequences into one observable sequence of element tuples whenever any of the observable sequences produces an element. + + - returns: An observable sequence containing the result of combining elements of the sources. + */ + public static func combineLatest + (_ source1: O1, _ source2: O2, _ source3: O3, _ source4: O4) + -> SharedSequence where SharingStrategy == O1.SharingStrategy, + SharingStrategy == O2.SharingStrategy, + SharingStrategy == O3.SharingStrategy, + SharingStrategy == O4.SharingStrategy { + let source = Observable.combineLatest( + source1.asSharedSequence().asObservable(), source2.asSharedSequence().asObservable(), source3.asSharedSequence().asObservable(), source4.asSharedSequence().asObservable() + ) + + return SharedSequence(source) + } +} + + + +// 5 + +extension SharedSequence { + /** + Merges the specified observable sequences into one observable sequence by using the selector function whenever all of the observable sequences have produced an element at a corresponding index. + + - parameter resultSelector: Function to invoke for each series of elements at corresponding indexes in the sources. + - returns: An observable sequence containing the result of combining elements of the sources using the specified result selector function. + */ + public static func zip + (_ source1: O1, _ source2: O2, _ source3: O3, _ source4: O4, _ source5: O5, resultSelector: @escaping (O1.Element, O2.Element, O3.Element, O4.Element, O5.Element) throws -> Element) + -> SharedSequence where SharingStrategy == O1.SharingStrategy, + SharingStrategy == O2.SharingStrategy, + SharingStrategy == O3.SharingStrategy, + SharingStrategy == O4.SharingStrategy, + SharingStrategy == O5.SharingStrategy { + let source = Observable.zip( + source1.asSharedSequence().asObservable(), source2.asSharedSequence().asObservable(), source3.asSharedSequence().asObservable(), source4.asSharedSequence().asObservable(), source5.asSharedSequence().asObservable(), + resultSelector: resultSelector + ) + + return SharedSequence(source) + } +} + +extension SharedSequenceConvertibleType where Element == Any { + /** + Merges the specified observable sequences into one observable sequence of element tuples whenever all of the observable sequences have produced an element at a corresponding index. + + - returns: An observable sequence containing the result of combining elements of the sources. + */ + public static func zip + (_ source1: O1, _ source2: O2, _ source3: O3, _ source4: O4, _ source5: O5) + -> SharedSequence where SharingStrategy == O1.SharingStrategy, + SharingStrategy == O2.SharingStrategy, + SharingStrategy == O3.SharingStrategy, + SharingStrategy == O4.SharingStrategy, + SharingStrategy == O5.SharingStrategy { + let source = Observable.zip( + source1.asSharedSequence().asObservable(), source2.asSharedSequence().asObservable(), source3.asSharedSequence().asObservable(), source4.asSharedSequence().asObservable(), source5.asSharedSequence().asObservable() + ) + + return SharedSequence(source) + } +} + +extension SharedSequence { + /** + Merges the specified observable sequences into one observable sequence by using the selector function whenever any of the observable sequences produces an element. + + - parameter resultSelector: Function to invoke whenever any of the sources produces an element. + - returns: An observable sequence containing the result of combining elements of the sources using the specified result selector function. + */ + public static func combineLatest + (_ source1: O1, _ source2: O2, _ source3: O3, _ source4: O4, _ source5: O5, resultSelector: @escaping (O1.Element, O2.Element, O3.Element, O4.Element, O5.Element) throws -> Element) + -> SharedSequence where SharingStrategy == O1.SharingStrategy, + SharingStrategy == O2.SharingStrategy, + SharingStrategy == O3.SharingStrategy, + SharingStrategy == O4.SharingStrategy, + SharingStrategy == O5.SharingStrategy { + let source = Observable.combineLatest( + source1.asSharedSequence().asObservable(), source2.asSharedSequence().asObservable(), source3.asSharedSequence().asObservable(), source4.asSharedSequence().asObservable(), source5.asSharedSequence().asObservable(), + resultSelector: resultSelector + ) + + return SharedSequence(source) + } +} + +extension SharedSequenceConvertibleType where Element == Any { + /** + Merges the specified observable sequences into one observable sequence of element tuples whenever any of the observable sequences produces an element. + + - returns: An observable sequence containing the result of combining elements of the sources. + */ + public static func combineLatest + (_ source1: O1, _ source2: O2, _ source3: O3, _ source4: O4, _ source5: O5) + -> SharedSequence where SharingStrategy == O1.SharingStrategy, + SharingStrategy == O2.SharingStrategy, + SharingStrategy == O3.SharingStrategy, + SharingStrategy == O4.SharingStrategy, + SharingStrategy == O5.SharingStrategy { + let source = Observable.combineLatest( + source1.asSharedSequence().asObservable(), source2.asSharedSequence().asObservable(), source3.asSharedSequence().asObservable(), source4.asSharedSequence().asObservable(), source5.asSharedSequence().asObservable() + ) + + return SharedSequence(source) + } +} + + + +// 6 + +extension SharedSequence { + /** + Merges the specified observable sequences into one observable sequence by using the selector function whenever all of the observable sequences have produced an element at a corresponding index. + + - parameter resultSelector: Function to invoke for each series of elements at corresponding indexes in the sources. + - returns: An observable sequence containing the result of combining elements of the sources using the specified result selector function. + */ + public static func zip + (_ source1: O1, _ source2: O2, _ source3: O3, _ source4: O4, _ source5: O5, _ source6: O6, resultSelector: @escaping (O1.Element, O2.Element, O3.Element, O4.Element, O5.Element, O6.Element) throws -> Element) + -> SharedSequence where SharingStrategy == O1.SharingStrategy, + SharingStrategy == O2.SharingStrategy, + SharingStrategy == O3.SharingStrategy, + SharingStrategy == O4.SharingStrategy, + SharingStrategy == O5.SharingStrategy, + SharingStrategy == O6.SharingStrategy { + let source = Observable.zip( + source1.asSharedSequence().asObservable(), source2.asSharedSequence().asObservable(), source3.asSharedSequence().asObservable(), source4.asSharedSequence().asObservable(), source5.asSharedSequence().asObservable(), source6.asSharedSequence().asObservable(), + resultSelector: resultSelector + ) + + return SharedSequence(source) + } +} + +extension SharedSequenceConvertibleType where Element == Any { + /** + Merges the specified observable sequences into one observable sequence of element tuples whenever all of the observable sequences have produced an element at a corresponding index. + + - returns: An observable sequence containing the result of combining elements of the sources. + */ + public static func zip + (_ source1: O1, _ source2: O2, _ source3: O3, _ source4: O4, _ source5: O5, _ source6: O6) + -> SharedSequence where SharingStrategy == O1.SharingStrategy, + SharingStrategy == O2.SharingStrategy, + SharingStrategy == O3.SharingStrategy, + SharingStrategy == O4.SharingStrategy, + SharingStrategy == O5.SharingStrategy, + SharingStrategy == O6.SharingStrategy { + let source = Observable.zip( + source1.asSharedSequence().asObservable(), source2.asSharedSequence().asObservable(), source3.asSharedSequence().asObservable(), source4.asSharedSequence().asObservable(), source5.asSharedSequence().asObservable(), source6.asSharedSequence().asObservable() + ) + + return SharedSequence(source) + } +} + +extension SharedSequence { + /** + Merges the specified observable sequences into one observable sequence by using the selector function whenever any of the observable sequences produces an element. + + - parameter resultSelector: Function to invoke whenever any of the sources produces an element. + - returns: An observable sequence containing the result of combining elements of the sources using the specified result selector function. + */ + public static func combineLatest + (_ source1: O1, _ source2: O2, _ source3: O3, _ source4: O4, _ source5: O5, _ source6: O6, resultSelector: @escaping (O1.Element, O2.Element, O3.Element, O4.Element, O5.Element, O6.Element) throws -> Element) + -> SharedSequence where SharingStrategy == O1.SharingStrategy, + SharingStrategy == O2.SharingStrategy, + SharingStrategy == O3.SharingStrategy, + SharingStrategy == O4.SharingStrategy, + SharingStrategy == O5.SharingStrategy, + SharingStrategy == O6.SharingStrategy { + let source = Observable.combineLatest( + source1.asSharedSequence().asObservable(), source2.asSharedSequence().asObservable(), source3.asSharedSequence().asObservable(), source4.asSharedSequence().asObservable(), source5.asSharedSequence().asObservable(), source6.asSharedSequence().asObservable(), + resultSelector: resultSelector + ) + + return SharedSequence(source) + } +} + +extension SharedSequenceConvertibleType where Element == Any { + /** + Merges the specified observable sequences into one observable sequence of element tuples whenever any of the observable sequences produces an element. + + - returns: An observable sequence containing the result of combining elements of the sources. + */ + public static func combineLatest + (_ source1: O1, _ source2: O2, _ source3: O3, _ source4: O4, _ source5: O5, _ source6: O6) + -> SharedSequence where SharingStrategy == O1.SharingStrategy, + SharingStrategy == O2.SharingStrategy, + SharingStrategy == O3.SharingStrategy, + SharingStrategy == O4.SharingStrategy, + SharingStrategy == O5.SharingStrategy, + SharingStrategy == O6.SharingStrategy { + let source = Observable.combineLatest( + source1.asSharedSequence().asObservable(), source2.asSharedSequence().asObservable(), source3.asSharedSequence().asObservable(), source4.asSharedSequence().asObservable(), source5.asSharedSequence().asObservable(), source6.asSharedSequence().asObservable() + ) + + return SharedSequence(source) + } +} + + + +// 7 + +extension SharedSequence { + /** + Merges the specified observable sequences into one observable sequence by using the selector function whenever all of the observable sequences have produced an element at a corresponding index. + + - parameter resultSelector: Function to invoke for each series of elements at corresponding indexes in the sources. + - returns: An observable sequence containing the result of combining elements of the sources using the specified result selector function. + */ + public static func zip + (_ source1: O1, _ source2: O2, _ source3: O3, _ source4: O4, _ source5: O5, _ source6: O6, _ source7: O7, resultSelector: @escaping (O1.Element, O2.Element, O3.Element, O4.Element, O5.Element, O6.Element, O7.Element) throws -> Element) + -> SharedSequence where SharingStrategy == O1.SharingStrategy, + SharingStrategy == O2.SharingStrategy, + SharingStrategy == O3.SharingStrategy, + SharingStrategy == O4.SharingStrategy, + SharingStrategy == O5.SharingStrategy, + SharingStrategy == O6.SharingStrategy, + SharingStrategy == O7.SharingStrategy { + let source = Observable.zip( + source1.asSharedSequence().asObservable(), source2.asSharedSequence().asObservable(), source3.asSharedSequence().asObservable(), source4.asSharedSequence().asObservable(), source5.asSharedSequence().asObservable(), source6.asSharedSequence().asObservable(), source7.asSharedSequence().asObservable(), + resultSelector: resultSelector + ) + + return SharedSequence(source) + } +} + +extension SharedSequenceConvertibleType where Element == Any { + /** + Merges the specified observable sequences into one observable sequence of element tuples whenever all of the observable sequences have produced an element at a corresponding index. + + - returns: An observable sequence containing the result of combining elements of the sources. + */ + public static func zip + (_ source1: O1, _ source2: O2, _ source3: O3, _ source4: O4, _ source5: O5, _ source6: O6, _ source7: O7) + -> SharedSequence where SharingStrategy == O1.SharingStrategy, + SharingStrategy == O2.SharingStrategy, + SharingStrategy == O3.SharingStrategy, + SharingStrategy == O4.SharingStrategy, + SharingStrategy == O5.SharingStrategy, + SharingStrategy == O6.SharingStrategy, + SharingStrategy == O7.SharingStrategy { + let source = Observable.zip( + source1.asSharedSequence().asObservable(), source2.asSharedSequence().asObservable(), source3.asSharedSequence().asObservable(), source4.asSharedSequence().asObservable(), source5.asSharedSequence().asObservable(), source6.asSharedSequence().asObservable(), source7.asSharedSequence().asObservable() + ) + + return SharedSequence(source) + } +} + +extension SharedSequence { + /** + Merges the specified observable sequences into one observable sequence by using the selector function whenever any of the observable sequences produces an element. + + - parameter resultSelector: Function to invoke whenever any of the sources produces an element. + - returns: An observable sequence containing the result of combining elements of the sources using the specified result selector function. + */ + public static func combineLatest + (_ source1: O1, _ source2: O2, _ source3: O3, _ source4: O4, _ source5: O5, _ source6: O6, _ source7: O7, resultSelector: @escaping (O1.Element, O2.Element, O3.Element, O4.Element, O5.Element, O6.Element, O7.Element) throws -> Element) + -> SharedSequence where SharingStrategy == O1.SharingStrategy, + SharingStrategy == O2.SharingStrategy, + SharingStrategy == O3.SharingStrategy, + SharingStrategy == O4.SharingStrategy, + SharingStrategy == O5.SharingStrategy, + SharingStrategy == O6.SharingStrategy, + SharingStrategy == O7.SharingStrategy { + let source = Observable.combineLatest( + source1.asSharedSequence().asObservable(), source2.asSharedSequence().asObservable(), source3.asSharedSequence().asObservable(), source4.asSharedSequence().asObservable(), source5.asSharedSequence().asObservable(), source6.asSharedSequence().asObservable(), source7.asSharedSequence().asObservable(), + resultSelector: resultSelector + ) + + return SharedSequence(source) + } +} + +extension SharedSequenceConvertibleType where Element == Any { + /** + Merges the specified observable sequences into one observable sequence of element tuples whenever any of the observable sequences produces an element. + + - returns: An observable sequence containing the result of combining elements of the sources. + */ + public static func combineLatest + (_ source1: O1, _ source2: O2, _ source3: O3, _ source4: O4, _ source5: O5, _ source6: O6, _ source7: O7) + -> SharedSequence where SharingStrategy == O1.SharingStrategy, + SharingStrategy == O2.SharingStrategy, + SharingStrategy == O3.SharingStrategy, + SharingStrategy == O4.SharingStrategy, + SharingStrategy == O5.SharingStrategy, + SharingStrategy == O6.SharingStrategy, + SharingStrategy == O7.SharingStrategy { + let source = Observable.combineLatest( + source1.asSharedSequence().asObservable(), source2.asSharedSequence().asObservable(), source3.asSharedSequence().asObservable(), source4.asSharedSequence().asObservable(), source5.asSharedSequence().asObservable(), source6.asSharedSequence().asObservable(), source7.asSharedSequence().asObservable() + ) + + return SharedSequence(source) + } +} + + + +// 8 + +extension SharedSequence { + /** + Merges the specified observable sequences into one observable sequence by using the selector function whenever all of the observable sequences have produced an element at a corresponding index. + + - parameter resultSelector: Function to invoke for each series of elements at corresponding indexes in the sources. + - returns: An observable sequence containing the result of combining elements of the sources using the specified result selector function. + */ + public static func zip + (_ source1: O1, _ source2: O2, _ source3: O3, _ source4: O4, _ source5: O5, _ source6: O6, _ source7: O7, _ source8: O8, resultSelector: @escaping (O1.Element, O2.Element, O3.Element, O4.Element, O5.Element, O6.Element, O7.Element, O8.Element) throws -> Element) + -> SharedSequence where SharingStrategy == O1.SharingStrategy, + SharingStrategy == O2.SharingStrategy, + SharingStrategy == O3.SharingStrategy, + SharingStrategy == O4.SharingStrategy, + SharingStrategy == O5.SharingStrategy, + SharingStrategy == O6.SharingStrategy, + SharingStrategy == O7.SharingStrategy, + SharingStrategy == O8.SharingStrategy { + let source = Observable.zip( + source1.asSharedSequence().asObservable(), source2.asSharedSequence().asObservable(), source3.asSharedSequence().asObservable(), source4.asSharedSequence().asObservable(), source5.asSharedSequence().asObservable(), source6.asSharedSequence().asObservable(), source7.asSharedSequence().asObservable(), source8.asSharedSequence().asObservable(), + resultSelector: resultSelector + ) + + return SharedSequence(source) + } +} + +extension SharedSequenceConvertibleType where Element == Any { + /** + Merges the specified observable sequences into one observable sequence of element tuples whenever all of the observable sequences have produced an element at a corresponding index. + + - returns: An observable sequence containing the result of combining elements of the sources. + */ + public static func zip + (_ source1: O1, _ source2: O2, _ source3: O3, _ source4: O4, _ source5: O5, _ source6: O6, _ source7: O7, _ source8: O8) + -> SharedSequence where SharingStrategy == O1.SharingStrategy, + SharingStrategy == O2.SharingStrategy, + SharingStrategy == O3.SharingStrategy, + SharingStrategy == O4.SharingStrategy, + SharingStrategy == O5.SharingStrategy, + SharingStrategy == O6.SharingStrategy, + SharingStrategy == O7.SharingStrategy, + SharingStrategy == O8.SharingStrategy { + let source = Observable.zip( + source1.asSharedSequence().asObservable(), source2.asSharedSequence().asObservable(), source3.asSharedSequence().asObservable(), source4.asSharedSequence().asObservable(), source5.asSharedSequence().asObservable(), source6.asSharedSequence().asObservable(), source7.asSharedSequence().asObservable(), source8.asSharedSequence().asObservable() + ) + + return SharedSequence(source) + } +} + +extension SharedSequence { + /** + Merges the specified observable sequences into one observable sequence by using the selector function whenever any of the observable sequences produces an element. + + - parameter resultSelector: Function to invoke whenever any of the sources produces an element. + - returns: An observable sequence containing the result of combining elements of the sources using the specified result selector function. + */ + public static func combineLatest + (_ source1: O1, _ source2: O2, _ source3: O3, _ source4: O4, _ source5: O5, _ source6: O6, _ source7: O7, _ source8: O8, resultSelector: @escaping (O1.Element, O2.Element, O3.Element, O4.Element, O5.Element, O6.Element, O7.Element, O8.Element) throws -> Element) + -> SharedSequence where SharingStrategy == O1.SharingStrategy, + SharingStrategy == O2.SharingStrategy, + SharingStrategy == O3.SharingStrategy, + SharingStrategy == O4.SharingStrategy, + SharingStrategy == O5.SharingStrategy, + SharingStrategy == O6.SharingStrategy, + SharingStrategy == O7.SharingStrategy, + SharingStrategy == O8.SharingStrategy { + let source = Observable.combineLatest( + source1.asSharedSequence().asObservable(), source2.asSharedSequence().asObservable(), source3.asSharedSequence().asObservable(), source4.asSharedSequence().asObservable(), source5.asSharedSequence().asObservable(), source6.asSharedSequence().asObservable(), source7.asSharedSequence().asObservable(), source8.asSharedSequence().asObservable(), + resultSelector: resultSelector + ) + + return SharedSequence(source) + } +} + +extension SharedSequenceConvertibleType where Element == Any { + /** + Merges the specified observable sequences into one observable sequence of element tuples whenever any of the observable sequences produces an element. + + - returns: An observable sequence containing the result of combining elements of the sources. + */ + public static func combineLatest + (_ source1: O1, _ source2: O2, _ source3: O3, _ source4: O4, _ source5: O5, _ source6: O6, _ source7: O7, _ source8: O8) + -> SharedSequence where SharingStrategy == O1.SharingStrategy, + SharingStrategy == O2.SharingStrategy, + SharingStrategy == O3.SharingStrategy, + SharingStrategy == O4.SharingStrategy, + SharingStrategy == O5.SharingStrategy, + SharingStrategy == O6.SharingStrategy, + SharingStrategy == O7.SharingStrategy, + SharingStrategy == O8.SharingStrategy { + let source = Observable.combineLatest( + source1.asSharedSequence().asObservable(), source2.asSharedSequence().asObservable(), source3.asSharedSequence().asObservable(), source4.asSharedSequence().asObservable(), source5.asSharedSequence().asObservable(), source6.asSharedSequence().asObservable(), source7.asSharedSequence().asObservable(), source8.asSharedSequence().asObservable() + ) + + return SharedSequence(source) + } +} + + diff --git a/Pods/RxCocoa/RxCocoa/Traits/SharedSequence/SharedSequence+Operators.swift b/Pods/RxCocoa/RxCocoa/Traits/SharedSequence/SharedSequence+Operators.swift new file mode 100644 index 0000000..1d53b03 --- /dev/null +++ b/Pods/RxCocoa/RxCocoa/Traits/SharedSequence/SharedSequence+Operators.swift @@ -0,0 +1,584 @@ +// +// SharedSequence+Operators.swift +// RxCocoa +// +// Created by Krunoslav Zaher on 9/19/15. +// Copyright © 2015 Krunoslav Zaher. All rights reserved. +// + +import RxSwift + +// MARK: map +extension SharedSequenceConvertibleType { + + /** + Projects each element of an observable sequence into a new form. + + - parameter selector: A transform function to apply to each source element. + - returns: An observable sequence whose elements are the result of invoking the transform function on each element of source. + */ + public func map(_ selector: @escaping (Element) -> Result) -> SharedSequence { + let source = self + .asObservable() + .map(selector) + return SharedSequence(source) + } +} + +// MARK: compactMap +extension SharedSequenceConvertibleType { + + /** + Projects each element of an observable sequence into an optional form and filters all optional results. + + - parameter selector: A transform function to apply to each source element and which returns an element or nil. + - returns: An observable sequence whose elements are the result of filtering the transform function for each element of the source. + + */ + public func compactMap(_ selector: @escaping (Element) -> Result?) -> SharedSequence { + let source = self + .asObservable() + .compactMap(selector) + return SharedSequence(source) + } +} + +// MARK: filter +extension SharedSequenceConvertibleType { + /** + Filters the elements of an observable sequence based on a predicate. + + - parameter predicate: A function to test each source element for a condition. + - returns: An observable sequence that contains elements from the input sequence that satisfy the condition. + */ + public func filter(_ predicate: @escaping (Element) -> Bool) -> SharedSequence { + let source = self + .asObservable() + .filter(predicate) + return SharedSequence(source) + } +} + +// MARK: switchLatest +extension SharedSequenceConvertibleType where Element: SharedSequenceConvertibleType { + + /** + Transforms an observable sequence of observable sequences into an observable sequence + producing values only from the most recent observable sequence. + + Each time a new inner observable sequence is received, unsubscribe from the + previous inner observable sequence. + + - returns: The observable sequence that at any point in time produces the elements of the most recent inner observable sequence that has been received. + */ + public func switchLatest() -> SharedSequence { + let source: Observable = self + .asObservable() + .map { $0.asSharedSequence() } + .switchLatest() + return SharedSequence(source) + } +} + +// MARK: flatMapLatest +extension SharedSequenceConvertibleType { + /** + Projects each element of an observable sequence into a new sequence of observable sequences and then + transforms an observable sequence of observable sequences into an observable sequence producing values only from the most recent observable sequence. + + It is a combination of `map` + `switchLatest` operator + + - parameter selector: A transform function to apply to each element. + - returns: An observable sequence whose elements are the result of invoking the transform function on each element of source producing an + Observable of Observable sequences and that at any point in time produces the elements of the most recent inner observable sequence that has been received. + */ + public func flatMapLatest(_ selector: @escaping (Element) -> SharedSequence) + -> SharedSequence { + let source: Observable = self + .asObservable() + .flatMapLatest(selector) + return SharedSequence(source) + } +} + +// MARK: flatMapFirst +extension SharedSequenceConvertibleType { + + /** + Projects each element of an observable sequence to an observable sequence and merges the resulting observable sequences into one observable sequence. + If element is received while there is some projected observable sequence being merged it will simply be ignored. + + - parameter selector: A transform function to apply to element that was observed while no observable is executing in parallel. + - returns: An observable sequence whose elements are the result of invoking the one-to-many transform function on each element of the input sequence that was received while no other sequence was being calculated. + */ + public func flatMapFirst(_ selector: @escaping (Element) -> SharedSequence) + -> SharedSequence { + let source: Observable = self + .asObservable() + .flatMapFirst(selector) + return SharedSequence(source) + } +} + +// MARK: do +extension SharedSequenceConvertibleType { + /** + Invokes an action for each event in the observable sequence, and propagates all observer messages through the result sequence. + + - parameter onNext: Action to invoke for each element in the observable sequence. + - parameter afterNext: Action to invoke for each element after the observable has passed an onNext event along to its downstream. + - parameter onCompleted: Action to invoke upon graceful termination of the observable sequence. + - parameter afterCompleted: Action to invoke after graceful termination of the observable sequence. + - parameter onSubscribe: Action to invoke before subscribing to source observable sequence. + - parameter onSubscribed: Action to invoke after subscribing to source observable sequence. + - parameter onDispose: Action to invoke after subscription to source observable has been disposed for any reason. It can be either because sequence terminates for some reason or observer subscription being disposed. + - returns: The source sequence with the side-effecting behavior applied. + */ + public func `do`(onNext: ((Element) -> Void)? = nil, afterNext: ((Element) -> Void)? = nil, onCompleted: (() -> Void)? = nil, afterCompleted: (() -> Void)? = nil, onSubscribe: (() -> Void)? = nil, onSubscribed: (() -> Void)? = nil, onDispose: (() -> Void)? = nil) + -> SharedSequence { + let source = self.asObservable() + .do(onNext: onNext, afterNext: afterNext, onCompleted: onCompleted, afterCompleted: afterCompleted, onSubscribe: onSubscribe, onSubscribed: onSubscribed, onDispose: onDispose) + + return SharedSequence(source) + } +} + +// MARK: debug +extension SharedSequenceConvertibleType { + + /** + Prints received events for all observers on standard output. + + - parameter identifier: Identifier that is printed together with event description to standard output. + - returns: An observable sequence whose events are printed to standard output. + */ + public func debug(_ identifier: String? = nil, trimOutput: Bool = false, file: String = #file, line: UInt = #line, function: String = #function) -> SharedSequence { + let source = self.asObservable() + .debug(identifier, trimOutput: trimOutput, file: file, line: line, function: function) + return SharedSequence(source) + } +} + +// MARK: distinctUntilChanged +extension SharedSequenceConvertibleType where Element: Equatable { + + /** + Returns an observable sequence that contains only distinct contiguous elements according to equality operator. + + - returns: An observable sequence only containing the distinct contiguous elements, based on equality operator, from the source sequence. + */ + public func distinctUntilChanged() + -> SharedSequence { + let source = self.asObservable() + .distinctUntilChanged({ $0 }, comparer: { ($0 == $1) }) + + return SharedSequence(source) + } +} + +extension SharedSequenceConvertibleType { + + /** + Returns an observable sequence that contains only distinct contiguous elements according to the `keySelector`. + + - parameter keySelector: A function to compute the comparison key for each element. + - returns: An observable sequence only containing the distinct contiguous elements, based on a computed key value, from the source sequence. + */ + public func distinctUntilChanged(_ keySelector: @escaping (Element) -> Key) -> SharedSequence { + let source = self.asObservable() + .distinctUntilChanged(keySelector, comparer: { $0 == $1 }) + return SharedSequence(source) + } + + /** + Returns an observable sequence that contains only distinct contiguous elements according to the `comparer`. + + - parameter comparer: Equality comparer for computed key values. + - returns: An observable sequence only containing the distinct contiguous elements, based on `comparer`, from the source sequence. + */ + public func distinctUntilChanged(_ comparer: @escaping (Element, Element) -> Bool) -> SharedSequence { + let source = self.asObservable() + .distinctUntilChanged({ $0 }, comparer: comparer) + return SharedSequence(source) + } + + /** + Returns an observable sequence that contains only distinct contiguous elements according to the keySelector and the comparer. + + - parameter keySelector: A function to compute the comparison key for each element. + - parameter comparer: Equality comparer for computed key values. + - returns: An observable sequence only containing the distinct contiguous elements, based on a computed key value and the comparer, from the source sequence. + */ + public func distinctUntilChanged(_ keySelector: @escaping (Element) -> K, comparer: @escaping (K, K) -> Bool) -> SharedSequence { + let source = self.asObservable() + .distinctUntilChanged(keySelector, comparer: comparer) + return SharedSequence(source) + } +} + + +// MARK: flatMap +extension SharedSequenceConvertibleType { + + /** + Projects each element of an observable sequence to an observable sequence and merges the resulting observable sequences into one observable sequence. + + - parameter selector: A transform function to apply to each element. + - returns: An observable sequence whose elements are the result of invoking the one-to-many transform function on each element of the input sequence. + */ + public func flatMap(_ selector: @escaping (Element) -> SharedSequence) -> SharedSequence { + let source = self.asObservable() + .flatMap(selector) + + return SharedSequence(source) + } +} + +// MARK: merge +extension SharedSequenceConvertibleType { + /** + Merges elements from all observable sequences from collection into a single observable sequence. + + - seealso: [merge operator on reactivex.io](http://reactivex.io/documentation/operators/merge.html) + + - parameter sources: Collection of observable sequences to merge. + - returns: The observable sequence that merges the elements of the observable sequences. + */ + public static func merge(_ sources: Collection) -> SharedSequence + where Collection.Element == SharedSequence { + let source = Observable.merge(sources.map { $0.asObservable() }) + return SharedSequence(source) + } + + /** + Merges elements from all observable sequences from array into a single observable sequence. + + - seealso: [merge operator on reactivex.io](http://reactivex.io/documentation/operators/merge.html) + + - parameter sources: Array of observable sequences to merge. + - returns: The observable sequence that merges the elements of the observable sequences. + */ + public static func merge(_ sources: [SharedSequence]) -> SharedSequence { + let source = Observable.merge(sources.map { $0.asObservable() }) + return SharedSequence(source) + } + + /** + Merges elements from all observable sequences into a single observable sequence. + + - seealso: [merge operator on reactivex.io](http://reactivex.io/documentation/operators/merge.html) + + - parameter sources: Collection of observable sequences to merge. + - returns: The observable sequence that merges the elements of the observable sequences. + */ + public static func merge(_ sources: SharedSequence...) -> SharedSequence { + let source = Observable.merge(sources.map { $0.asObservable() }) + return SharedSequence(source) + } + +} + +// MARK: merge +extension SharedSequenceConvertibleType where Element: SharedSequenceConvertibleType { + /** + Merges elements from all observable sequences in the given enumerable sequence into a single observable sequence. + + - returns: The observable sequence that merges the elements of the observable sequences. + */ + public func merge() -> SharedSequence { + let source = self.asObservable() + .map { $0.asSharedSequence() } + .merge() + return SharedSequence(source) + } + + /** + Merges elements from all inner observable sequences into a single observable sequence, limiting the number of concurrent subscriptions to inner sequences. + + - parameter maxConcurrent: Maximum number of inner observable sequences being subscribed to concurrently. + - returns: The observable sequence that merges the elements of the inner sequences. + */ + public func merge(maxConcurrent: Int) + -> SharedSequence { + let source = self.asObservable() + .map { $0.asSharedSequence() } + .merge(maxConcurrent: maxConcurrent) + return SharedSequence(source) + } +} + +// MARK: throttle +extension SharedSequenceConvertibleType { + + /** + Returns an Observable that emits the first and the latest item emitted by the source Observable during sequential time windows of a specified duration. + + This operator makes sure that no two elements are emitted in less then dueTime. + + - seealso: [debounce operator on reactivex.io](http://reactivex.io/documentation/operators/debounce.html) + + - parameter dueTime: Throttling duration for each element. + - parameter latest: Should latest element received in a dueTime wide time window since last element emission be emitted. + - returns: The throttled sequence. + */ + public func throttle(_ dueTime: RxTimeInterval, latest: Bool = true) + -> SharedSequence { + let source = self.asObservable() + .throttle(dueTime, latest: latest, scheduler: SharingStrategy.scheduler) + + return SharedSequence(source) + } + + /** + Ignores elements from an observable sequence which are followed by another element within a specified relative time duration, using the specified scheduler to run throttling timers. + + - parameter dueTime: Throttling duration for each element. + - returns: The throttled sequence. + */ + public func debounce(_ dueTime: RxTimeInterval) + -> SharedSequence { + let source = self.asObservable() + .debounce(dueTime, scheduler: SharingStrategy.scheduler) + + return SharedSequence(source) + } +} + +// MARK: scan +extension SharedSequenceConvertibleType { + /** + Applies an accumulator function over an observable sequence and returns each intermediate result. The specified seed value is used as the initial accumulator value. + + For aggregation behavior with no intermediate results, see `reduce`. + + - parameter seed: The initial accumulator value. + - parameter accumulator: An accumulator function to be invoked on each element. + - returns: An observable sequence containing the accumulated values. + */ + public func scan(_ seed: A, accumulator: @escaping (A, Element) -> A) + -> SharedSequence { + let source = self.asObservable() + .scan(seed, accumulator: accumulator) + return SharedSequence(source) + } +} + +// MARK: concat + +extension SharedSequence { + /** + Concatenates all observable sequences in the given sequence, as long as the previous observable sequence terminated successfully. + + - returns: An observable sequence that contains the elements of each given sequence, in sequential order. + */ + public static func concat(_ sequence: Sequence) -> SharedSequence + where Sequence.Element == SharedSequence { + let source = Observable.concat(sequence.lazy.map { $0.asObservable() }) + return SharedSequence(source) + } + + /** + Concatenates all observable sequences in the given sequence, as long as the previous observable sequence terminated successfully. + + - returns: An observable sequence that contains the elements of each given sequence, in sequential order. + */ + public static func concat(_ collection: Collection) -> SharedSequence + where Collection.Element == SharedSequence { + let source = Observable.concat(collection.map { $0.asObservable() }) + return SharedSequence(source) + } +} + +// MARK: zip + +extension SharedSequence { + /** + Merges the specified observable sequences into one observable sequence by using the selector function whenever all of the observable sequences have produced an element at a corresponding index. + + - parameter resultSelector: Function to invoke for each series of elements at corresponding indexes in the sources. + - returns: An observable sequence containing the result of combining elements of the sources using the specified result selector function. + */ + public static func zip(_ collection: Collection, resultSelector: @escaping ([Element]) throws -> Result) -> SharedSequence + where Collection.Element == SharedSequence { + let source = Observable.zip(collection.map { $0.asSharedSequence().asObservable() }, resultSelector: resultSelector) + return SharedSequence(source) + } + + /** + Merges the specified observable sequences into one observable sequence all of the observable sequences have produced an element at a corresponding index. + + - returns: An observable sequence containing the result of combining elements of the sources. + */ + public static func zip(_ collection: Collection) -> SharedSequence + where Collection.Element == SharedSequence { + let source = Observable.zip(collection.map { $0.asSharedSequence().asObservable() }) + return SharedSequence(source) + } +} + +// MARK: combineLatest + +extension SharedSequence { + /** + Merges the specified observable sequences into one observable sequence by using the selector function whenever any of the observable sequences produces an element. + + - parameter resultSelector: Function to invoke whenever any of the sources produces an element. + - returns: An observable sequence containing the result of combining elements of the sources using the specified result selector function. + */ + public static func combineLatest(_ collection: Collection, resultSelector: @escaping ([Element]) throws -> Result) -> SharedSequence + where Collection.Element == SharedSequence { + let source = Observable.combineLatest(collection.map { $0.asObservable() }, resultSelector: resultSelector) + return SharedSequence(source) + } + + /** + Merges the specified observable sequences into one observable sequence whenever any of the observable sequences produces an element. + + - returns: An observable sequence containing the result of combining elements of the sources. + */ + public static func combineLatest(_ collection: Collection) -> SharedSequence + where Collection.Element == SharedSequence { + let source = Observable.combineLatest(collection.map { $0.asObservable() }) + return SharedSequence(source) + } +} + +// MARK: - withUnretained +extension SharedSequenceConvertibleType where SharingStrategy == SignalSharingStrategy { + /** + Provides an unretained, safe to use (i.e. not implicitly unwrapped), reference to an object along with the events emitted by the sequence. + + In the case the provided object cannot be retained successfully, the sequence will complete. + + - note: Be careful when using this operator in a sequence that has a buffer or replay, for example `share(replay: 1)`, as the sharing buffer will also include the provided object, which could potentially cause a retain cycle. + + - parameter obj: The object to provide an unretained reference on. + - parameter resultSelector: A function to combine the unretained referenced on `obj` and the value of the observable sequence. + - returns: An observable sequence that contains the result of `resultSelector` being called with an unretained reference on `obj` and the values of the original sequence. + */ + public func withUnretained( + _ obj: Object, + resultSelector: @escaping (Object, Element) -> Out + ) -> SharedSequence { + SharedSequence(self.asObservable().withUnretained(obj, resultSelector: resultSelector)) + } + + /** + Provides an unretained, safe to use (i.e. not implicitly unwrapped), reference to an object along with the events emitted by the sequence. + + In the case the provided object cannot be retained successfully, the sequence will complete. + + - note: Be careful when using this operator in a sequence that has a buffer or replay, for example `share(replay: 1)`, as the sharing buffer will also include the provided object, which could potentially cause a retain cycle. + + - parameter obj: The object to provide an unretained reference on. + - returns: An observable sequence of tuples that contains both an unretained reference on `obj` and the values of the original sequence. + */ + public func withUnretained(_ obj: Object) -> SharedSequence { + withUnretained(obj) { ($0, $1) } + } +} + +extension SharedSequenceConvertibleType where SharingStrategy == DriverSharingStrategy { + @available(*, message: "withUnretained has been deprecated for Driver. Consider using `drive(with:onNext:onCompleted:onDisposed:)`, instead", unavailable) + public func withUnretained( + _ obj: Object, + resultSelector: @escaping (Object, Element) -> Out + ) -> SharedSequence { + SharedSequence(self.asObservable().withUnretained(obj, resultSelector: resultSelector)) + } + + @available(*, message: "withUnretained has been deprecated for Driver. Consider using `drive(with:onNext:onCompleted:onDisposed:)`, instead", unavailable) + public func withUnretained(_ obj: Object) -> SharedSequence { + SharedSequence(self.asObservable().withUnretained(obj) { ($0, $1) }) + } +} + +// MARK: withLatestFrom +extension SharedSequenceConvertibleType { + + /** + Merges two observable sequences into one observable sequence by combining each element from self with the latest element from the second source, if any. + + - parameter second: Second observable source. + - parameter resultSelector: Function to invoke for each element from the self combined with the latest element from the second source, if any. + - returns: An observable sequence containing the result of combining each element of the self with the latest element from the second source, if any, using the specified result selector function. + */ + public func withLatestFrom(_ second: SecondO, resultSelector: @escaping (Element, SecondO.Element) -> ResultType) -> SharedSequence where SecondO.SharingStrategy == SharingStrategy { + let source = self.asObservable() + .withLatestFrom(second.asSharedSequence(), resultSelector: resultSelector) + + return SharedSequence(source) + } + + /** + Merges two observable sequences into one observable sequence by using latest element from the second sequence every time when `self` emits an element. + + - parameter second: Second observable source. + - returns: An observable sequence containing the result of combining each element of the self with the latest element from the second source, if any, using the specified result selector function. + */ + public func withLatestFrom(_ second: SecondO) -> SharedSequence { + let source = self.asObservable() + .withLatestFrom(second.asSharedSequence()) + + return SharedSequence(source) + } +} + +// MARK: skip +extension SharedSequenceConvertibleType { + + /** + Bypasses a specified number of elements in an observable sequence and then returns the remaining elements. + + - seealso: [skip operator on reactivex.io](http://reactivex.io/documentation/operators/skip.html) + + - parameter count: The number of elements to skip before returning the remaining elements. + - returns: An observable sequence that contains the elements that occur after the specified index in the input sequence. + */ + public func skip(_ count: Int) + -> SharedSequence { + let source = self.asObservable() + .skip(count) + return SharedSequence(source) + } +} + +// MARK: startWith +extension SharedSequenceConvertibleType { + + /** + Prepends a value to an observable sequence. + + - seealso: [startWith operator on reactivex.io](http://reactivex.io/documentation/operators/startwith.html) + + - parameter element: Element to prepend to the specified sequence. + - returns: The source sequence prepended with the specified values. + */ + public func startWith(_ element: Element) + -> SharedSequence { + let source = self.asObservable() + .startWith(element) + + return SharedSequence(source) + } +} + +// MARK: delay +extension SharedSequenceConvertibleType { + + /** + Returns an observable sequence by the source observable sequence shifted forward in time by a specified delay. Error events from the source observable sequence are not delayed. + + - seealso: [delay operator on reactivex.io](http://reactivex.io/documentation/operators/delay.html) + + - parameter dueTime: Relative time shift of the source by. + - returns: the source Observable shifted in time by the specified delay. + */ + public func delay(_ dueTime: RxTimeInterval) + -> SharedSequence { + let source = self.asObservable() + .delay(dueTime, scheduler: SharingStrategy.scheduler) + + return SharedSequence(source) + } +} diff --git a/Pods/RxCocoa/RxCocoa/Traits/SharedSequence/SharedSequence.swift b/Pods/RxCocoa/RxCocoa/Traits/SharedSequence/SharedSequence.swift new file mode 100644 index 0000000..4db2ee4 --- /dev/null +++ b/Pods/RxCocoa/RxCocoa/Traits/SharedSequence/SharedSequence.swift @@ -0,0 +1,226 @@ +// +// SharedSequence.swift +// RxCocoa +// +// Created by Krunoslav Zaher on 8/27/15. +// Copyright © 2015 Krunoslav Zaher. All rights reserved. +// + +import RxSwift + +/** + Trait that represents observable sequence that shares computation resources with following properties: + + - it never fails + - it delivers events on `SharingStrategy.scheduler` + - sharing strategy is customizable using `SharingStrategy.share` behavior + + `SharedSequence` can be considered a builder pattern for observable sequences that share computation resources. + + To find out more about units and how to use them, please visit `Documentation/Traits.md`. +*/ +public struct SharedSequence : SharedSequenceConvertibleType, ObservableConvertibleType { + let source: Observable + + init(_ source: Observable) { + self.source = SharingStrategy.share(source) + } + + init(raw: Observable) { + self.source = raw + } + + #if EXPANDABLE_SHARED_SEQUENCE + /** + This method is extension hook in case this unit needs to extended from outside the library. + + By defining `EXPANDABLE_SHARED_SEQUENCE` one agrees that it's up to them to ensure shared sequence + properties are preserved after extension. + */ + public static func createUnsafe(source: Source) -> SharedSequence { + SharedSequence(raw: source.asObservable()) + } + #endif + + /** + - returns: Built observable sequence. + */ + public func asObservable() -> Observable { + self.source + } + + /** + - returns: `self` + */ + public func asSharedSequence() -> SharedSequence { + self + } +} + +/** + Different `SharedSequence` sharing strategies must conform to this protocol. + */ +public protocol SharingStrategyProtocol { + /** + Scheduled on which all sequence events will be delivered. + */ + static var scheduler: SchedulerType { get } + + /** + Computation resources sharing strategy for multiple sequence observers. + + E.g. One can choose `share(replay:scope:)` + as sequence event sharing strategies, but also do something more exotic, like + implementing promises or lazy loading chains. + */ + static func share(_ source: Observable) -> Observable +} + +/** +A type that can be converted to `SharedSequence`. +*/ +public protocol SharedSequenceConvertibleType : ObservableConvertibleType { + associatedtype SharingStrategy: SharingStrategyProtocol + + /** + Converts self to `SharedSequence`. + */ + func asSharedSequence() -> SharedSequence +} + +extension SharedSequenceConvertibleType { + public func asObservable() -> Observable { + self.asSharedSequence().asObservable() + } +} + + +extension SharedSequence { + + /** + Returns an empty observable sequence, using the specified scheduler to send out the single `Completed` message. + + - returns: An observable sequence with no elements. + */ + public static func empty() -> SharedSequence { + SharedSequence(raw: Observable.empty().subscribe(on: SharingStrategy.scheduler)) + } + + /** + Returns a non-terminating observable sequence, which can be used to denote an infinite duration. + + - returns: An observable sequence whose observers will never get called. + */ + public static func never() -> SharedSequence { + SharedSequence(raw: Observable.never()) + } + + /** + Returns an observable sequence that contains a single element. + + - parameter element: Single element in the resulting observable sequence. + - returns: An observable sequence containing the single specified element. + */ + public static func just(_ element: Element) -> SharedSequence { + SharedSequence(raw: Observable.just(element).subscribe(on: SharingStrategy.scheduler)) + } + + /** + Returns an observable sequence that invokes the specified factory function whenever a new observer subscribes. + + - parameter observableFactory: Observable factory function to invoke for each observer that subscribes to the resulting sequence. + - returns: An observable sequence whose observers trigger an invocation of the given observable factory function. + */ + public static func deferred(_ observableFactory: @escaping () -> SharedSequence) + -> SharedSequence { + SharedSequence(Observable.deferred { observableFactory().asObservable() }) + } + + /** + This method creates a new Observable instance with a variable number of elements. + + - seealso: [from operator on reactivex.io](http://reactivex.io/documentation/operators/from.html) + + - parameter elements: Elements to generate. + - returns: The observable sequence whose elements are pulled from the given arguments. + */ + public static func of(_ elements: Element ...) -> SharedSequence { + let source = Observable.from(elements, scheduler: SharingStrategy.scheduler) + return SharedSequence(raw: source) + } +} + +extension SharedSequence { + + /** + This method converts an array to an observable sequence. + + - seealso: [from operator on reactivex.io](http://reactivex.io/documentation/operators/from.html) + + - returns: The observable sequence whose elements are pulled from the given enumerable sequence. + */ + public static func from(_ array: [Element]) -> SharedSequence { + let source = Observable.from(array, scheduler: SharingStrategy.scheduler) + return SharedSequence(raw: source) + } + + /** + This method converts a sequence to an observable sequence. + + - seealso: [from operator on reactivex.io](http://reactivex.io/documentation/operators/from.html) + + - returns: The observable sequence whose elements are pulled from the given enumerable sequence. + */ + public static func from(_ sequence: Sequence) -> SharedSequence where Sequence.Element == Element { + let source = Observable.from(sequence, scheduler: SharingStrategy.scheduler) + return SharedSequence(raw: source) + } + + /** + This method converts a optional to an observable sequence. + + - seealso: [from operator on reactivex.io](http://reactivex.io/documentation/operators/from.html) + + - parameter optional: Optional element in the resulting observable sequence. + + - returns: An observable sequence containing the wrapped value or not from given optional. + */ + public static func from(optional: Element?) -> SharedSequence { + let source = Observable.from(optional: optional, scheduler: SharingStrategy.scheduler) + return SharedSequence(raw: source) + } +} + +extension SharedSequence where Element: RxAbstractInteger { + /** + Returns an observable sequence that produces a value after each period, using the specified scheduler to run timers and to send out observer messages. + + - seealso: [interval operator on reactivex.io](http://reactivex.io/documentation/operators/interval.html) + + - parameter period: Period for producing the values in the resulting sequence. + - returns: An observable sequence that produces a value after each period. + */ + public static func interval(_ period: RxTimeInterval) + -> SharedSequence { + SharedSequence(Observable.interval(period, scheduler: SharingStrategy.scheduler)) + } +} + +// MARK: timer + +extension SharedSequence where Element: RxAbstractInteger { + /** + Returns an observable sequence that periodically produces a value after the specified initial relative due time has elapsed, using the specified scheduler to run timers. + + - seealso: [timer operator on reactivex.io](http://reactivex.io/documentation/operators/timer.html) + + - parameter dueTime: Relative time at which to produce the first value. + - parameter period: Period to produce subsequent values. + - returns: An observable sequence that produces a value after due time has elapsed and then each period. + */ + public static func timer(_ dueTime: RxTimeInterval, period: RxTimeInterval) + -> SharedSequence { + SharedSequence(Observable.timer(dueTime, period: period, scheduler: SharingStrategy.scheduler)) + } +} + diff --git a/Pods/RxCocoa/RxCocoa/Traits/Signal/ControlEvent+Signal.swift b/Pods/RxCocoa/RxCocoa/Traits/Signal/ControlEvent+Signal.swift new file mode 100644 index 0000000..bec4723 --- /dev/null +++ b/Pods/RxCocoa/RxCocoa/Traits/Signal/ControlEvent+Signal.swift @@ -0,0 +1,25 @@ +// +// ControlEvent+Signal.swift +// RxCocoa +// +// Created by Krunoslav Zaher on 11/1/17. +// Copyright © 2017 Krunoslav Zaher. All rights reserved. +// + +import RxSwift + +extension ControlEvent { + /// Converts `ControlEvent` to `Signal` trait. + /// + /// `ControlEvent` already can't fail, so no special case needs to be handled. + public func asSignal() -> Signal { + return self.asSignal { _ -> Signal in + #if DEBUG + rxFatalError("Somehow signal received error from a source that shouldn't fail.") + #else + return Signal.empty() + #endif + } + } +} + diff --git a/Pods/RxCocoa/RxCocoa/Traits/Signal/ObservableConvertibleType+Signal.swift b/Pods/RxCocoa/RxCocoa/Traits/Signal/ObservableConvertibleType+Signal.swift new file mode 100644 index 0000000..b962d4e --- /dev/null +++ b/Pods/RxCocoa/RxCocoa/Traits/Signal/ObservableConvertibleType+Signal.swift @@ -0,0 +1,57 @@ +// +// ObservableConvertibleType+Signal.swift +// RxCocoa +// +// Created by Krunoslav Zaher on 9/19/15. +// Copyright © 2015 Krunoslav Zaher. All rights reserved. +// + +import RxSwift + +extension ObservableConvertibleType { + /** + Converts observable sequence to `Signal` trait. + + - parameter onErrorJustReturn: Element to return in case of error and after that complete the sequence. + - returns: Signal trait. + */ + public func asSignal(onErrorJustReturn: Element) -> Signal { + let source = self + .asObservable() + .observe(on: SignalSharingStrategy.scheduler) + .catchAndReturn(onErrorJustReturn) + return Signal(source) + } + + /** + Converts observable sequence to `Signal` trait. + + - parameter onErrorSignalWith: Signal that continues to emit the sequence in case of error. + - returns: Signal trait. + */ + public func asSignal(onErrorSignalWith: Signal) -> Signal { + let source = self + .asObservable() + .observe(on: SignalSharingStrategy.scheduler) + .catch { _ in + onErrorSignalWith.asObservable() + } + return Signal(source) + } + + /** + Converts observable sequence to `Signal` trait. + + - parameter onErrorRecover: Calculates signal that continues to emit the sequence in case of error. + - returns: Signal trait. + */ + public func asSignal(onErrorRecover: @escaping (_ error: Swift.Error) -> Signal) -> Signal { + let source = self + .asObservable() + .observe(on: SignalSharingStrategy.scheduler) + .catch { error in + onErrorRecover(error).asObservable() + } + return Signal(source) + } +} diff --git a/Pods/RxCocoa/RxCocoa/Traits/Signal/PublishRelay+Signal.swift b/Pods/RxCocoa/RxCocoa/Traits/Signal/PublishRelay+Signal.swift new file mode 100644 index 0000000..79b975d --- /dev/null +++ b/Pods/RxCocoa/RxCocoa/Traits/Signal/PublishRelay+Signal.swift @@ -0,0 +1,21 @@ +// +// PublishRelay+Signal.swift +// RxCocoa +// +// Created by Krunoslav Zaher on 12/28/15. +// Copyright © 2017 Krunoslav Zaher. All rights reserved. +// + +import RxSwift +import RxRelay + +extension PublishRelay { + /// Converts `PublishRelay` to `Signal`. + /// + /// - returns: Observable sequence. + public func asSignal() -> Signal { + let source = self.asObservable() + .observe(on:SignalSharingStrategy.scheduler) + return SharedSequence(source) + } +} diff --git a/Pods/RxCocoa/RxCocoa/Traits/Signal/Signal+Subscription.swift b/Pods/RxCocoa/RxCocoa/Traits/Signal/Signal+Subscription.swift new file mode 100644 index 0000000..4a6add3 --- /dev/null +++ b/Pods/RxCocoa/RxCocoa/Traits/Signal/Signal+Subscription.swift @@ -0,0 +1,178 @@ +// +// Signal+Subscription.swift +// RxCocoa +// +// Created by Krunoslav Zaher on 9/19/15. +// Copyright © 2015 Krunoslav Zaher. All rights reserved. +// + +import RxSwift +import RxRelay + +extension SharedSequenceConvertibleType where SharingStrategy == SignalSharingStrategy { + /** + Creates new subscription and sends elements to observer. + + In this form it's equivalent to `subscribe` method, but it communicates intent better. + + - parameter observers: Observers that receives events. + - returns: Disposable object that can be used to unsubscribe the observer from the subject. + */ + public func emit(to observers: Observer...) -> Disposable where Observer.Element == Element { + return self.asSharedSequence() + .asObservable() + .subscribe { event in + observers.forEach { $0.on(event) } + } + } + + /** + Creates new subscription and sends elements to observer. + + In this form it's equivalent to `subscribe` method, but it communicates intent better. + + - parameter observers: Observers that receives events. + - returns: Disposable object that can be used to unsubscribe the observer from the subject. + */ + public func emit(to observers: Observer...) -> Disposable where Observer.Element == Element? { + return self.asSharedSequence() + .asObservable() + .map { $0 as Element? } + .subscribe { event in + observers.forEach { $0.on(event) } + } + } + + /** + Creates new subscription and sends elements to `BehaviorRelay`. + - parameter relays: Target relays for sequence elements. + - returns: Disposable object that can be used to unsubscribe the observer from the relay. + */ + public func emit(to relays: BehaviorRelay...) -> Disposable { + return self.emit(onNext: { e in + relays.forEach { $0.accept(e) } + }) + } + + /** + Creates new subscription and sends elements to `BehaviorRelay`. + - parameter relays: Target relays for sequence elements. + - returns: Disposable object that can be used to unsubscribe the observer from the relay. + */ + public func emit(to relays: BehaviorRelay...) -> Disposable { + return self.emit(onNext: { e in + relays.forEach { $0.accept(e) } + }) + } + + /** + Creates new subscription and sends elements to `PublishRelay`. + + - parameter relays: Target relays for sequence elements. + - returns: Disposable object that can be used to unsubscribe the observer from the relay. + */ + public func emit(to relays: PublishRelay...) -> Disposable { + return self.emit(onNext: { e in + relays.forEach { $0.accept(e) } + }) + } + + /** + Creates new subscription and sends elements to `PublishRelay`. + + - parameter relays: Target relay for sequence elements. + - returns: Disposable object that can be used to unsubscribe the observer from the relay. + */ + public func emit(to relays: PublishRelay...) -> Disposable { + return self.emit(onNext: { e in + relays.forEach { $0.accept(e) } + }) + } + + /** + Creates new subscription and sends elements to `ReplayRelay`. + + - parameter relays: Target relays for sequence elements. + - returns: Disposable object that can be used to unsubscribe the observer from the relay. + */ + public func emit(to relays: ReplayRelay...) -> Disposable { + return self.emit(onNext: { e in + relays.forEach { $0.accept(e) } + }) + } + + /** + Creates new subscription and sends elements to `ReplayRelay`. + + - parameter relays: Target relay for sequence elements. + - returns: Disposable object that can be used to unsubscribe the observer from the relay. + */ + public func emit(to relays: ReplayRelay...) -> Disposable { + return self.emit(onNext: { e in + relays.forEach { $0.accept(e) } + }) + } + + /** + Subscribes an element handler, a completion handler and disposed handler to an observable sequence. + + Also, take in an object and provide an unretained, safe to use (i.e. not implicitly unwrapped), reference to it along with the events emitted by the sequence. + + Error callback is not exposed because `Signal` can't error out. + + - Note: If `object` can't be retained, none of the other closures will be invoked. + + - parameter object: The object to provide an unretained reference on. + - parameter onNext: Action to invoke for each element in the observable sequence. + - parameter onCompleted: Action to invoke upon graceful termination of the observable sequence. + gracefully completed, errored, or if the generation is canceled by disposing subscription) + - parameter onDisposed: Action to invoke upon any type of termination of sequence (if the sequence has + gracefully completed, errored, or if the generation is canceled by disposing subscription) + - returns: Subscription object used to unsubscribe from the observable sequence. + */ + public func emit( + with object: Object, + onNext: ((Object, Element) -> Void)? = nil, + onCompleted: ((Object) -> Void)? = nil, + onDisposed: ((Object) -> Void)? = nil + ) -> Disposable { + self.asObservable().subscribe( + with: object, + onNext: onNext, + onCompleted: onCompleted, + onDisposed: onDisposed + ) + } + + /** + Subscribes an element handler, a completion handler and disposed handler to an observable sequence. + + Error callback is not exposed because `Signal` can't error out. + + - parameter onNext: Action to invoke for each element in the observable sequence. + - parameter onCompleted: Action to invoke upon graceful termination of the observable sequence. + gracefully completed, errored, or if the generation is canceled by disposing subscription) + - parameter onDisposed: Action to invoke upon any type of termination of sequence (if the sequence has + gracefully completed, errored, or if the generation is canceled by disposing subscription) + - returns: Subscription object used to unsubscribe from the observable sequence. + */ + public func emit( + onNext: ((Element) -> Void)? = nil, + onCompleted: (() -> Void)? = nil, + onDisposed: (() -> Void)? = nil + ) -> Disposable { + self.asObservable().subscribe(onNext: onNext, onCompleted: onCompleted, onDisposed: onDisposed) + } + + /** + Subscribes to this `Signal` with a no-op. + This method can be only called from `MainThread`. + + - note: This is an alias of `emit(onNext: nil, onCompleted: nil, onDisposed: nil)` used to fix an ambiguity bug in Swift: https://bugs.swift.org/browse/SR-13657 + + - returns: Subscription object used to unsubscribe from the observable sequence. + */ + public func emit() -> Disposable { + emit(onNext: nil, onCompleted: nil, onDisposed: nil) + } +} diff --git a/Pods/RxCocoa/RxCocoa/Traits/Signal/Signal.swift b/Pods/RxCocoa/RxCocoa/Traits/Signal/Signal.swift new file mode 100644 index 0000000..e066b7e --- /dev/null +++ b/Pods/RxCocoa/RxCocoa/Traits/Signal/Signal.swift @@ -0,0 +1,45 @@ +// +// Signal.swift +// RxCocoa +// +// Created by Krunoslav Zaher on 9/26/16. +// Copyright © 2016 Krunoslav Zaher. All rights reserved. +// + +import RxSwift + +/** + Trait that represents observable sequence with following properties: + + - it never fails + - it delivers events on `MainScheduler.instance` + - `share(scope: .whileConnected)` sharing strategy + + Additional explanation: + - all observers share sequence computation resources + - there is no replaying of sequence elements on new observer subscription + - computation of elements is reference counted with respect to the number of observers + - if there are no subscribers, it will release sequence computation resources + + In case trait that models state propagation is required, please check `Driver`. + + `Signal` can be considered a builder pattern for observable sequences that model imperative events part of the application. + + To find out more about units and how to use them, please visit `Documentation/Traits.md`. + */ +public typealias Signal = SharedSequence + +public struct SignalSharingStrategy: SharingStrategyProtocol { + public static var scheduler: SchedulerType { SharingScheduler.make() } + + public static func share(_ source: Observable) -> Observable { + source.share(scope: .whileConnected) + } +} + +extension SharedSequenceConvertibleType where SharingStrategy == SignalSharingStrategy { + /// Adds `asPublisher` to `SharingSequence` with `PublishSharingStrategy`. + public func asSignal() -> Signal { + self.asSharedSequence() + } +} diff --git a/Pods/RxCocoa/RxCocoa/iOS/DataSources/RxCollectionViewReactiveArrayDataSource.swift b/Pods/RxCocoa/RxCocoa/iOS/DataSources/RxCollectionViewReactiveArrayDataSource.swift new file mode 100644 index 0000000..1acc998 --- /dev/null +++ b/Pods/RxCocoa/RxCocoa/iOS/DataSources/RxCollectionViewReactiveArrayDataSource.swift @@ -0,0 +1,108 @@ +// +// RxCollectionViewReactiveArrayDataSource.swift +// RxCocoa +// +// Created by Krunoslav Zaher on 6/29/15. +// Copyright © 2015 Krunoslav Zaher. All rights reserved. +// + +#if os(iOS) || os(tvOS) + +import UIKit +import RxSwift + +// objc monkey business +class _RxCollectionViewReactiveArrayDataSource + : NSObject + , UICollectionViewDataSource { + + @objc(numberOfSectionsInCollectionView:) + func numberOfSections(in: UICollectionView) -> Int { + 1 + } + + func _collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int { + 0 + } + + func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int { + _collectionView(collectionView, numberOfItemsInSection: section) + } + + fileprivate func _collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell { + rxAbstractMethod() + } + + func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell { + _collectionView(collectionView, cellForItemAt: indexPath) + } +} + +class RxCollectionViewReactiveArrayDataSourceSequenceWrapper + : RxCollectionViewReactiveArrayDataSource + , RxCollectionViewDataSourceType { + typealias Element = Sequence + + override init(cellFactory: @escaping CellFactory) { + super.init(cellFactory: cellFactory) + } + + func collectionView(_ collectionView: UICollectionView, observedEvent: Event) { + Binder(self) { collectionViewDataSource, sectionModels in + let sections = Array(sectionModels) + collectionViewDataSource.collectionView(collectionView, observedElements: sections) + }.on(observedEvent) + } +} + + +// Please take a look at `DelegateProxyType.swift` +class RxCollectionViewReactiveArrayDataSource + : _RxCollectionViewReactiveArrayDataSource + , SectionedViewDataSourceType { + + typealias CellFactory = (UICollectionView, Int, Element) -> UICollectionViewCell + + var itemModels: [Element]? + + func modelAtIndex(_ index: Int) -> Element? { + itemModels?[index] + } + + func model(at indexPath: IndexPath) throws -> Any { + precondition(indexPath.section == 0) + guard let item = itemModels?[indexPath.item] else { + throw RxCocoaError.itemsNotYetBound(object: self) + } + return item + } + + var cellFactory: CellFactory + + init(cellFactory: @escaping CellFactory) { + self.cellFactory = cellFactory + } + + // data source + + override func _collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int { + itemModels?.count ?? 0 + } + + override func _collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell { + cellFactory(collectionView, indexPath.item, itemModels![indexPath.item]) + } + + // reactive + + func collectionView(_ collectionView: UICollectionView, observedElements: [Element]) { + self.itemModels = observedElements + + collectionView.reloadData() + + // workaround for http://stackoverflow.com/questions/39867325/ios-10-bug-uicollectionview-received-layout-attributes-for-a-cell-with-an-index + collectionView.collectionViewLayout.invalidateLayout() + } +} + +#endif diff --git a/Pods/RxCocoa/RxCocoa/iOS/DataSources/RxPickerViewAdapter.swift b/Pods/RxCocoa/RxCocoa/iOS/DataSources/RxPickerViewAdapter.swift new file mode 100644 index 0000000..53b8475 --- /dev/null +++ b/Pods/RxCocoa/RxCocoa/iOS/DataSources/RxPickerViewAdapter.swift @@ -0,0 +1,92 @@ +// +// RxPickerViewAdapter.swift +// RxCocoa +// +// Created by Sergey Shulga on 12/07/2017. +// Copyright © 2017 Krunoslav Zaher. All rights reserved. +// + +#if os(iOS) + +import UIKit +import RxSwift + +class RxPickerViewArrayDataSource: NSObject, UIPickerViewDataSource, SectionedViewDataSourceType { + fileprivate var items: [T] = [] + + func model(at indexPath: IndexPath) throws -> Any { + guard items.indices ~= indexPath.row else { + throw RxCocoaError.itemsNotYetBound(object: self) + } + return items[indexPath.row] + } + + func numberOfComponents(in pickerView: UIPickerView) -> Int { + 1 + } + + func pickerView(_ pickerView: UIPickerView, numberOfRowsInComponent component: Int) -> Int { + items.count + } +} + +class RxPickerViewSequenceDataSource + : RxPickerViewArrayDataSource + , RxPickerViewDataSourceType { + typealias Element = Sequence + + func pickerView(_ pickerView: UIPickerView, observedEvent: Event) { + Binder(self) { dataSource, items in + dataSource.items = items + pickerView.reloadAllComponents() + } + .on(observedEvent.map(Array.init)) + } +} + +final class RxStringPickerViewAdapter + : RxPickerViewSequenceDataSource + , UIPickerViewDelegate { + + typealias TitleForRow = (Int, Sequence.Element) -> String? + private let titleForRow: TitleForRow + + init(titleForRow: @escaping TitleForRow) { + self.titleForRow = titleForRow + super.init() + } + + func pickerView(_ pickerView: UIPickerView, titleForRow row: Int, forComponent component: Int) -> String? { + titleForRow(row, items[row]) + } +} + +final class RxAttributedStringPickerViewAdapter: RxPickerViewSequenceDataSource, UIPickerViewDelegate { + typealias AttributedTitleForRow = (Int, Sequence.Element) -> NSAttributedString? + private let attributedTitleForRow: AttributedTitleForRow + + init(attributedTitleForRow: @escaping AttributedTitleForRow) { + self.attributedTitleForRow = attributedTitleForRow + super.init() + } + + func pickerView(_ pickerView: UIPickerView, attributedTitleForRow row: Int, forComponent component: Int) -> NSAttributedString? { + attributedTitleForRow(row, items[row]) + } +} + +final class RxPickerViewAdapter: RxPickerViewSequenceDataSource, UIPickerViewDelegate { + typealias ViewForRow = (Int, Sequence.Element, UIView?) -> UIView + private let viewForRow: ViewForRow + + init(viewForRow: @escaping ViewForRow) { + self.viewForRow = viewForRow + super.init() + } + + func pickerView(_ pickerView: UIPickerView, viewForRow row: Int, forComponent component: Int, reusing view: UIView?) -> UIView { + viewForRow(row, items[row], view) + } +} + +#endif diff --git a/Pods/RxCocoa/RxCocoa/iOS/DataSources/RxTableViewReactiveArrayDataSource.swift b/Pods/RxCocoa/RxCocoa/iOS/DataSources/RxTableViewReactiveArrayDataSource.swift new file mode 100644 index 0000000..6d612f3 --- /dev/null +++ b/Pods/RxCocoa/RxCocoa/iOS/DataSources/RxTableViewReactiveArrayDataSource.swift @@ -0,0 +1,101 @@ +// +// RxTableViewReactiveArrayDataSource.swift +// RxCocoa +// +// Created by Krunoslav Zaher on 6/26/15. +// Copyright © 2015 Krunoslav Zaher. All rights reserved. +// + +#if os(iOS) || os(tvOS) + +import UIKit +import RxSwift + +// objc monkey business +class _RxTableViewReactiveArrayDataSource + : NSObject + , UITableViewDataSource { + + func numberOfSections(in tableView: UITableView) -> Int { + 1 + } + + func _tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { + 0 + } + + func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { + _tableView(tableView, numberOfRowsInSection: section) + } + + fileprivate func _tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { + rxAbstractMethod() + } + + func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { + _tableView(tableView, cellForRowAt: indexPath) + } +} + + +class RxTableViewReactiveArrayDataSourceSequenceWrapper + : RxTableViewReactiveArrayDataSource + , RxTableViewDataSourceType { + typealias Element = Sequence + + override init(cellFactory: @escaping CellFactory) { + super.init(cellFactory: cellFactory) + } + + func tableView(_ tableView: UITableView, observedEvent: Event) { + Binder(self) { tableViewDataSource, sectionModels in + let sections = Array(sectionModels) + tableViewDataSource.tableView(tableView, observedElements: sections) + }.on(observedEvent) + } +} + +// Please take a look at `DelegateProxyType.swift` +class RxTableViewReactiveArrayDataSource + : _RxTableViewReactiveArrayDataSource + , SectionedViewDataSourceType { + typealias CellFactory = (UITableView, Int, Element) -> UITableViewCell + + var itemModels: [Element]? + + func modelAtIndex(_ index: Int) -> Element? { + itemModels?[index] + } + + func model(at indexPath: IndexPath) throws -> Any { + precondition(indexPath.section == 0) + guard let item = itemModels?[indexPath.item] else { + throw RxCocoaError.itemsNotYetBound(object: self) + } + return item + } + + let cellFactory: CellFactory + + init(cellFactory: @escaping CellFactory) { + self.cellFactory = cellFactory + } + + override func _tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { + itemModels?.count ?? 0 + } + + override func _tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { + cellFactory(tableView, indexPath.item, itemModels![indexPath.row]) + } + + // reactive + + func tableView(_ tableView: UITableView, observedElements: [Element]) { + self.itemModels = observedElements + + tableView.reloadData() + } +} + +#endif diff --git a/Pods/RxCocoa/RxCocoa/iOS/Events/ItemEvents.swift b/Pods/RxCocoa/RxCocoa/iOS/Events/ItemEvents.swift new file mode 100644 index 0000000..aadf749 --- /dev/null +++ b/Pods/RxCocoa/RxCocoa/iOS/Events/ItemEvents.swift @@ -0,0 +1,15 @@ +// +// ItemEvents.swift +// RxCocoa +// +// Created by Krunoslav Zaher on 6/20/15. +// Copyright © 2015 Krunoslav Zaher. All rights reserved. +// + +#if os(iOS) || os(tvOS) +import UIKit + +public typealias ItemMovedEvent = (sourceIndex: IndexPath, destinationIndex: IndexPath) +public typealias WillDisplayCellEvent = (cell: UITableViewCell, indexPath: IndexPath) +public typealias DidEndDisplayingCellEvent = (cell: UITableViewCell, indexPath: IndexPath) +#endif diff --git a/Pods/RxCocoa/RxCocoa/iOS/NSTextStorage+Rx.swift b/Pods/RxCocoa/RxCocoa/iOS/NSTextStorage+Rx.swift new file mode 100644 index 0000000..ba30547 --- /dev/null +++ b/Pods/RxCocoa/RxCocoa/iOS/NSTextStorage+Rx.swift @@ -0,0 +1,35 @@ +// +// NSTextStorage+Rx.swift +// RxCocoa +// +// Created by Segii Shulga on 12/30/15. +// Copyright © 2015 Krunoslav Zaher. All rights reserved. +// + +#if os(iOS) || os(tvOS) + import RxSwift + import UIKit + + extension Reactive where Base: NSTextStorage { + + /// Reactive wrapper for `delegate`. + /// + /// For more information take a look at `DelegateProxyType` protocol documentation. + public var delegate: DelegateProxy { + return RxTextStorageDelegateProxy.proxy(for: base) + } + + /// Reactive wrapper for `delegate` message. + public var didProcessEditingRangeChangeInLength: Observable<(editedMask: NSTextStorage.EditActions, editedRange: NSRange, delta: Int)> { + return delegate + .methodInvoked(#selector(NSTextStorageDelegate.textStorage(_:didProcessEditing:range:changeInLength:))) + .map { a in + let editedMask = NSTextStorage.EditActions(rawValue: try castOrThrow(UInt.self, a[1]) ) + let editedRange = try castOrThrow(NSValue.self, a[2]).rangeValue + let delta = try castOrThrow(Int.self, a[3]) + + return (editedMask, editedRange, delta) + } + } + } +#endif diff --git a/Pods/RxCocoa/RxCocoa/iOS/Protocols/RxCollectionViewDataSourceType.swift b/Pods/RxCocoa/RxCocoa/iOS/Protocols/RxCollectionViewDataSourceType.swift new file mode 100644 index 0000000..b098a9e --- /dev/null +++ b/Pods/RxCocoa/RxCocoa/iOS/Protocols/RxCollectionViewDataSourceType.swift @@ -0,0 +1,27 @@ +// +// RxCollectionViewDataSourceType.swift +// RxCocoa +// +// Created by Krunoslav Zaher on 6/29/15. +// Copyright © 2015 Krunoslav Zaher. All rights reserved. +// + +#if os(iOS) || os(tvOS) + +import UIKit +import RxSwift + +/// Marks data source as `UICollectionView` reactive data source enabling it to be used with one of the `bindTo` methods. +public protocol RxCollectionViewDataSourceType /*: UICollectionViewDataSource*/ { + + /// Type of elements that can be bound to collection view. + associatedtype Element + + /// New observable sequence event observed. + /// + /// - parameter collectionView: Bound collection view. + /// - parameter observedEvent: Event + func collectionView(_ collectionView: UICollectionView, observedEvent: Event) +} + +#endif diff --git a/Pods/RxCocoa/RxCocoa/iOS/Protocols/RxPickerViewDataSourceType.swift b/Pods/RxCocoa/RxCocoa/iOS/Protocols/RxPickerViewDataSourceType.swift new file mode 100644 index 0000000..1f390bf --- /dev/null +++ b/Pods/RxCocoa/RxCocoa/iOS/Protocols/RxPickerViewDataSourceType.swift @@ -0,0 +1,26 @@ +// +// RxPickerViewDataSourceType.swift +// RxCocoa +// +// Created by Sergey Shulga on 05/07/2017. +// Copyright © 2017 Krunoslav Zaher. All rights reserved. +// + +#if os(iOS) + +import UIKit +import RxSwift + +/// Marks data source as `UIPickerView` reactive data source enabling it to be used with one of the `bindTo` methods. +public protocol RxPickerViewDataSourceType { + /// Type of elements that can be bound to picker view. + associatedtype Element + + /// New observable sequence event observed. + /// + /// - parameter pickerView: Bound picker view. + /// - parameter observedEvent: Event + func pickerView(_ pickerView: UIPickerView, observedEvent: Event) +} + +#endif diff --git a/Pods/RxCocoa/RxCocoa/iOS/Protocols/RxTableViewDataSourceType.swift b/Pods/RxCocoa/RxCocoa/iOS/Protocols/RxTableViewDataSourceType.swift new file mode 100644 index 0000000..d59af9e --- /dev/null +++ b/Pods/RxCocoa/RxCocoa/iOS/Protocols/RxTableViewDataSourceType.swift @@ -0,0 +1,27 @@ +// +// RxTableViewDataSourceType.swift +// RxCocoa +// +// Created by Krunoslav Zaher on 6/26/15. +// Copyright © 2015 Krunoslav Zaher. All rights reserved. +// + +#if os(iOS) || os(tvOS) + +import UIKit +import RxSwift + +/// Marks data source as `UITableView` reactive data source enabling it to be used with one of the `bindTo` methods. +public protocol RxTableViewDataSourceType /*: UITableViewDataSource*/ { + + /// Type of elements that can be bound to table view. + associatedtype Element + + /// New observable sequence event observed. + /// + /// - parameter tableView: Bound table view. + /// - parameter observedEvent: Event + func tableView(_ tableView: UITableView, observedEvent: Event) +} + +#endif diff --git a/Pods/RxCocoa/RxCocoa/iOS/Proxies/RxCollectionViewDataSourcePrefetchingProxy.swift b/Pods/RxCocoa/RxCocoa/iOS/Proxies/RxCollectionViewDataSourcePrefetchingProxy.swift new file mode 100644 index 0000000..5ddfda7 --- /dev/null +++ b/Pods/RxCocoa/RxCocoa/iOS/Proxies/RxCollectionViewDataSourcePrefetchingProxy.swift @@ -0,0 +1,92 @@ +// +// RxCollectionViewDataSourcePrefetchingProxy.swift +// RxCocoa +// +// Created by Rowan Livingstone on 2/15/18. +// Copyright © 2018 Krunoslav Zaher. All rights reserved. +// + +#if os(iOS) || os(tvOS) + +import UIKit +import RxSwift + +@available(iOS 10.0, tvOS 10.0, *) +extension UICollectionView: HasPrefetchDataSource { + public typealias PrefetchDataSource = UICollectionViewDataSourcePrefetching +} + +@available(iOS 10.0, tvOS 10.0, *) +private let collectionViewPrefetchDataSourceNotSet = CollectionViewPrefetchDataSourceNotSet() + +@available(iOS 10.0, tvOS 10.0, *) +private final class CollectionViewPrefetchDataSourceNotSet + : NSObject + , UICollectionViewDataSourcePrefetching { + + func collectionView(_ collectionView: UICollectionView, prefetchItemsAt indexPaths: [IndexPath]) {} + +} + +@available(iOS 10.0, tvOS 10.0, *) +open class RxCollectionViewDataSourcePrefetchingProxy + : DelegateProxy + , DelegateProxyType { + + /// Typed parent object. + public weak private(set) var collectionView: UICollectionView? + + /// - parameter collectionView: Parent object for delegate proxy. + public init(collectionView: ParentObject) { + self.collectionView = collectionView + super.init(parentObject: collectionView, delegateProxy: RxCollectionViewDataSourcePrefetchingProxy.self) + } + + // Register known implementations + public static func registerKnownImplementations() { + self.register { RxCollectionViewDataSourcePrefetchingProxy(collectionView: $0) } + } + + private var _prefetchItemsPublishSubject: PublishSubject<[IndexPath]>? + + /// Optimized version used for observing prefetch items callbacks. + internal var prefetchItemsPublishSubject: PublishSubject<[IndexPath]> { + if let subject = _prefetchItemsPublishSubject { + return subject + } + + let subject = PublishSubject<[IndexPath]>() + _prefetchItemsPublishSubject = subject + + return subject + } + + private weak var _requiredMethodsPrefetchDataSource: UICollectionViewDataSourcePrefetching? = collectionViewPrefetchDataSourceNotSet + + /// For more information take a look at `DelegateProxyType`. + open override func setForwardToDelegate(_ forwardToDelegate: UICollectionViewDataSourcePrefetching?, retainDelegate: Bool) { + _requiredMethodsPrefetchDataSource = forwardToDelegate ?? collectionViewPrefetchDataSourceNotSet + super.setForwardToDelegate(forwardToDelegate, retainDelegate: retainDelegate) + } + + deinit { + if let subject = _prefetchItemsPublishSubject { + subject.on(.completed) + } + } + +} + +@available(iOS 10.0, tvOS 10.0, *) +extension RxCollectionViewDataSourcePrefetchingProxy: UICollectionViewDataSourcePrefetching { + /// Required delegate method implementation. + public func collectionView(_ collectionView: UICollectionView, prefetchItemsAt indexPaths: [IndexPath]) { + if let subject = _prefetchItemsPublishSubject { + subject.on(.next(indexPaths)) + } + + (_requiredMethodsPrefetchDataSource ?? collectionViewPrefetchDataSourceNotSet).collectionView(collectionView, prefetchItemsAt: indexPaths) + } +} + +#endif diff --git a/Pods/RxCocoa/RxCocoa/iOS/Proxies/RxCollectionViewDataSourceProxy.swift b/Pods/RxCocoa/RxCocoa/iOS/Proxies/RxCollectionViewDataSourceProxy.swift new file mode 100644 index 0000000..534b6fa --- /dev/null +++ b/Pods/RxCocoa/RxCocoa/iOS/Proxies/RxCollectionViewDataSourceProxy.swift @@ -0,0 +1,75 @@ +// +// RxCollectionViewDataSourceProxy.swift +// RxCocoa +// +// Created by Krunoslav Zaher on 6/29/15. +// Copyright © 2015 Krunoslav Zaher. All rights reserved. +// + +#if os(iOS) || os(tvOS) + +import UIKit +import RxSwift + +extension UICollectionView: HasDataSource { + public typealias DataSource = UICollectionViewDataSource +} + +private let collectionViewDataSourceNotSet = CollectionViewDataSourceNotSet() + +private final class CollectionViewDataSourceNotSet + : NSObject + , UICollectionViewDataSource { + + func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int { + 0 + } + + // The cell that is returned must be retrieved from a call to -dequeueReusableCellWithReuseIdentifier:forIndexPath: + func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell { + rxAbstractMethod(message: dataSourceNotSet) + } + +} + +/// For more information take a look at `DelegateProxyType`. +open class RxCollectionViewDataSourceProxy + : DelegateProxy + , DelegateProxyType { + + /// Typed parent object. + public weak private(set) var collectionView: UICollectionView? + + /// - parameter collectionView: Parent object for delegate proxy. + public init(collectionView: ParentObject) { + self.collectionView = collectionView + super.init(parentObject: collectionView, delegateProxy: RxCollectionViewDataSourceProxy.self) + } + + // Register known implementations + public static func registerKnownImplementations() { + self.register { RxCollectionViewDataSourceProxy(collectionView: $0) } + } + + private weak var _requiredMethodsDataSource: UICollectionViewDataSource? = collectionViewDataSourceNotSet + + /// For more information take a look at `DelegateProxyType`. + open override func setForwardToDelegate(_ forwardToDelegate: UICollectionViewDataSource?, retainDelegate: Bool) { + _requiredMethodsDataSource = forwardToDelegate ?? collectionViewDataSourceNotSet + super.setForwardToDelegate(forwardToDelegate, retainDelegate: retainDelegate) + } +} + +extension RxCollectionViewDataSourceProxy: UICollectionViewDataSource { + /// Required delegate method implementation. + public func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int { + (_requiredMethodsDataSource ?? collectionViewDataSourceNotSet).collectionView(collectionView, numberOfItemsInSection: section) + } + + /// Required delegate method implementation. + public func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell { + (_requiredMethodsDataSource ?? collectionViewDataSourceNotSet).collectionView(collectionView, cellForItemAt: indexPath) + } +} + +#endif diff --git a/Pods/RxCocoa/RxCocoa/iOS/Proxies/RxCollectionViewDelegateProxy.swift b/Pods/RxCocoa/RxCocoa/iOS/Proxies/RxCollectionViewDelegateProxy.swift new file mode 100644 index 0000000..da04caa --- /dev/null +++ b/Pods/RxCocoa/RxCocoa/iOS/Proxies/RxCollectionViewDelegateProxy.swift @@ -0,0 +1,32 @@ +// +// RxCollectionViewDelegateProxy.swift +// RxCocoa +// +// Created by Krunoslav Zaher on 6/29/15. +// Copyright © 2015 Krunoslav Zaher. All rights reserved. +// + +#if os(iOS) || os(tvOS) + +import UIKit +import RxSwift + +/// For more information take a look at `DelegateProxyType`. +open class RxCollectionViewDelegateProxy + : RxScrollViewDelegateProxy { + + /// Typed parent object. + public weak private(set) var collectionView: UICollectionView? + + /// Initializes `RxCollectionViewDelegateProxy` + /// + /// - parameter collectionView: Parent object for delegate proxy. + public init(collectionView: UICollectionView) { + self.collectionView = collectionView + super.init(scrollView: collectionView) + } +} + +extension RxCollectionViewDelegateProxy: UICollectionViewDelegateFlowLayout {} + +#endif diff --git a/Pods/RxCocoa/RxCocoa/iOS/Proxies/RxNavigationControllerDelegateProxy.swift b/Pods/RxCocoa/RxCocoa/iOS/Proxies/RxNavigationControllerDelegateProxy.swift new file mode 100644 index 0000000..b4a827e --- /dev/null +++ b/Pods/RxCocoa/RxCocoa/iOS/Proxies/RxNavigationControllerDelegateProxy.swift @@ -0,0 +1,39 @@ +// +// RxNavigationControllerDelegateProxy.swift +// RxCocoa +// +// Created by Diogo on 13/04/17. +// Copyright © 2017 Krunoslav Zaher. All rights reserved. +// + +#if os(iOS) || os(tvOS) + + import UIKit + import RxSwift + + extension UINavigationController: HasDelegate { + public typealias Delegate = UINavigationControllerDelegate + } + + /// For more information take a look at `DelegateProxyType`. + open class RxNavigationControllerDelegateProxy + : DelegateProxy + , DelegateProxyType { + + /// Typed parent object. + public weak private(set) var navigationController: UINavigationController? + + /// - parameter navigationController: Parent object for delegate proxy. + public init(navigationController: ParentObject) { + self.navigationController = navigationController + super.init(parentObject: navigationController, delegateProxy: RxNavigationControllerDelegateProxy.self) + } + + // Register known implementations + public static func registerKnownImplementations() { + self.register { RxNavigationControllerDelegateProxy(navigationController: $0) } + } + } + + extension RxNavigationControllerDelegateProxy: UINavigationControllerDelegate {} +#endif diff --git a/Pods/RxCocoa/RxCocoa/iOS/Proxies/RxPickerViewDataSourceProxy.swift b/Pods/RxCocoa/RxCocoa/iOS/Proxies/RxPickerViewDataSourceProxy.swift new file mode 100644 index 0000000..ecd0288 --- /dev/null +++ b/Pods/RxCocoa/RxCocoa/iOS/Proxies/RxPickerViewDataSourceProxy.swift @@ -0,0 +1,72 @@ +// +// RxPickerViewDataSourceProxy.swift +// RxCocoa +// +// Created by Sergey Shulga on 05/07/2017. +// Copyright © 2017 Krunoslav Zaher. All rights reserved. +// + +#if os(iOS) + +import UIKit +import RxSwift + +extension UIPickerView: HasDataSource { + public typealias DataSource = UIPickerViewDataSource +} + +private let pickerViewDataSourceNotSet = PickerViewDataSourceNotSet() + +final private class PickerViewDataSourceNotSet: NSObject, UIPickerViewDataSource { + func numberOfComponents(in pickerView: UIPickerView) -> Int { + 0 + } + + func pickerView(_ pickerView: UIPickerView, numberOfRowsInComponent component: Int) -> Int { + 0 + } +} + +/// For more information take a look at `DelegateProxyType`. +public class RxPickerViewDataSourceProxy + : DelegateProxy + , DelegateProxyType { + + /// Typed parent object. + public weak private(set) var pickerView: UIPickerView? + + /// - parameter pickerView: Parent object for delegate proxy. + public init(pickerView: ParentObject) { + self.pickerView = pickerView + super.init(parentObject: pickerView, delegateProxy: RxPickerViewDataSourceProxy.self) + } + + // Register known implementations + public static func registerKnownImplementations() { + self.register { RxPickerViewDataSourceProxy(pickerView: $0) } + } + + private weak var _requiredMethodsDataSource: UIPickerViewDataSource? = pickerViewDataSourceNotSet + + /// For more information take a look at `DelegateProxyType`. + public override func setForwardToDelegate(_ forwardToDelegate: UIPickerViewDataSource?, retainDelegate: Bool) { + _requiredMethodsDataSource = forwardToDelegate ?? pickerViewDataSourceNotSet + super.setForwardToDelegate(forwardToDelegate, retainDelegate: retainDelegate) + } +} + +// MARK: UIPickerViewDataSource + +extension RxPickerViewDataSourceProxy: UIPickerViewDataSource { + /// Required delegate method implementation. + public func numberOfComponents(in pickerView: UIPickerView) -> Int { + (_requiredMethodsDataSource ?? pickerViewDataSourceNotSet).numberOfComponents(in: pickerView) + } + + /// Required delegate method implementation. + public func pickerView(_ pickerView: UIPickerView, numberOfRowsInComponent component: Int) -> Int { + (_requiredMethodsDataSource ?? pickerViewDataSourceNotSet).pickerView(pickerView, numberOfRowsInComponent: component) + } +} + +#endif diff --git a/Pods/RxCocoa/RxCocoa/iOS/Proxies/RxPickerViewDelegateProxy.swift b/Pods/RxCocoa/RxCocoa/iOS/Proxies/RxPickerViewDelegateProxy.swift new file mode 100644 index 0000000..9e64f01 --- /dev/null +++ b/Pods/RxCocoa/RxCocoa/iOS/Proxies/RxPickerViewDelegateProxy.swift @@ -0,0 +1,38 @@ +// +// RxPickerViewDelegateProxy.swift +// RxCocoa +// +// Created by Segii Shulga on 5/12/16. +// Copyright © 2016 Krunoslav Zaher. All rights reserved. +// + +#if os(iOS) + + import RxSwift + import UIKit + + extension UIPickerView: HasDelegate { + public typealias Delegate = UIPickerViewDelegate + } + + open class RxPickerViewDelegateProxy + : DelegateProxy + , DelegateProxyType { + + /// Typed parent object. + public weak private(set) var pickerView: UIPickerView? + + /// - parameter pickerView: Parent object for delegate proxy. + public init(pickerView: ParentObject) { + self.pickerView = pickerView + super.init(parentObject: pickerView, delegateProxy: RxPickerViewDelegateProxy.self) + } + + // Register known implementations + public static func registerKnownImplementations() { + self.register { RxPickerViewDelegateProxy(pickerView: $0) } + } + } + + extension RxPickerViewDelegateProxy: UIPickerViewDelegate {} +#endif diff --git a/Pods/RxCocoa/RxCocoa/iOS/Proxies/RxScrollViewDelegateProxy.swift b/Pods/RxCocoa/RxCocoa/iOS/Proxies/RxScrollViewDelegateProxy.swift new file mode 100644 index 0000000..02e7592 --- /dev/null +++ b/Pods/RxCocoa/RxCocoa/iOS/Proxies/RxScrollViewDelegateProxy.swift @@ -0,0 +1,91 @@ +// +// RxScrollViewDelegateProxy.swift +// RxCocoa +// +// Created by Krunoslav Zaher on 6/19/15. +// Copyright © 2015 Krunoslav Zaher. All rights reserved. +// + +#if os(iOS) || os(tvOS) + +import RxSwift +import UIKit + +extension UIScrollView: HasDelegate { + public typealias Delegate = UIScrollViewDelegate +} + +/// For more information take a look at `DelegateProxyType`. +open class RxScrollViewDelegateProxy + : DelegateProxy + , DelegateProxyType { + + /// Typed parent object. + public weak private(set) var scrollView: UIScrollView? + + /// - parameter scrollView: Parent object for delegate proxy. + public init(scrollView: ParentObject) { + self.scrollView = scrollView + super.init(parentObject: scrollView, delegateProxy: RxScrollViewDelegateProxy.self) + } + + // Register known implementations + public static func registerKnownImplementations() { + self.register { RxScrollViewDelegateProxy(scrollView: $0) } + self.register { RxTableViewDelegateProxy(tableView: $0) } + self.register { RxCollectionViewDelegateProxy(collectionView: $0) } + self.register { RxTextViewDelegateProxy(textView: $0) } + } + + private var _contentOffsetBehaviorSubject: BehaviorSubject? + private var _contentOffsetPublishSubject: PublishSubject<()>? + + /// Optimized version used for observing content offset changes. + internal var contentOffsetBehaviorSubject: BehaviorSubject { + if let subject = _contentOffsetBehaviorSubject { + return subject + } + + let subject = BehaviorSubject(value: self.scrollView?.contentOffset ?? CGPoint.zero) + _contentOffsetBehaviorSubject = subject + + return subject + } + + /// Optimized version used for observing content offset changes. + internal var contentOffsetPublishSubject: PublishSubject<()> { + if let subject = _contentOffsetPublishSubject { + return subject + } + + let subject = PublishSubject<()>() + _contentOffsetPublishSubject = subject + + return subject + } + + deinit { + if let subject = _contentOffsetBehaviorSubject { + subject.on(.completed) + } + + if let subject = _contentOffsetPublishSubject { + subject.on(.completed) + } + } +} + +extension RxScrollViewDelegateProxy: UIScrollViewDelegate { + /// For more information take a look at `DelegateProxyType`. + public func scrollViewDidScroll(_ scrollView: UIScrollView) { + if let subject = _contentOffsetBehaviorSubject { + subject.on(.next(scrollView.contentOffset)) + } + if let subject = _contentOffsetPublishSubject { + subject.on(.next(())) + } + self._forwardToDelegate?.scrollViewDidScroll?(scrollView) + } +} + +#endif diff --git a/Pods/RxCocoa/RxCocoa/iOS/Proxies/RxSearchBarDelegateProxy.swift b/Pods/RxCocoa/RxCocoa/iOS/Proxies/RxSearchBarDelegateProxy.swift new file mode 100644 index 0000000..94bd30b --- /dev/null +++ b/Pods/RxCocoa/RxCocoa/iOS/Proxies/RxSearchBarDelegateProxy.swift @@ -0,0 +1,40 @@ +// +// RxSearchBarDelegateProxy.swift +// RxCocoa +// +// Created by Krunoslav Zaher on 7/4/15. +// Copyright © 2015 Krunoslav Zaher. All rights reserved. +// + +#if os(iOS) || os(tvOS) + +import UIKit +import RxSwift + +extension UISearchBar: HasDelegate { + public typealias Delegate = UISearchBarDelegate +} + +/// For more information take a look at `DelegateProxyType`. +open class RxSearchBarDelegateProxy + : DelegateProxy + , DelegateProxyType { + + /// Typed parent object. + public weak private(set) var searchBar: UISearchBar? + + /// - parameter searchBar: Parent object for delegate proxy. + public init(searchBar: ParentObject) { + self.searchBar = searchBar + super.init(parentObject: searchBar, delegateProxy: RxSearchBarDelegateProxy.self) + } + + // Register known implementations + public static func registerKnownImplementations() { + self.register { RxSearchBarDelegateProxy(searchBar: $0) } + } +} + +extension RxSearchBarDelegateProxy: UISearchBarDelegate {} + +#endif diff --git a/Pods/RxCocoa/RxCocoa/iOS/Proxies/RxSearchControllerDelegateProxy.swift b/Pods/RxCocoa/RxCocoa/iOS/Proxies/RxSearchControllerDelegateProxy.swift new file mode 100644 index 0000000..64e36a2 --- /dev/null +++ b/Pods/RxCocoa/RxCocoa/iOS/Proxies/RxSearchControllerDelegateProxy.swift @@ -0,0 +1,40 @@ +// +// RxSearchControllerDelegateProxy.swift +// RxCocoa +// +// Created by Segii Shulga on 3/17/16. +// Copyright © 2016 Krunoslav Zaher. All rights reserved. +// + +#if os(iOS) + +import RxSwift +import UIKit + +extension UISearchController: HasDelegate { + public typealias Delegate = UISearchControllerDelegate +} + +/// For more information take a look at `DelegateProxyType`. +open class RxSearchControllerDelegateProxy + : DelegateProxy + , DelegateProxyType { + + /// Typed parent object. + public weak private(set) var searchController: UISearchController? + + /// - parameter searchController: Parent object for delegate proxy. + public init(searchController: UISearchController) { + self.searchController = searchController + super.init(parentObject: searchController, delegateProxy: RxSearchControllerDelegateProxy.self) + } + + // Register known implementations + public static func registerKnownImplementations() { + self.register { RxSearchControllerDelegateProxy(searchController: $0) } + } +} + +extension RxSearchControllerDelegateProxy: UISearchControllerDelegate {} + +#endif diff --git a/Pods/RxCocoa/RxCocoa/iOS/Proxies/RxTabBarControllerDelegateProxy.swift b/Pods/RxCocoa/RxCocoa/iOS/Proxies/RxTabBarControllerDelegateProxy.swift new file mode 100644 index 0000000..62d42ac --- /dev/null +++ b/Pods/RxCocoa/RxCocoa/iOS/Proxies/RxTabBarControllerDelegateProxy.swift @@ -0,0 +1,40 @@ +// +// RxTabBarControllerDelegateProxy.swift +// RxCocoa +// +// Created by Yusuke Kita on 2016/12/07. +// Copyright © 2016 Krunoslav Zaher. All rights reserved. +// + +#if os(iOS) || os(tvOS) + +import UIKit +import RxSwift + +extension UITabBarController: HasDelegate { + public typealias Delegate = UITabBarControllerDelegate +} + +/// For more information take a look at `DelegateProxyType`. +open class RxTabBarControllerDelegateProxy + : DelegateProxy + , DelegateProxyType { + + /// Typed parent object. + public weak private(set) var tabBar: UITabBarController? + + /// - parameter tabBar: Parent object for delegate proxy. + public init(tabBar: ParentObject) { + self.tabBar = tabBar + super.init(parentObject: tabBar, delegateProxy: RxTabBarControllerDelegateProxy.self) + } + + // Register known implementations + public static func registerKnownImplementations() { + self.register { RxTabBarControllerDelegateProxy(tabBar: $0) } + } +} + +extension RxTabBarControllerDelegateProxy: UITabBarControllerDelegate {} + +#endif diff --git a/Pods/RxCocoa/RxCocoa/iOS/Proxies/RxTabBarDelegateProxy.swift b/Pods/RxCocoa/RxCocoa/iOS/Proxies/RxTabBarDelegateProxy.swift new file mode 100644 index 0000000..49c5cf7 --- /dev/null +++ b/Pods/RxCocoa/RxCocoa/iOS/Proxies/RxTabBarDelegateProxy.swift @@ -0,0 +1,50 @@ +// +// RxTabBarDelegateProxy.swift +// RxCocoa +// +// Created by Jesse Farless on 5/14/16. +// Copyright © 2016 Krunoslav Zaher. All rights reserved. +// + +#if os(iOS) || os(tvOS) + +import UIKit +import RxSwift + +extension UITabBar: HasDelegate { + public typealias Delegate = UITabBarDelegate +} + +/// For more information take a look at `DelegateProxyType`. +open class RxTabBarDelegateProxy + : DelegateProxy + , DelegateProxyType { + + /// Typed parent object. + public weak private(set) var tabBar: UITabBar? + + /// - parameter tabBar: Parent object for delegate proxy. + public init(tabBar: ParentObject) { + self.tabBar = tabBar + super.init(parentObject: tabBar, delegateProxy: RxTabBarDelegateProxy.self) + } + + // Register known implementations + public static func registerKnownImplementations() { + self.register { RxTabBarDelegateProxy(tabBar: $0) } + } + + /// For more information take a look at `DelegateProxyType`. + open class func currentDelegate(for object: ParentObject) -> UITabBarDelegate? { + object.delegate + } + + /// For more information take a look at `DelegateProxyType`. + open class func setCurrentDelegate(_ delegate: UITabBarDelegate?, to object: ParentObject) { + object.delegate = delegate + } +} + +extension RxTabBarDelegateProxy: UITabBarDelegate {} + +#endif diff --git a/Pods/RxCocoa/RxCocoa/iOS/Proxies/RxTableViewDataSourcePrefetchingProxy.swift b/Pods/RxCocoa/RxCocoa/iOS/Proxies/RxTableViewDataSourcePrefetchingProxy.swift new file mode 100644 index 0000000..d0831f2 --- /dev/null +++ b/Pods/RxCocoa/RxCocoa/iOS/Proxies/RxTableViewDataSourcePrefetchingProxy.swift @@ -0,0 +1,93 @@ +// +// RxTableViewDataSourcePrefetchingProxy.swift +// RxCocoa +// +// Created by Rowan Livingstone on 2/15/18. +// Copyright © 2018 Krunoslav Zaher. All rights reserved. +// + +#if os(iOS) || os(tvOS) + +import UIKit +import RxSwift + +@available(iOS 10.0, tvOS 10.0, *) +extension UITableView: HasPrefetchDataSource { + public typealias PrefetchDataSource = UITableViewDataSourcePrefetching +} + +@available(iOS 10.0, tvOS 10.0, *) +private let tableViewPrefetchDataSourceNotSet = TableViewPrefetchDataSourceNotSet() + +@available(iOS 10.0, tvOS 10.0, *) +private final class TableViewPrefetchDataSourceNotSet + : NSObject + , UITableViewDataSourcePrefetching { + + func tableView(_ tableView: UITableView, prefetchRowsAt indexPaths: [IndexPath]) {} + +} + +@available(iOS 10.0, tvOS 10.0, *) +open class RxTableViewDataSourcePrefetchingProxy + : DelegateProxy + , DelegateProxyType { + + /// Typed parent object. + public weak private(set) var tableView: UITableView? + + /// - parameter tableView: Parent object for delegate proxy. + public init(tableView: ParentObject) { + self.tableView = tableView + super.init(parentObject: tableView, delegateProxy: RxTableViewDataSourcePrefetchingProxy.self) + } + + // Register known implementations + public static func registerKnownImplementations() { + self.register { RxTableViewDataSourcePrefetchingProxy(tableView: $0) } + } + + private var _prefetchRowsPublishSubject: PublishSubject<[IndexPath]>? + + /// Optimized version used for observing prefetch rows callbacks. + internal var prefetchRowsPublishSubject: PublishSubject<[IndexPath]> { + if let subject = _prefetchRowsPublishSubject { + return subject + } + + let subject = PublishSubject<[IndexPath]>() + _prefetchRowsPublishSubject = subject + + return subject + } + + private weak var _requiredMethodsPrefetchDataSource: UITableViewDataSourcePrefetching? = tableViewPrefetchDataSourceNotSet + + /// For more information take a look at `DelegateProxyType`. + open override func setForwardToDelegate(_ forwardToDelegate: UITableViewDataSourcePrefetching?, retainDelegate: Bool) { + _requiredMethodsPrefetchDataSource = forwardToDelegate ?? tableViewPrefetchDataSourceNotSet + super.setForwardToDelegate(forwardToDelegate, retainDelegate: retainDelegate) + } + + deinit { + if let subject = _prefetchRowsPublishSubject { + subject.on(.completed) + } + } + +} + +@available(iOS 10.0, tvOS 10.0, *) +extension RxTableViewDataSourcePrefetchingProxy: UITableViewDataSourcePrefetching { + /// Required delegate method implementation. + public func tableView(_ tableView: UITableView, prefetchRowsAt indexPaths: [IndexPath]) { + if let subject = _prefetchRowsPublishSubject { + subject.on(.next(indexPaths)) + } + + (_requiredMethodsPrefetchDataSource ?? tableViewPrefetchDataSourceNotSet).tableView(tableView, prefetchRowsAt: indexPaths) + } +} + +#endif + diff --git a/Pods/RxCocoa/RxCocoa/iOS/Proxies/RxTableViewDataSourceProxy.swift b/Pods/RxCocoa/RxCocoa/iOS/Proxies/RxTableViewDataSourceProxy.swift new file mode 100644 index 0000000..4c5e863 --- /dev/null +++ b/Pods/RxCocoa/RxCocoa/iOS/Proxies/RxTableViewDataSourceProxy.swift @@ -0,0 +1,73 @@ +// +// RxTableViewDataSourceProxy.swift +// RxCocoa +// +// Created by Krunoslav Zaher on 6/15/15. +// Copyright © 2015 Krunoslav Zaher. All rights reserved. +// + +#if os(iOS) || os(tvOS) + +import UIKit +import RxSwift + +extension UITableView: HasDataSource { + public typealias DataSource = UITableViewDataSource +} + +private let tableViewDataSourceNotSet = TableViewDataSourceNotSet() + +private final class TableViewDataSourceNotSet + : NSObject + , UITableViewDataSource { + + func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { + 0 + } + + func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { + rxAbstractMethod(message: dataSourceNotSet) + } +} + +/// For more information take a look at `DelegateProxyType`. +open class RxTableViewDataSourceProxy + : DelegateProxy + , DelegateProxyType { + + /// Typed parent object. + public weak private(set) var tableView: UITableView? + + /// - parameter tableView: Parent object for delegate proxy. + public init(tableView: UITableView) { + self.tableView = tableView + super.init(parentObject: tableView, delegateProxy: RxTableViewDataSourceProxy.self) + } + + // Register known implementations + public static func registerKnownImplementations() { + self.register { RxTableViewDataSourceProxy(tableView: $0) } + } + + private weak var _requiredMethodsDataSource: UITableViewDataSource? = tableViewDataSourceNotSet + + /// For more information take a look at `DelegateProxyType`. + open override func setForwardToDelegate(_ forwardToDelegate: UITableViewDataSource?, retainDelegate: Bool) { + _requiredMethodsDataSource = forwardToDelegate ?? tableViewDataSourceNotSet + super.setForwardToDelegate(forwardToDelegate, retainDelegate: retainDelegate) + } +} + +extension RxTableViewDataSourceProxy: UITableViewDataSource { + /// Required delegate method implementation. + public func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { + (_requiredMethodsDataSource ?? tableViewDataSourceNotSet).tableView(tableView, numberOfRowsInSection: section) + } + + /// Required delegate method implementation. + public func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { + (_requiredMethodsDataSource ?? tableViewDataSourceNotSet).tableView(tableView, cellForRowAt: indexPath) + } +} + +#endif diff --git a/Pods/RxCocoa/RxCocoa/iOS/Proxies/RxTableViewDelegateProxy.swift b/Pods/RxCocoa/RxCocoa/iOS/Proxies/RxTableViewDelegateProxy.swift new file mode 100644 index 0000000..901fe66 --- /dev/null +++ b/Pods/RxCocoa/RxCocoa/iOS/Proxies/RxTableViewDelegateProxy.swift @@ -0,0 +1,31 @@ +// +// RxTableViewDelegateProxy.swift +// RxCocoa +// +// Created by Krunoslav Zaher on 6/15/15. +// Copyright © 2015 Krunoslav Zaher. All rights reserved. +// + +#if os(iOS) || os(tvOS) + +import UIKit +import RxSwift + +/// For more information take a look at `DelegateProxyType`. +open class RxTableViewDelegateProxy + : RxScrollViewDelegateProxy { + + /// Typed parent object. + public weak private(set) var tableView: UITableView? + + /// - parameter tableView: Parent object for delegate proxy. + public init(tableView: UITableView) { + self.tableView = tableView + super.init(scrollView: tableView) + } + +} + +extension RxTableViewDelegateProxy: UITableViewDelegate {} + +#endif diff --git a/Pods/RxCocoa/RxCocoa/iOS/Proxies/RxTextStorageDelegateProxy.swift b/Pods/RxCocoa/RxCocoa/iOS/Proxies/RxTextStorageDelegateProxy.swift new file mode 100644 index 0000000..e8ff33f --- /dev/null +++ b/Pods/RxCocoa/RxCocoa/iOS/Proxies/RxTextStorageDelegateProxy.swift @@ -0,0 +1,38 @@ +// +// RxTextStorageDelegateProxy.swift +// RxCocoa +// +// Created by Segii Shulga on 12/30/15. +// Copyright © 2015 Krunoslav Zaher. All rights reserved. +// + +#if os(iOS) || os(tvOS) + + import RxSwift + import UIKit + + extension NSTextStorage: HasDelegate { + public typealias Delegate = NSTextStorageDelegate + } + + open class RxTextStorageDelegateProxy + : DelegateProxy + , DelegateProxyType { + + /// Typed parent object. + public weak private(set) var textStorage: NSTextStorage? + + /// - parameter textStorage: Parent object for delegate proxy. + public init(textStorage: NSTextStorage) { + self.textStorage = textStorage + super.init(parentObject: textStorage, delegateProxy: RxTextStorageDelegateProxy.self) + } + + // Register known implementations + public static func registerKnownImplementations() { + self.register { RxTextStorageDelegateProxy(textStorage: $0) } + } + } + + extension RxTextStorageDelegateProxy: NSTextStorageDelegate {} +#endif diff --git a/Pods/RxCocoa/RxCocoa/iOS/Proxies/RxTextViewDelegateProxy.swift b/Pods/RxCocoa/RxCocoa/iOS/Proxies/RxTextViewDelegateProxy.swift new file mode 100644 index 0000000..9d93424 --- /dev/null +++ b/Pods/RxCocoa/RxCocoa/iOS/Proxies/RxTextViewDelegateProxy.swift @@ -0,0 +1,42 @@ +// +// RxTextViewDelegateProxy.swift +// RxCocoa +// +// Created by Yuta ToKoRo on 7/19/15. +// Copyright © 2015 Krunoslav Zaher. All rights reserved. +// + +#if os(iOS) || os(tvOS) + +import UIKit +import RxSwift + +/// For more information take a look at `DelegateProxyType`. +open class RxTextViewDelegateProxy + : RxScrollViewDelegateProxy { + + /// Typed parent object. + public weak private(set) var textView: UITextView? + + /// - parameter textview: Parent object for delegate proxy. + public init(textView: UITextView) { + self.textView = textView + super.init(scrollView: textView) + } +} + +extension RxTextViewDelegateProxy: UITextViewDelegate { + /// For more information take a look at `DelegateProxyType`. + @objc open func textView(_ textView: UITextView, shouldChangeTextIn range: NSRange, replacementText text: String) -> Bool { + /** + We've had some issues with observing text changes. This is here just in case we need the same hack in future and that + we wouldn't need to change the public interface. + */ + let forwardToDelegate = self.forwardToDelegate() as? UITextViewDelegate + return forwardToDelegate?.textView?(textView, + shouldChangeTextIn: range, + replacementText: text) ?? true + } +} + +#endif diff --git a/Pods/RxCocoa/RxCocoa/iOS/Proxies/RxWKNavigationDelegateProxy.swift b/Pods/RxCocoa/RxCocoa/iOS/Proxies/RxWKNavigationDelegateProxy.swift new file mode 100644 index 0000000..0fa16b4 --- /dev/null +++ b/Pods/RxCocoa/RxCocoa/iOS/Proxies/RxWKNavigationDelegateProxy.swift @@ -0,0 +1,45 @@ +// +// RxWKNavigationDelegateProxy.swift +// RxCocoa +// +// Created by Giuseppe Lanza on 14/02/2020. +// Copyright © 2020 Krunoslav Zaher. All rights reserved. +// + +#if os(iOS) || os(macOS) + +import RxSwift +import WebKit + +@available(iOS 8.0, OSX 10.10, OSXApplicationExtension 10.10, *) +open class RxWKNavigationDelegateProxy + : DelegateProxy + , DelegateProxyType { + + /// Typed parent object. + public weak private(set) var webView: WKWebView? + + /// - parameter webView: Parent object for delegate proxy. + public init(webView: ParentObject) { + self.webView = webView + super.init(parentObject: webView, delegateProxy: RxWKNavigationDelegateProxy.self) + } + + // Register known implementations + public static func registerKnownImplementations() { + self.register { RxWKNavigationDelegateProxy(webView: $0) } + } + + public static func currentDelegate(for object: WKWebView) -> WKNavigationDelegate? { + object.navigationDelegate + } + + public static func setCurrentDelegate(_ delegate: WKNavigationDelegate?, to object: WKWebView) { + object.navigationDelegate = delegate + } +} + +@available(iOS 8.0, OSX 10.10, OSXApplicationExtension 10.10, *) +extension RxWKNavigationDelegateProxy: WKNavigationDelegate {} + +#endif diff --git a/Pods/RxCocoa/RxCocoa/iOS/UIActivityIndicatorView+Rx.swift b/Pods/RxCocoa/RxCocoa/iOS/UIActivityIndicatorView+Rx.swift new file mode 100644 index 0000000..ca2d4f1 --- /dev/null +++ b/Pods/RxCocoa/RxCocoa/iOS/UIActivityIndicatorView+Rx.swift @@ -0,0 +1,27 @@ +// +// UIActivityIndicatorView+Rx.swift +// RxCocoa +// +// Created by Ivan Persidskiy on 02/12/15. +// Copyright © 2015 Krunoslav Zaher. All rights reserved. +// + +#if os(iOS) || os(tvOS) + +import UIKit +import RxSwift + +extension Reactive where Base: UIActivityIndicatorView { + /// Bindable sink for `startAnimating()`, `stopAnimating()` methods. + public var isAnimating: Binder { + Binder(self.base) { activityIndicator, active in + if active { + activityIndicator.startAnimating() + } else { + activityIndicator.stopAnimating() + } + } + } +} + +#endif diff --git a/Pods/RxCocoa/RxCocoa/iOS/UIApplication+Rx.swift b/Pods/RxCocoa/RxCocoa/iOS/UIApplication+Rx.swift new file mode 100644 index 0000000..d776105 --- /dev/null +++ b/Pods/RxCocoa/RxCocoa/iOS/UIApplication+Rx.swift @@ -0,0 +1,106 @@ +// +// UIApplication+Rx.swift +// RxCocoa +// +// Created by Mads Bøgeskov on 18/01/16. +// Copyright © 2016 Krunoslav Zaher. All rights reserved. +// + +#if os(iOS) + +import UIKit +import RxSwift + +extension Reactive where Base: UIApplication { + /// Bindable sink for `isNetworkActivityIndicatorVisible`. + public var isNetworkActivityIndicatorVisible: Binder { + return Binder(self.base) { application, active in + application.isNetworkActivityIndicatorVisible = active + } + } + + /// Reactive wrapper for `UIApplication.didEnterBackgroundNotification` + public static var didEnterBackground: ControlEvent { + let source = NotificationCenter.default.rx.notification(UIApplication.didEnterBackgroundNotification).map { _ in } + + return ControlEvent(events: source) + } + + /// Reactive wrapper for `UIApplication.willEnterForegroundNotification` + public static var willEnterForeground: ControlEvent { + let source = NotificationCenter.default.rx.notification(UIApplication.willEnterForegroundNotification).map { _ in } + + return ControlEvent(events: source) + } + + /// Reactive wrapper for `UIApplication.didFinishLaunchingNotification` + public static var didFinishLaunching: ControlEvent { + let source = NotificationCenter.default.rx.notification(UIApplication.didFinishLaunchingNotification).map { _ in } + + return ControlEvent(events: source) + } + + /// Reactive wrapper for `UIApplication.didBecomeActiveNotification` + public static var didBecomeActive: ControlEvent { + let source = NotificationCenter.default.rx.notification(UIApplication.didBecomeActiveNotification).map { _ in } + + return ControlEvent(events: source) + } + + /// Reactive wrapper for `UIApplication.willResignActiveNotification` + public static var willResignActive: ControlEvent { + let source = NotificationCenter.default.rx.notification(UIApplication.willResignActiveNotification).map { _ in } + + return ControlEvent(events: source) + } + + /// Reactive wrapper for `UIApplication.didReceiveMemoryWarningNotification` + public static var didReceiveMemoryWarning: ControlEvent { + let source = NotificationCenter.default.rx.notification(UIApplication.didReceiveMemoryWarningNotification).map { _ in } + + return ControlEvent(events: source) + } + + /// Reactive wrapper for `UIApplication.willTerminateNotification` + public static var willTerminate: ControlEvent { + let source = NotificationCenter.default.rx.notification(UIApplication.willTerminateNotification).map { _ in } + + return ControlEvent(events: source) + } + + /// Reactive wrapper for `UIApplication.significantTimeChangeNotification` + public static var significantTimeChange: ControlEvent { + let source = NotificationCenter.default.rx.notification(UIApplication.significantTimeChangeNotification).map { _ in } + + return ControlEvent(events: source) + } + + /// Reactive wrapper for `UIApplication.backgroundRefreshStatusDidChangeNotification` + public static var backgroundRefreshStatusDidChange: ControlEvent { + let source = NotificationCenter.default.rx.notification(UIApplication.backgroundRefreshStatusDidChangeNotification).map { _ in } + + return ControlEvent(events: source) + } + + /// Reactive wrapper for `UIApplication.protectedDataWillBecomeUnavailableNotification` + public static var protectedDataWillBecomeUnavailable: ControlEvent { + let source = NotificationCenter.default.rx.notification(UIApplication.protectedDataWillBecomeUnavailableNotification).map { _ in } + + return ControlEvent(events: source) + } + + /// Reactive wrapper for `UIApplication.protectedDataDidBecomeAvailableNotification` + public static var protectedDataDidBecomeAvailable: ControlEvent { + let source = NotificationCenter.default.rx.notification(UIApplication.protectedDataDidBecomeAvailableNotification).map { _ in } + + return ControlEvent(events: source) + } + + /// Reactive wrapper for `UIApplication.userDidTakeScreenshotNotification` + public static var userDidTakeScreenshot: ControlEvent { + let source = NotificationCenter.default.rx.notification(UIApplication.userDidTakeScreenshotNotification).map { _ in } + + return ControlEvent(events: source) + } +} +#endif diff --git a/Pods/RxCocoa/RxCocoa/iOS/UIBarButtonItem+Rx.swift b/Pods/RxCocoa/RxCocoa/iOS/UIBarButtonItem+Rx.swift new file mode 100644 index 0000000..0bcaa99 --- /dev/null +++ b/Pods/RxCocoa/RxCocoa/iOS/UIBarButtonItem+Rx.swift @@ -0,0 +1,72 @@ +// +// UIBarButtonItem+Rx.swift +// RxCocoa +// +// Created by Daniel Tartaglia on 5/31/15. +// Copyright © 2015 Krunoslav Zaher. All rights reserved. +// + +#if os(iOS) || os(tvOS) + +import UIKit +import RxSwift + +private var rx_tap_key: UInt8 = 0 + +extension Reactive where Base: UIBarButtonItem { + /// Reactive wrapper for target action pattern on `self`. + public var tap: ControlEvent<()> { + let source = lazyInstanceObservable(&rx_tap_key) { () -> Observable<()> in + Observable.create { [weak control = self.base] observer in + guard let control = control else { + observer.on(.completed) + return Disposables.create() + } + let target = BarButtonItemTarget(barButtonItem: control) { + observer.on(.next(())) + } + return target + } + .take(until: self.deallocated) + .share() + } + + return ControlEvent(events: source) + } +} + + +@objc +final class BarButtonItemTarget: RxTarget { + typealias Callback = () -> Void + + weak var barButtonItem: UIBarButtonItem? + var callback: Callback! + + init(barButtonItem: UIBarButtonItem, callback: @escaping () -> Void) { + self.barButtonItem = barButtonItem + self.callback = callback + super.init() + barButtonItem.target = self + barButtonItem.action = #selector(BarButtonItemTarget.action(_:)) + } + + override func dispose() { + super.dispose() +#if DEBUG + MainScheduler.ensureRunningOnMainThread() +#endif + + barButtonItem?.target = nil + barButtonItem?.action = nil + + callback = nil + } + + @objc func action(_ sender: AnyObject) { + callback() + } + +} + +#endif diff --git a/Pods/RxCocoa/RxCocoa/iOS/UIButton+Rx.swift b/Pods/RxCocoa/RxCocoa/iOS/UIButton+Rx.swift new file mode 100644 index 0000000..4d0f4c3 --- /dev/null +++ b/Pods/RxCocoa/RxCocoa/iOS/UIButton+Rx.swift @@ -0,0 +1,82 @@ +// +// UIButton+Rx.swift +// RxCocoa +// +// Created by Krunoslav Zaher on 3/28/15. +// Copyright © 2015 Krunoslav Zaher. All rights reserved. +// + +#if os(iOS) + +import RxSwift +import UIKit + +extension Reactive where Base: UIButton { + + /// Reactive wrapper for `TouchUpInside` control event. + public var tap: ControlEvent { + controlEvent(.touchUpInside) + } +} + +#endif + +#if os(tvOS) + +import RxSwift +import UIKit + +extension Reactive where Base: UIButton { + + /// Reactive wrapper for `PrimaryActionTriggered` control event. + public var primaryAction: ControlEvent { + controlEvent(.primaryActionTriggered) + } + +} + +#endif + +#if os(iOS) || os(tvOS) + +import RxSwift +import UIKit + +extension Reactive where Base: UIButton { + /// Reactive wrapper for `setTitle(_:for:)` + public func title(for controlState: UIControl.State = []) -> Binder { + Binder(self.base) { button, title in + button.setTitle(title, for: controlState) + } + } + + /// Reactive wrapper for `setImage(_:for:)` + public func image(for controlState: UIControl.State = []) -> Binder { + Binder(self.base) { button, image in + button.setImage(image, for: controlState) + } + } + + /// Reactive wrapper for `setBackgroundImage(_:for:)` + public func backgroundImage(for controlState: UIControl.State = []) -> Binder { + Binder(self.base) { button, image in + button.setBackgroundImage(image, for: controlState) + } + } + +} +#endif + +#if os(iOS) || os(tvOS) + import RxSwift + import UIKit + + extension Reactive where Base: UIButton { + /// Reactive wrapper for `setAttributedTitle(_:controlState:)` + public func attributedTitle(for controlState: UIControl.State = []) -> Binder { + return Binder(self.base) { button, attributedTitle -> Void in + button.setAttributedTitle(attributedTitle, for: controlState) + } + } + } +#endif diff --git a/Pods/RxCocoa/RxCocoa/iOS/UICollectionView+Rx.swift b/Pods/RxCocoa/RxCocoa/iOS/UICollectionView+Rx.swift new file mode 100644 index 0000000..8f4bdb3 --- /dev/null +++ b/Pods/RxCocoa/RxCocoa/iOS/UICollectionView+Rx.swift @@ -0,0 +1,380 @@ +// +// UICollectionView+Rx.swift +// RxCocoa +// +// Created by Krunoslav Zaher on 4/2/15. +// Copyright © 2015 Krunoslav Zaher. All rights reserved. +// + +#if os(iOS) || os(tvOS) + +import RxSwift +import UIKit + +// Items + +extension Reactive where Base: UICollectionView { + + /** + Binds sequences of elements to collection view items. + + - parameter source: Observable sequence of items. + - parameter cellFactory: Transform between sequence elements and view cells. + - returns: Disposable object that can be used to unbind. + + Example + + let items = Observable.just([ + 1, + 2, + 3 + ]) + + items + .bind(to: collectionView.rx.items) { (collectionView, row, element) in + let indexPath = IndexPath(row: row, section: 0) + let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "Cell", for: indexPath) as! NumberCell + cell.value?.text = "\(element) @ \(row)" + return cell + } + .disposed(by: disposeBag) + */ + public func items + (_ source: Source) + -> (_ cellFactory: @escaping (UICollectionView, Int, Sequence.Element) -> UICollectionViewCell) + -> Disposable where Source.Element == Sequence { + return { cellFactory in + let dataSource = RxCollectionViewReactiveArrayDataSourceSequenceWrapper(cellFactory: cellFactory) + return self.items(dataSource: dataSource)(source) + } + + } + + /** + Binds sequences of elements to collection view items. + + - parameter cellIdentifier: Identifier used to dequeue cells. + - parameter source: Observable sequence of items. + - parameter configureCell: Transform between sequence elements and view cells. + - parameter cellType: Type of collection view cell. + - returns: Disposable object that can be used to unbind. + + Example + + let items = Observable.just([ + 1, + 2, + 3 + ]) + + items + .bind(to: collectionView.rx.items(cellIdentifier: "Cell", cellType: NumberCell.self)) { (row, element, cell) in + cell.value?.text = "\(element) @ \(row)" + } + .disposed(by: disposeBag) + */ + public func items + (cellIdentifier: String, cellType: Cell.Type = Cell.self) + -> (_ source: Source) + -> (_ configureCell: @escaping (Int, Sequence.Element, Cell) -> Void) + -> Disposable where Source.Element == Sequence { + return { source in + return { configureCell in + let dataSource = RxCollectionViewReactiveArrayDataSourceSequenceWrapper { cv, i, item in + let indexPath = IndexPath(item: i, section: 0) + let cell = cv.dequeueReusableCell(withReuseIdentifier: cellIdentifier, for: indexPath) as! Cell + configureCell(i, item, cell) + return cell + } + + return self.items(dataSource: dataSource)(source) + } + } + } + + + /** + Binds sequences of elements to collection view items using a custom reactive data used to perform the transformation. + + - parameter dataSource: Data source used to transform elements to view cells. + - parameter source: Observable sequence of items. + - returns: Disposable object that can be used to unbind. + + Example + + let dataSource = RxCollectionViewSectionedReloadDataSource>() + + let items = Observable.just([ + SectionModel(model: "First section", items: [ + 1.0, + 2.0, + 3.0 + ]), + SectionModel(model: "Second section", items: [ + 1.0, + 2.0, + 3.0 + ]), + SectionModel(model: "Third section", items: [ + 1.0, + 2.0, + 3.0 + ]) + ]) + + dataSource.configureCell = { (dataSource, cv, indexPath, element) in + let cell = cv.dequeueReusableCell(withReuseIdentifier: "Cell", for: indexPath) as! NumberCell + cell.value?.text = "\(element) @ row \(indexPath.row)" + return cell + } + + items + .bind(to: collectionView.rx.items(dataSource: dataSource)) + .disposed(by: disposeBag) + */ + public func items< + DataSource: RxCollectionViewDataSourceType & UICollectionViewDataSource, + Source: ObservableType> + (dataSource: DataSource) + -> (_ source: Source) + -> Disposable where DataSource.Element == Source.Element + { + return { source in + // This is called for side effects only, and to make sure delegate proxy is in place when + // data source is being bound. + // This is needed because theoretically the data source subscription itself might + // call `self.rx.delegate`. If that happens, it might cause weird side effects since + // setting data source will set delegate, and UICollectionView might get into a weird state. + // Therefore it's better to set delegate proxy first, just to be sure. + _ = self.delegate + // Strong reference is needed because data source is in use until result subscription is disposed + return source.subscribeProxyDataSource(ofObject: self.base, dataSource: dataSource, retainDataSource: true) { [weak collectionView = self.base] (_: RxCollectionViewDataSourceProxy, event) -> Void in + guard let collectionView = collectionView else { + return + } + dataSource.collectionView(collectionView, observedEvent: event) + } + } + } +} + +extension Reactive where Base: UICollectionView { + public typealias DisplayCollectionViewCellEvent = (cell: UICollectionViewCell, at: IndexPath) + public typealias DisplayCollectionViewSupplementaryViewEvent = (supplementaryView: UICollectionReusableView, elementKind: String, at: IndexPath) + + /// Reactive wrapper for `dataSource`. + /// + /// For more information take a look at `DelegateProxyType` protocol documentation. + public var dataSource: DelegateProxy { + RxCollectionViewDataSourceProxy.proxy(for: base) + } + + /// Installs data source as forwarding delegate on `rx.dataSource`. + /// Data source won't be retained. + /// + /// It enables using normal delegate mechanism with reactive delegate mechanism. + /// + /// - parameter dataSource: Data source object. + /// - returns: Disposable object that can be used to unbind the data source. + public func setDataSource(_ dataSource: UICollectionViewDataSource) + -> Disposable { + RxCollectionViewDataSourceProxy.installForwardDelegate(dataSource, retainDelegate: false, onProxyForObject: self.base) + } + + /// Reactive wrapper for `delegate` message `collectionView(_:didSelectItemAtIndexPath:)`. + public var itemSelected: ControlEvent { + let source = delegate.methodInvoked(#selector(UICollectionViewDelegate.collectionView(_:didSelectItemAt:))) + .map { a in + return try castOrThrow(IndexPath.self, a[1]) + } + + return ControlEvent(events: source) + } + + /// Reactive wrapper for `delegate` message `collectionView(_:didDeselectItemAtIndexPath:)`. + public var itemDeselected: ControlEvent { + let source = delegate.methodInvoked(#selector(UICollectionViewDelegate.collectionView(_:didDeselectItemAt:))) + .map { a in + return try castOrThrow(IndexPath.self, a[1]) + } + + return ControlEvent(events: source) + } + + /// Reactive wrapper for `delegate` message `collectionView(_:didHighlightItemAt:)`. + public var itemHighlighted: ControlEvent { + let source = delegate.methodInvoked(#selector(UICollectionViewDelegate.collectionView(_:didHighlightItemAt:))) + .map { a in + return try castOrThrow(IndexPath.self, a[1]) + } + + return ControlEvent(events: source) + } + + /// Reactive wrapper for `delegate` message `collectionView(_:didUnhighlightItemAt:)`. + public var itemUnhighlighted: ControlEvent { + let source = delegate.methodInvoked(#selector(UICollectionViewDelegate.collectionView(_:didUnhighlightItemAt:))) + .map { a in + return try castOrThrow(IndexPath.self, a[1]) + } + + return ControlEvent(events: source) + } + + /// Reactive wrapper for `delegate` message `collectionView:willDisplay:forItemAt:`. + public var willDisplayCell: ControlEvent { + let source: Observable = self.delegate.methodInvoked(#selector(UICollectionViewDelegate.collectionView(_:willDisplay:forItemAt:))) + .map { a in + return (try castOrThrow(UICollectionViewCell.self, a[1]), try castOrThrow(IndexPath.self, a[2])) + } + + return ControlEvent(events: source) + } + + /// Reactive wrapper for `delegate` message `collectionView(_:willDisplaySupplementaryView:forElementKind:at:)`. + public var willDisplaySupplementaryView: ControlEvent { + let source: Observable = self.delegate.methodInvoked(#selector(UICollectionViewDelegate.collectionView(_:willDisplaySupplementaryView:forElementKind:at:))) + .map { a in + return (try castOrThrow(UICollectionReusableView.self, a[1]), + try castOrThrow(String.self, a[2]), + try castOrThrow(IndexPath.self, a[3])) + } + + return ControlEvent(events: source) + } + + /// Reactive wrapper for `delegate` message `collectionView:didEndDisplaying:forItemAt:`. + public var didEndDisplayingCell: ControlEvent { + let source: Observable = self.delegate.methodInvoked(#selector(UICollectionViewDelegate.collectionView(_:didEndDisplaying:forItemAt:))) + .map { a in + return (try castOrThrow(UICollectionViewCell.self, a[1]), try castOrThrow(IndexPath.self, a[2])) + } + + return ControlEvent(events: source) + } + + /// Reactive wrapper for `delegate` message `collectionView(_:didEndDisplayingSupplementaryView:forElementOfKind:at:)`. + public var didEndDisplayingSupplementaryView: ControlEvent { + let source: Observable = self.delegate.methodInvoked(#selector(UICollectionViewDelegate.collectionView(_:didEndDisplayingSupplementaryView:forElementOfKind:at:))) + .map { a in + return (try castOrThrow(UICollectionReusableView.self, a[1]), + try castOrThrow(String.self, a[2]), + try castOrThrow(IndexPath.self, a[3])) + } + + return ControlEvent(events: source) + } + + /// Reactive wrapper for `delegate` message `collectionView(_:didSelectItemAtIndexPath:)`. + /// + /// It can be only used when one of the `rx.itemsWith*` methods is used to bind observable sequence, + /// or any other data source conforming to `SectionedViewDataSourceType` protocol. + /// + /// ``` + /// collectionView.rx.modelSelected(MyModel.self) + /// .map { ... + /// ``` + public func modelSelected(_ modelType: T.Type) -> ControlEvent { + let source: Observable = itemSelected.flatMap { [weak view = self.base as UICollectionView] indexPath -> Observable in + guard let view = view else { + return Observable.empty() + } + + return Observable.just(try view.rx.model(at: indexPath)) + } + + return ControlEvent(events: source) + } + + /// Reactive wrapper for `delegate` message `collectionView(_:didSelectItemAtIndexPath:)`. + /// + /// It can be only used when one of the `rx.itemsWith*` methods is used to bind observable sequence, + /// or any other data source conforming to `SectionedViewDataSourceType` protocol. + /// + /// ``` + /// collectionView.rx.modelDeselected(MyModel.self) + /// .map { ... + /// ``` + public func modelDeselected(_ modelType: T.Type) -> ControlEvent { + let source: Observable = itemDeselected.flatMap { [weak view = self.base as UICollectionView] indexPath -> Observable in + guard let view = view else { + return Observable.empty() + } + + return Observable.just(try view.rx.model(at: indexPath)) + } + + return ControlEvent(events: source) + } + + /// Synchronous helper method for retrieving a model at indexPath through a reactive data source + public func model(at indexPath: IndexPath) throws -> T { + let dataSource: SectionedViewDataSourceType = castOrFatalError(self.dataSource.forwardToDelegate(), message: "This method only works in case one of the `rx.itemsWith*` methods was used.") + + let element = try dataSource.model(at: indexPath) + + return try castOrThrow(T.self, element) + } +} + +@available(iOS 10.0, tvOS 10.0, *) +extension Reactive where Base: UICollectionView { + + /// Reactive wrapper for `prefetchDataSource`. + /// + /// For more information take a look at `DelegateProxyType` protocol documentation. + public var prefetchDataSource: DelegateProxy { + RxCollectionViewDataSourcePrefetchingProxy.proxy(for: base) + } + + /** + Installs prefetch data source as forwarding delegate on `rx.prefetchDataSource`. + Prefetch data source won't be retained. + + It enables using normal delegate mechanism with reactive delegate mechanism. + + - parameter prefetchDataSource: Prefetch data source object. + - returns: Disposable object that can be used to unbind the data source. + */ + public func setPrefetchDataSource(_ prefetchDataSource: UICollectionViewDataSourcePrefetching) + -> Disposable { + return RxCollectionViewDataSourcePrefetchingProxy.installForwardDelegate(prefetchDataSource, retainDelegate: false, onProxyForObject: self.base) + } + + /// Reactive wrapper for `prefetchDataSource` message `collectionView(_:prefetchItemsAt:)`. + public var prefetchItems: ControlEvent<[IndexPath]> { + let source = RxCollectionViewDataSourcePrefetchingProxy.proxy(for: base).prefetchItemsPublishSubject + return ControlEvent(events: source) + } + + /// Reactive wrapper for `prefetchDataSource` message `collectionView(_:cancelPrefetchingForItemsAt:)`. + public var cancelPrefetchingForItems: ControlEvent<[IndexPath]> { + let source = prefetchDataSource.methodInvoked(#selector(UICollectionViewDataSourcePrefetching.collectionView(_:cancelPrefetchingForItemsAt:))) + .map { a in + return try castOrThrow(Array.self, a[1]) + } + + return ControlEvent(events: source) + } + +} +#endif + +#if os(tvOS) + +extension Reactive where Base: UICollectionView { + + /// Reactive wrapper for `delegate` message `collectionView(_:didUpdateFocusInContext:withAnimationCoordinator:)`. + public var didUpdateFocusInContextWithAnimationCoordinator: ControlEvent<(context: UICollectionViewFocusUpdateContext, animationCoordinator: UIFocusAnimationCoordinator)> { + + let source = delegate.methodInvoked(#selector(UICollectionViewDelegate.collectionView(_:didUpdateFocusIn:with:))) + .map { a -> (context: UICollectionViewFocusUpdateContext, animationCoordinator: UIFocusAnimationCoordinator) in + let context = try castOrThrow(UICollectionViewFocusUpdateContext.self, a[1]) + let animationCoordinator = try castOrThrow(UIFocusAnimationCoordinator.self, a[2]) + return (context: context, animationCoordinator: animationCoordinator) + } + + return ControlEvent(events: source) + } +} +#endif diff --git a/Pods/RxCocoa/RxCocoa/iOS/UIControl+Rx.swift b/Pods/RxCocoa/RxCocoa/iOS/UIControl+Rx.swift new file mode 100644 index 0000000..6698cf2 --- /dev/null +++ b/Pods/RxCocoa/RxCocoa/iOS/UIControl+Rx.swift @@ -0,0 +1,86 @@ +// +// UIControl+Rx.swift +// RxCocoa +// +// Created by Daniel Tartaglia on 5/23/15. +// Copyright © 2015 Krunoslav Zaher. All rights reserved. +// + +#if os(iOS) || os(tvOS) + +import RxSwift +import UIKit + +extension Reactive where Base: UIControl { + /// Reactive wrapper for target action pattern. + /// + /// - parameter controlEvents: Filter for observed event types. + public func controlEvent(_ controlEvents: UIControl.Event) -> ControlEvent<()> { + let source: Observable = Observable.create { [weak control = self.base] observer in + MainScheduler.ensureRunningOnMainThread() + + guard let control = control else { + observer.on(.completed) + return Disposables.create() + } + + let controlTarget = ControlTarget(control: control, controlEvents: controlEvents) { _ in + observer.on(.next(())) + } + + return Disposables.create(with: controlTarget.dispose) + } + .take(until: deallocated) + + return ControlEvent(events: source) + } + + /// Creates a `ControlProperty` that is triggered by target/action pattern value updates. + /// + /// - parameter controlEvents: Events that trigger value update sequence elements. + /// - parameter getter: Property value getter. + /// - parameter setter: Property value setter. + public func controlProperty( + editingEvents: UIControl.Event, + getter: @escaping (Base) -> T, + setter: @escaping (Base, T) -> Void + ) -> ControlProperty { + let source: Observable = Observable.create { [weak weakControl = base] observer in + guard let control = weakControl else { + observer.on(.completed) + return Disposables.create() + } + + observer.on(.next(getter(control))) + + let controlTarget = ControlTarget(control: control, controlEvents: editingEvents) { _ in + if let control = weakControl { + observer.on(.next(getter(control))) + } + } + + return Disposables.create(with: controlTarget.dispose) + } + .take(until: deallocated) + + let bindingObserver = Binder(base, binding: setter) + + return ControlProperty(values: source, valueSink: bindingObserver) + } + + /// This is a separate method to better communicate to public consumers that + /// an `editingEvent` needs to fire for control property to be updated. + internal func controlPropertyWithDefaultEvents( + editingEvents: UIControl.Event = [.allEditingEvents, .valueChanged], + getter: @escaping (Base) -> T, + setter: @escaping (Base, T) -> Void + ) -> ControlProperty { + return controlProperty( + editingEvents: editingEvents, + getter: getter, + setter: setter + ) + } +} + +#endif diff --git a/Pods/RxCocoa/RxCocoa/iOS/UIDatePicker+Rx.swift b/Pods/RxCocoa/RxCocoa/iOS/UIDatePicker+Rx.swift new file mode 100644 index 0000000..e10c1ec --- /dev/null +++ b/Pods/RxCocoa/RxCocoa/iOS/UIDatePicker+Rx.swift @@ -0,0 +1,43 @@ +// +// UIDatePicker+Rx.swift +// RxCocoa +// +// Created by Daniel Tartaglia on 5/31/15. +// Copyright © 2015 Krunoslav Zaher. All rights reserved. +// + +#if os(iOS) + +import RxSwift +import UIKit + +extension Reactive where Base: UIDatePicker { + /// Reactive wrapper for `date` property. + public var date: ControlProperty { + value + } + + /// Reactive wrapper for `date` property. + public var value: ControlProperty { + return base.rx.controlPropertyWithDefaultEvents( + getter: { datePicker in + datePicker.date + }, setter: { datePicker, value in + datePicker.date = value + } + ) + } + + /// Reactive wrapper for `countDownDuration` property. + public var countDownDuration: ControlProperty { + return base.rx.controlPropertyWithDefaultEvents( + getter: { datePicker in + datePicker.countDownDuration + }, setter: { datePicker, value in + datePicker.countDownDuration = value + } + ) + } +} + +#endif diff --git a/Pods/RxCocoa/RxCocoa/iOS/UIGestureRecognizer+Rx.swift b/Pods/RxCocoa/RxCocoa/iOS/UIGestureRecognizer+Rx.swift new file mode 100644 index 0000000..5512900 --- /dev/null +++ b/Pods/RxCocoa/RxCocoa/iOS/UIGestureRecognizer+Rx.swift @@ -0,0 +1,75 @@ +// +// UIGestureRecognizer+Rx.swift +// RxCocoa +// +// Created by Carlos García on 10/6/15. +// Copyright © 2015 Krunoslav Zaher. All rights reserved. +// + +#if os(iOS) || os(tvOS) + +import UIKit +import RxSwift + +// This should be only used from `MainScheduler` +final class GestureTarget: RxTarget { + typealias Callback = (Recognizer) -> Void + + let selector = #selector(ControlTarget.eventHandler(_:)) + + weak var gestureRecognizer: Recognizer? + var callback: Callback? + + init(_ gestureRecognizer: Recognizer, callback: @escaping Callback) { + self.gestureRecognizer = gestureRecognizer + self.callback = callback + + super.init() + + gestureRecognizer.addTarget(self, action: selector) + + let method = self.method(for: selector) + if method == nil { + fatalError("Can't find method") + } + } + + @objc func eventHandler(_ sender: UIGestureRecognizer) { + if let callback = self.callback, let gestureRecognizer = self.gestureRecognizer { + callback(gestureRecognizer) + } + } + + override func dispose() { + super.dispose() + + self.gestureRecognizer?.removeTarget(self, action: self.selector) + self.callback = nil + } +} + +extension Reactive where Base: UIGestureRecognizer { + + /// Reactive wrapper for gesture recognizer events. + public var event: ControlEvent { + let source: Observable = Observable.create { [weak control = self.base] observer in + MainScheduler.ensureRunningOnMainThread() + + guard let control = control else { + observer.on(.completed) + return Disposables.create() + } + + let observer = GestureTarget(control) { control in + observer.on(.next(control)) + } + + return observer + }.take(until: deallocated) + + return ControlEvent(events: source) + } + +} + +#endif diff --git a/Pods/RxCocoa/RxCocoa/iOS/UINavigationController+Rx.swift b/Pods/RxCocoa/RxCocoa/iOS/UINavigationController+Rx.swift new file mode 100644 index 0000000..94796b6 --- /dev/null +++ b/Pods/RxCocoa/RxCocoa/iOS/UINavigationController+Rx.swift @@ -0,0 +1,49 @@ +// +// UINavigationController+Rx.swift +// RxCocoa +// +// Created by Diogo on 13/04/17. +// Copyright © 2017 Krunoslav Zaher. All rights reserved. +// + +#if os(iOS) || os(tvOS) + +import RxSwift +import UIKit + +extension Reactive where Base: UINavigationController { + public typealias ShowEvent = (viewController: UIViewController, animated: Bool) + + /// Reactive wrapper for `delegate`. + /// + /// For more information take a look at `DelegateProxyType` protocol documentation. + public var delegate: DelegateProxy { + RxNavigationControllerDelegateProxy.proxy(for: base) + } + + /// Reactive wrapper for delegate method `navigationController(:willShow:animated:)`. + public var willShow: ControlEvent { + let source: Observable = delegate + .methodInvoked(#selector(UINavigationControllerDelegate.navigationController(_:willShow:animated:))) + .map { arg in + let viewController = try castOrThrow(UIViewController.self, arg[1]) + let animated = try castOrThrow(Bool.self, arg[2]) + return (viewController, animated) + } + return ControlEvent(events: source) + } + + /// Reactive wrapper for delegate method `navigationController(:didShow:animated:)`. + public var didShow: ControlEvent { + let source: Observable = delegate + .methodInvoked(#selector(UINavigationControllerDelegate.navigationController(_:didShow:animated:))) + .map { arg in + let viewController = try castOrThrow(UIViewController.self, arg[1]) + let animated = try castOrThrow(Bool.self, arg[2]) + return (viewController, animated) + } + return ControlEvent(events: source) + } +} + +#endif diff --git a/Pods/RxCocoa/RxCocoa/iOS/UIPickerView+Rx.swift b/Pods/RxCocoa/RxCocoa/iOS/UIPickerView+Rx.swift new file mode 100644 index 0000000..317dc13 --- /dev/null +++ b/Pods/RxCocoa/RxCocoa/iOS/UIPickerView+Rx.swift @@ -0,0 +1,224 @@ +// +// UIPickerView+Rx.swift +// RxCocoa +// +// Created by Segii Shulga on 5/12/16. +// Copyright © 2016 Krunoslav Zaher. All rights reserved. +// + +#if os(iOS) + + import RxSwift + import UIKit + + extension Reactive where Base: UIPickerView { + + /// Reactive wrapper for `delegate`. + /// For more information take a look at `DelegateProxyType` protocol documentation. + public var delegate: DelegateProxy { + return RxPickerViewDelegateProxy.proxy(for: base) + } + + /// Installs delegate as forwarding delegate on `delegate`. + /// Delegate won't be retained. + /// + /// It enables using normal delegate mechanism with reactive delegate mechanism. + /// + /// - parameter delegate: Delegate object. + /// - returns: Disposable object that can be used to unbind the delegate. + public func setDelegate(_ delegate: UIPickerViewDelegate) + -> Disposable { + return RxPickerViewDelegateProxy.installForwardDelegate(delegate, retainDelegate: false, onProxyForObject: self.base) + } + + /** + Reactive wrapper for `dataSource`. + + For more information take a look at `DelegateProxyType` protocol documentation. + */ + public var dataSource: DelegateProxy { + return RxPickerViewDataSourceProxy.proxy(for: base) + } + + /** + Reactive wrapper for `delegate` message `pickerView:didSelectRow:inComponent:`. + */ + public var itemSelected: ControlEvent<(row: Int, component: Int)> { + let source = delegate + .methodInvoked(#selector(UIPickerViewDelegate.pickerView(_:didSelectRow:inComponent:))) + .map { + return (row: try castOrThrow(Int.self, $0[1]), component: try castOrThrow(Int.self, $0[2])) + } + return ControlEvent(events: source) + } + + /** + Reactive wrapper for `delegate` message `pickerView:didSelectRow:inComponent:`. + + It can be only used when one of the `rx.itemTitles, rx.itemAttributedTitles, items(_ source: O)` methods is used to bind observable sequence, + or any other data source conforming to a `ViewDataSourceType` protocol. + + ``` + pickerView.rx.modelSelected(MyModel.self) + .map { ... + ``` + - parameter modelType: Type of a Model which bound to the dataSource + */ + public func modelSelected(_ modelType: T.Type) -> ControlEvent<[T]> { + let source = itemSelected.flatMap { [weak view = self.base as UIPickerView] _, component -> Observable<[T]> in + guard let view = view else { + return Observable.empty() + } + + let model: [T] = try (0 ..< view.numberOfComponents).map { component in + let row = view.selectedRow(inComponent: component) + return try view.rx.model(at: IndexPath(row: row, section: component)) + } + + return Observable.just(model) + } + + return ControlEvent(events: source) + } + + /** + Binds sequences of elements to picker view rows. + + - parameter source: Observable sequence of items. + - parameter titleForRow: Transform between sequence elements and row titles. + - returns: Disposable object that can be used to unbind. + + Example: + + let items = Observable.just([ + "First Item", + "Second Item", + "Third Item" + ]) + + items + .bind(to: pickerView.rx.itemTitles) { (row, element) in + return element.title + } + .disposed(by: disposeBag) + + */ + + public func itemTitles + (_ source: Source) + -> (_ titleForRow: @escaping (Int, Sequence.Element) -> String?) + -> Disposable where Source.Element == Sequence { + return { titleForRow in + let adapter = RxStringPickerViewAdapter(titleForRow: titleForRow) + return self.items(adapter: adapter)(source) + } + } + + /** + Binds sequences of elements to picker view rows. + + - parameter source: Observable sequence of items. + - parameter attributedTitleForRow: Transform between sequence elements and row attributed titles. + - returns: Disposable object that can be used to unbind. + + Example: + + let items = Observable.just([ + "First Item", + "Second Item", + "Third Item" + ]) + + items + .bind(to: pickerView.rx.itemAttributedTitles) { (row, element) in + return NSAttributedString(string: element.title) + } + .disposed(by: disposeBag) + + */ + + public func itemAttributedTitles + (_ source: Source) + -> (_ attributedTitleForRow: @escaping (Int, Sequence.Element) -> NSAttributedString?) + -> Disposable where Source.Element == Sequence { + return { attributedTitleForRow in + let adapter = RxAttributedStringPickerViewAdapter(attributedTitleForRow: attributedTitleForRow) + return self.items(adapter: adapter)(source) + } + } + + /** + Binds sequences of elements to picker view rows. + + - parameter source: Observable sequence of items. + - parameter viewForRow: Transform between sequence elements and row views. + - returns: Disposable object that can be used to unbind. + + Example: + + let items = Observable.just([ + "First Item", + "Second Item", + "Third Item" + ]) + + items + .bind(to: pickerView.rx.items) { (row, element, view) in + guard let myView = view as? MyView else { + let view = MyView() + view.configure(with: element) + return view + } + myView.configure(with: element) + return myView + } + .disposed(by: disposeBag) + + */ + + public func items + (_ source: Source) + -> (_ viewForRow: @escaping (Int, Sequence.Element, UIView?) -> UIView) + -> Disposable where Source.Element == Sequence { + return { viewForRow in + let adapter = RxPickerViewAdapter(viewForRow: viewForRow) + return self.items(adapter: adapter)(source) + } + } + + /** + Binds sequences of elements to picker view rows using a custom reactive adapter used to perform the transformation. + This method will retain the adapter for as long as the subscription isn't disposed (result `Disposable` + being disposed). + In case `source` observable sequence terminates successfully, the adapter will present latest element + until the subscription isn't disposed. + + - parameter adapter: Adapter used to transform elements to picker components. + - parameter source: Observable sequence of items. + - returns: Disposable object that can be used to unbind. + */ + public func items(adapter: Adapter) + -> (_ source: Source) + -> Disposable where Source.Element == Adapter.Element { + return { source in + let delegateSubscription = self.setDelegate(adapter) + let dataSourceSubscription = source.subscribeProxyDataSource(ofObject: self.base, dataSource: adapter, retainDataSource: true, binding: { [weak pickerView = self.base] (_: RxPickerViewDataSourceProxy, event) in + guard let pickerView = pickerView else { return } + adapter.pickerView(pickerView, observedEvent: event) + }) + return Disposables.create(delegateSubscription, dataSourceSubscription) + } + } + + /** + Synchronous helper method for retrieving a model at indexPath through a reactive data source. + */ + public func model(at indexPath: IndexPath) throws -> T { + let dataSource: SectionedViewDataSourceType = castOrFatalError(self.dataSource.forwardToDelegate(), message: "This method only works in case one of the `rx.itemTitles, rx.itemAttributedTitles, items(_ source: O)` methods was used.") + + return castOrFatalError(try dataSource.model(at: indexPath)) + } + } + +#endif diff --git a/Pods/RxCocoa/RxCocoa/iOS/UIRefreshControl+Rx.swift b/Pods/RxCocoa/RxCocoa/iOS/UIRefreshControl+Rx.swift new file mode 100644 index 0000000..cdb10be --- /dev/null +++ b/Pods/RxCocoa/RxCocoa/iOS/UIRefreshControl+Rx.swift @@ -0,0 +1,28 @@ +// +// UIRefreshControl+Rx.swift +// RxCocoa +// +// Created by Yosuke Ishikawa on 1/31/16. +// Copyright © 2016 Krunoslav Zaher. All rights reserved. +// + +#if os(iOS) + +import UIKit +import RxSwift + +extension Reactive where Base: UIRefreshControl { + /// Bindable sink for `beginRefreshing()`, `endRefreshing()` methods. + public var isRefreshing: Binder { + return Binder(self.base) { refreshControl, refresh in + if refresh { + refreshControl.beginRefreshing() + } else { + refreshControl.endRefreshing() + } + } + } + +} + +#endif diff --git a/Pods/RxCocoa/RxCocoa/iOS/UIScrollView+Rx.swift b/Pods/RxCocoa/RxCocoa/iOS/UIScrollView+Rx.swift new file mode 100644 index 0000000..f90e1c2 --- /dev/null +++ b/Pods/RxCocoa/RxCocoa/iOS/UIScrollView+Rx.swift @@ -0,0 +1,131 @@ +// +// UIScrollView+Rx.swift +// RxCocoa +// +// Created by Krunoslav Zaher on 4/3/15. +// Copyright © 2015 Krunoslav Zaher. All rights reserved. +// + +#if os(iOS) || os(tvOS) + + import RxSwift + import UIKit + + extension Reactive where Base: UIScrollView { + public typealias EndZoomEvent = (view: UIView?, scale: CGFloat) + public typealias WillEndDraggingEvent = (velocity: CGPoint, targetContentOffset: UnsafeMutablePointer) + + /// Reactive wrapper for `delegate`. + /// + /// For more information take a look at `DelegateProxyType` protocol documentation. + public var delegate: DelegateProxy { + return RxScrollViewDelegateProxy.proxy(for: base) + } + + /// Reactive wrapper for `contentOffset`. + public var contentOffset: ControlProperty { + let proxy = RxScrollViewDelegateProxy.proxy(for: base) + + let bindingObserver = Binder(self.base) { scrollView, contentOffset in + scrollView.contentOffset = contentOffset + } + + return ControlProperty(values: proxy.contentOffsetBehaviorSubject, valueSink: bindingObserver) + } + + /// Reactive wrapper for delegate method `scrollViewDidScroll` + public var didScroll: ControlEvent { + let source = RxScrollViewDelegateProxy.proxy(for: base).contentOffsetPublishSubject + return ControlEvent(events: source) + } + + /// Reactive wrapper for delegate method `scrollViewWillBeginDecelerating` + public var willBeginDecelerating: ControlEvent { + let source = delegate.methodInvoked(#selector(UIScrollViewDelegate.scrollViewWillBeginDecelerating(_:))).map { _ in } + return ControlEvent(events: source) + } + + /// Reactive wrapper for delegate method `scrollViewDidEndDecelerating` + public var didEndDecelerating: ControlEvent { + let source = delegate.methodInvoked(#selector(UIScrollViewDelegate.scrollViewDidEndDecelerating(_:))).map { _ in } + return ControlEvent(events: source) + } + + /// Reactive wrapper for delegate method `scrollViewWillBeginDragging` + public var willBeginDragging: ControlEvent { + let source = delegate.methodInvoked(#selector(UIScrollViewDelegate.scrollViewWillBeginDragging(_:))).map { _ in } + return ControlEvent(events: source) + } + + /// Reactive wrapper for delegate method `scrollViewWillEndDragging(_:withVelocity:targetContentOffset:)` + public var willEndDragging: ControlEvent { + let source = delegate.methodInvoked(#selector(UIScrollViewDelegate.scrollViewWillEndDragging(_:withVelocity:targetContentOffset:))) + .map { value -> WillEndDraggingEvent in + let velocity = try castOrThrow(CGPoint.self, value[1]) + let targetContentOffsetValue = try castOrThrow(NSValue.self, value[2]) + + guard let rawPointer = targetContentOffsetValue.pointerValue else { throw RxCocoaError.unknown } + let typedPointer = rawPointer.bindMemory(to: CGPoint.self, capacity: MemoryLayout.size) + + return (velocity, typedPointer) + } + return ControlEvent(events: source) + } + + /// Reactive wrapper for delegate method `scrollViewDidEndDragging(_:willDecelerate:)` + public var didEndDragging: ControlEvent { + let source = delegate.methodInvoked(#selector(UIScrollViewDelegate.scrollViewDidEndDragging(_:willDecelerate:))).map { value -> Bool in + return try castOrThrow(Bool.self, value[1]) + } + return ControlEvent(events: source) + } + + /// Reactive wrapper for delegate method `scrollViewDidZoom` + public var didZoom: ControlEvent { + let source = delegate.methodInvoked(#selector(UIScrollViewDelegate.scrollViewDidZoom)).map { _ in } + return ControlEvent(events: source) + } + + + /// Reactive wrapper for delegate method `scrollViewDidScrollToTop` + public var didScrollToTop: ControlEvent { + let source = delegate.methodInvoked(#selector(UIScrollViewDelegate.scrollViewDidScrollToTop(_:))).map { _ in } + return ControlEvent(events: source) + } + + /// Reactive wrapper for delegate method `scrollViewDidEndScrollingAnimation` + public var didEndScrollingAnimation: ControlEvent { + let source = delegate.methodInvoked(#selector(UIScrollViewDelegate.scrollViewDidEndScrollingAnimation(_:))).map { _ in } + return ControlEvent(events: source) + } + + /// Reactive wrapper for delegate method `scrollViewWillBeginZooming(_:with:)` + public var willBeginZooming: ControlEvent { + let source = delegate.methodInvoked(#selector(UIScrollViewDelegate.scrollViewWillBeginZooming(_:with:))).map { value -> UIView? in + return try castOptionalOrThrow(UIView.self, value[1] as AnyObject) + } + return ControlEvent(events: source) + } + + /// Reactive wrapper for delegate method `scrollViewDidEndZooming(_:with:atScale:)` + public var didEndZooming: ControlEvent { + let source = delegate.methodInvoked(#selector(UIScrollViewDelegate.scrollViewDidEndZooming(_:with:atScale:))).map { value -> EndZoomEvent in + return (try castOptionalOrThrow(UIView.self, value[1] as AnyObject), try castOrThrow(CGFloat.self, value[2])) + } + return ControlEvent(events: source) + } + + /// Installs delegate as forwarding delegate on `delegate`. + /// Delegate won't be retained. + /// + /// It enables using normal delegate mechanism with reactive delegate mechanism. + /// + /// - parameter delegate: Delegate object. + /// - returns: Disposable object that can be used to unbind the delegate. + public func setDelegate(_ delegate: UIScrollViewDelegate) + -> Disposable { + return RxScrollViewDelegateProxy.installForwardDelegate(delegate, retainDelegate: false, onProxyForObject: self.base) + } + } + +#endif diff --git a/Pods/RxCocoa/RxCocoa/iOS/UISearchBar+Rx.swift b/Pods/RxCocoa/RxCocoa/iOS/UISearchBar+Rx.swift new file mode 100644 index 0000000..3892b1c --- /dev/null +++ b/Pods/RxCocoa/RxCocoa/iOS/UISearchBar+Rx.swift @@ -0,0 +1,136 @@ +// +// UISearchBar+Rx.swift +// RxCocoa +// +// Created by Krunoslav Zaher on 3/28/15. +// Copyright © 2015 Krunoslav Zaher. All rights reserved. +// + +#if os(iOS) || os(tvOS) + +import RxSwift +import UIKit + +extension Reactive where Base: UISearchBar { + + /// Reactive wrapper for `delegate`. + /// + /// For more information take a look at `DelegateProxyType` protocol documentation. + public var delegate: DelegateProxy { + RxSearchBarDelegateProxy.proxy(for: base) + } + + /// Reactive wrapper for `text` property. + public var text: ControlProperty { + value + } + + /// Reactive wrapper for `text` property. + public var value: ControlProperty { + let source: Observable = Observable.deferred { [weak searchBar = self.base as UISearchBar] () -> Observable in + let text = searchBar?.text + + let textDidChange = (searchBar?.rx.delegate.methodInvoked(#selector(UISearchBarDelegate.searchBar(_:textDidChange:))) ?? Observable.empty()) + let didEndEditing = (searchBar?.rx.delegate.methodInvoked(#selector(UISearchBarDelegate.searchBarTextDidEndEditing(_:))) ?? Observable.empty()) + + return Observable.merge(textDidChange, didEndEditing) + .map { _ in searchBar?.text ?? "" } + .startWith(text) + } + + let bindingObserver = Binder(self.base) { (searchBar, text: String?) in + searchBar.text = text + } + + return ControlProperty(values: source, valueSink: bindingObserver) + } + + /// Reactive wrapper for `selectedScopeButtonIndex` property. + public var selectedScopeButtonIndex: ControlProperty { + let source: Observable = Observable.deferred { [weak source = self.base as UISearchBar] () -> Observable in + let index = source?.selectedScopeButtonIndex ?? 0 + + return (source?.rx.delegate.methodInvoked(#selector(UISearchBarDelegate.searchBar(_:selectedScopeButtonIndexDidChange:))) ?? Observable.empty()) + .map { a in + return try castOrThrow(Int.self, a[1]) + } + .startWith(index) + } + + let bindingObserver = Binder(self.base) { (searchBar, index: Int) in + searchBar.selectedScopeButtonIndex = index + } + + return ControlProperty(values: source, valueSink: bindingObserver) + } + +#if os(iOS) + /// Reactive wrapper for delegate method `searchBarCancelButtonClicked`. + public var cancelButtonClicked: ControlEvent { + let source: Observable = self.delegate.methodInvoked(#selector(UISearchBarDelegate.searchBarCancelButtonClicked(_:))) + .map { _ in + return () + } + return ControlEvent(events: source) + } + + /// Reactive wrapper for delegate method `searchBarBookmarkButtonClicked`. + public var bookmarkButtonClicked: ControlEvent { + let source: Observable = self.delegate.methodInvoked(#selector(UISearchBarDelegate.searchBarBookmarkButtonClicked(_:))) + .map { _ in + return () + } + return ControlEvent(events: source) + } + + /// Reactive wrapper for delegate method `searchBarResultsListButtonClicked`. + public var resultsListButtonClicked: ControlEvent { + let source: Observable = self.delegate.methodInvoked(#selector(UISearchBarDelegate.searchBarResultsListButtonClicked(_:))) + .map { _ in + return () + } + return ControlEvent(events: source) + } +#endif + + /// Reactive wrapper for delegate method `searchBarSearchButtonClicked`. + public var searchButtonClicked: ControlEvent { + let source: Observable = self.delegate.methodInvoked(#selector(UISearchBarDelegate.searchBarSearchButtonClicked(_:))) + .map { _ in + return () + } + return ControlEvent(events: source) + } + + /// Reactive wrapper for delegate method `searchBarTextDidBeginEditing`. + public var textDidBeginEditing: ControlEvent { + let source: Observable = self.delegate.methodInvoked(#selector(UISearchBarDelegate.searchBarTextDidBeginEditing(_:))) + .map { _ in + return () + } + return ControlEvent(events: source) + } + + /// Reactive wrapper for delegate method `searchBarTextDidEndEditing`. + public var textDidEndEditing: ControlEvent { + let source: Observable = self.delegate.methodInvoked(#selector(UISearchBarDelegate.searchBarTextDidEndEditing(_:))) + .map { _ in + return () + } + return ControlEvent(events: source) + } + + /// Installs delegate as forwarding delegate on `delegate`. + /// Delegate won't be retained. + /// + /// It enables using normal delegate mechanism with reactive delegate mechanism. + /// + /// - parameter delegate: Delegate object. + /// - returns: Disposable object that can be used to unbind the delegate. + public func setDelegate(_ delegate: UISearchBarDelegate) + -> Disposable { + RxSearchBarDelegateProxy.installForwardDelegate(delegate, retainDelegate: false, onProxyForObject: self.base) + } +} + +#endif diff --git a/Pods/RxCocoa/RxCocoa/iOS/UISearchController+Rx.swift b/Pods/RxCocoa/RxCocoa/iOS/UISearchController+Rx.swift new file mode 100644 index 0000000..4f524a5 --- /dev/null +++ b/Pods/RxCocoa/RxCocoa/iOS/UISearchController+Rx.swift @@ -0,0 +1,58 @@ +// +// UISearchController+Rx.swift +// RxCocoa +// +// Created by Segii Shulga on 3/17/16. +// Copyright © 2016 Krunoslav Zaher. All rights reserved. +// + +#if os(iOS) + + import RxSwift + import UIKit + + extension Reactive where Base: UISearchController { + /// Reactive wrapper for `delegate`. + /// For more information take a look at `DelegateProxyType` protocol documentation. + public var delegate: DelegateProxy { + return RxSearchControllerDelegateProxy.proxy(for: base) + } + + /// Reactive wrapper for `delegate` message. + public var didDismiss: Observable { + return delegate + .methodInvoked( #selector(UISearchControllerDelegate.didDismissSearchController(_:))) + .map { _ in } + } + + /// Reactive wrapper for `delegate` message. + public var didPresent: Observable { + return delegate + .methodInvoked(#selector(UISearchControllerDelegate.didPresentSearchController(_:))) + .map { _ in } + } + + /// Reactive wrapper for `delegate` message. + public var present: Observable { + return delegate + .methodInvoked( #selector(UISearchControllerDelegate.presentSearchController(_:))) + .map { _ in } + } + + /// Reactive wrapper for `delegate` message. + public var willDismiss: Observable { + return delegate + .methodInvoked(#selector(UISearchControllerDelegate.willDismissSearchController(_:))) + .map { _ in } + } + + /// Reactive wrapper for `delegate` message. + public var willPresent: Observable { + return delegate + .methodInvoked( #selector(UISearchControllerDelegate.willPresentSearchController(_:))) + .map { _ in } + } + + } + +#endif diff --git a/Pods/RxCocoa/RxCocoa/iOS/UISegmentedControl+Rx.swift b/Pods/RxCocoa/RxCocoa/iOS/UISegmentedControl+Rx.swift new file mode 100644 index 0000000..1a62662 --- /dev/null +++ b/Pods/RxCocoa/RxCocoa/iOS/UISegmentedControl+Rx.swift @@ -0,0 +1,54 @@ +// +// UISegmentedControl+Rx.swift +// RxCocoa +// +// Created by Carlos García on 8/7/15. +// Copyright © 2015 Krunoslav Zaher. All rights reserved. +// + +#if os(iOS) || os(tvOS) + +import UIKit +import RxSwift + +extension Reactive where Base: UISegmentedControl { + /// Reactive wrapper for `selectedSegmentIndex` property. + public var selectedSegmentIndex: ControlProperty { + value + } + + /// Reactive wrapper for `selectedSegmentIndex` property. + public var value: ControlProperty { + return base.rx.controlPropertyWithDefaultEvents( + getter: { segmentedControl in + segmentedControl.selectedSegmentIndex + }, setter: { segmentedControl, value in + segmentedControl.selectedSegmentIndex = value + } + ) + } + + /// Reactive wrapper for `setEnabled(_:forSegmentAt:)` + public func enabledForSegment(at index: Int) -> Binder { + return Binder(self.base) { segmentedControl, segmentEnabled -> Void in + segmentedControl.setEnabled(segmentEnabled, forSegmentAt: index) + } + } + + /// Reactive wrapper for `setTitle(_:forSegmentAt:)` + public func titleForSegment(at index: Int) -> Binder { + return Binder(self.base) { segmentedControl, title -> Void in + segmentedControl.setTitle(title, forSegmentAt: index) + } + } + + /// Reactive wrapper for `setImage(_:forSegmentAt:)` + public func imageForSegment(at index: Int) -> Binder { + return Binder(self.base) { segmentedControl, image -> Void in + segmentedControl.setImage(image, forSegmentAt: index) + } + } + +} + +#endif diff --git a/Pods/RxCocoa/RxCocoa/iOS/UISlider+Rx.swift b/Pods/RxCocoa/RxCocoa/iOS/UISlider+Rx.swift new file mode 100644 index 0000000..07d4adb --- /dev/null +++ b/Pods/RxCocoa/RxCocoa/iOS/UISlider+Rx.swift @@ -0,0 +1,29 @@ +// +// UISlider+Rx.swift +// RxCocoa +// +// Created by Alexander van der Werff on 28/05/15. +// Copyright © 2015 Krunoslav Zaher. All rights reserved. +// + +#if os(iOS) + +import RxSwift +import UIKit + +extension Reactive where Base: UISlider { + + /// Reactive wrapper for `value` property. + public var value: ControlProperty { + return base.rx.controlPropertyWithDefaultEvents( + getter: { slider in + slider.value + }, setter: { slider, value in + slider.value = value + } + ) + } + +} + +#endif diff --git a/Pods/RxCocoa/RxCocoa/iOS/UIStepper+Rx.swift b/Pods/RxCocoa/RxCocoa/iOS/UIStepper+Rx.swift new file mode 100644 index 0000000..29f6386 --- /dev/null +++ b/Pods/RxCocoa/RxCocoa/iOS/UIStepper+Rx.swift @@ -0,0 +1,29 @@ +// +// UIStepper+Rx.swift +// RxCocoa +// +// Created by Yuta ToKoRo on 9/1/15. +// Copyright © 2015 Krunoslav Zaher. All rights reserved. +// + +#if os(iOS) + +import UIKit +import RxSwift + +extension Reactive where Base: UIStepper { + + /// Reactive wrapper for `value` property. + public var value: ControlProperty { + return base.rx.controlPropertyWithDefaultEvents( + getter: { stepper in + stepper.value + }, setter: { stepper, value in + stepper.value = value + } + ) + } +} + +#endif + diff --git a/Pods/RxCocoa/RxCocoa/iOS/UISwitch+Rx.swift b/Pods/RxCocoa/RxCocoa/iOS/UISwitch+Rx.swift new file mode 100644 index 0000000..6e116b3 --- /dev/null +++ b/Pods/RxCocoa/RxCocoa/iOS/UISwitch+Rx.swift @@ -0,0 +1,38 @@ +// +// UISwitch+Rx.swift +// RxCocoa +// +// Created by Carlos García on 8/7/15. +// Copyright © 2015 Krunoslav Zaher. All rights reserved. +// + +#if os(iOS) + +import UIKit +import RxSwift + +extension Reactive where Base: UISwitch { + + /// Reactive wrapper for `isOn` property. + public var isOn: ControlProperty { + value + } + + /// Reactive wrapper for `isOn` property. + /// + /// ⚠️ Versions prior to iOS 10.2 were leaking `UISwitch`'s, so on those versions + /// underlying observable sequence won't complete when nothing holds a strong reference + /// to `UISwitch`. + public var value: ControlProperty { + return base.rx.controlPropertyWithDefaultEvents( + getter: { uiSwitch in + uiSwitch.isOn + }, setter: { uiSwitch, value in + uiSwitch.isOn = value + } + ) + } + +} + +#endif diff --git a/Pods/RxCocoa/RxCocoa/iOS/UITabBar+Rx.swift b/Pods/RxCocoa/RxCocoa/iOS/UITabBar+Rx.swift new file mode 100644 index 0000000..e989667 --- /dev/null +++ b/Pods/RxCocoa/RxCocoa/iOS/UITabBar+Rx.swift @@ -0,0 +1,92 @@ +// +// UITabBar+Rx.swift +// RxCocoa +// +// Created by Jesse Farless on 5/13/16. +// Copyright © 2016 Krunoslav Zaher. All rights reserved. +// + +#if os(iOS) || os(tvOS) + +import UIKit +import RxSwift + +/** + iOS only + */ +#if os(iOS) +extension Reactive where Base: UITabBar { + + /// Reactive wrapper for `delegate` message `tabBar(_:willBeginCustomizing:)`. + public var willBeginCustomizing: ControlEvent<[UITabBarItem]> { + + let source = delegate.methodInvoked(#selector(UITabBarDelegate.tabBar(_:willBeginCustomizing:))) + .map { a in + return try castOrThrow([UITabBarItem].self, a[1]) + } + + return ControlEvent(events: source) + } + + /// Reactive wrapper for `delegate` message `tabBar(_:didBeginCustomizing:)`. + public var didBeginCustomizing: ControlEvent<[UITabBarItem]> { + let source = delegate.methodInvoked(#selector(UITabBarDelegate.tabBar(_:didBeginCustomizing:))) + .map { a in + return try castOrThrow([UITabBarItem].self, a[1]) + } + + return ControlEvent(events: source) + } + + /// Reactive wrapper for `delegate` message `tabBar(_:willEndCustomizing:changed:)`. + public var willEndCustomizing: ControlEvent<([UITabBarItem], Bool)> { + let source = delegate.methodInvoked(#selector(UITabBarDelegate.tabBar(_:willEndCustomizing:changed:))) + .map { (a: [Any]) -> (([UITabBarItem], Bool)) in + let items = try castOrThrow([UITabBarItem].self, a[1]) + let changed = try castOrThrow(Bool.self, a[2]) + return (items, changed) + } + + return ControlEvent(events: source) + } + + /// Reactive wrapper for `delegate` message `tabBar(_:didEndCustomizing:changed:)`. + public var didEndCustomizing: ControlEvent<([UITabBarItem], Bool)> { + let source = delegate.methodInvoked(#selector(UITabBarDelegate.tabBar(_:didEndCustomizing:changed:))) + .map { (a: [Any]) -> (([UITabBarItem], Bool)) in + let items = try castOrThrow([UITabBarItem].self, a[1]) + let changed = try castOrThrow(Bool.self, a[2]) + return (items, changed) + } + + return ControlEvent(events: source) + } + +} +#endif + +/** + iOS and tvOS + */ + +extension Reactive where Base: UITabBar { + /// Reactive wrapper for `delegate`. + /// + /// For more information take a look at `DelegateProxyType` protocol documentation. + public var delegate: DelegateProxy { + RxTabBarDelegateProxy.proxy(for: base) + } + + /// Reactive wrapper for `delegate` message `tabBar(_:didSelect:)`. + public var didSelectItem: ControlEvent { + let source = delegate.methodInvoked(#selector(UITabBarDelegate.tabBar(_:didSelect:))) + .map { a in + return try castOrThrow(UITabBarItem.self, a[1]) + } + + return ControlEvent(events: source) + } + +} + +#endif diff --git a/Pods/RxCocoa/RxCocoa/iOS/UITabBarController+Rx.swift b/Pods/RxCocoa/RxCocoa/iOS/UITabBarController+Rx.swift new file mode 100644 index 0000000..4b48e8e --- /dev/null +++ b/Pods/RxCocoa/RxCocoa/iOS/UITabBarController+Rx.swift @@ -0,0 +1,79 @@ +// +// UITabBarController+Rx.swift +// RxCocoa +// +// Created by Yusuke Kita on 2016/12/07. +// Copyright © 2016 Krunoslav Zaher. All rights reserved. +// + +#if os(iOS) || os(tvOS) + +import UIKit +import RxSwift + +/** + iOS only + */ +#if os(iOS) +extension Reactive where Base: UITabBarController { + + /// Reactive wrapper for `delegate` message `tabBarController:willBeginCustomizing:`. + public var willBeginCustomizing: ControlEvent<[UIViewController]> { + let source = delegate.methodInvoked(#selector(UITabBarControllerDelegate.tabBarController(_:willBeginCustomizing:))) + .map { a in + return try castOrThrow([UIViewController].self, a[1]) + } + + return ControlEvent(events: source) + } + + /// Reactive wrapper for `delegate` message `tabBarController:willEndCustomizing:changed:`. + public var willEndCustomizing: ControlEvent<(viewControllers: [UIViewController], changed: Bool)> { + let source = delegate.methodInvoked(#selector(UITabBarControllerDelegate.tabBarController(_:willEndCustomizing:changed:))) + .map { (a: [Any]) -> (viewControllers: [UIViewController], changed: Bool) in + let viewControllers = try castOrThrow([UIViewController].self, a[1]) + let changed = try castOrThrow(Bool.self, a[2]) + return (viewControllers, changed) + } + + return ControlEvent(events: source) + } + + /// Reactive wrapper for `delegate` message `tabBarController:didEndCustomizing:changed:`. + public var didEndCustomizing: ControlEvent<(viewControllers: [UIViewController], changed: Bool)> { + let source = delegate.methodInvoked(#selector(UITabBarControllerDelegate.tabBarController(_:didEndCustomizing:changed:))) + .map { (a: [Any]) -> (viewControllers: [UIViewController], changed: Bool) in + let viewControllers = try castOrThrow([UIViewController].self, a[1]) + let changed = try castOrThrow(Bool.self, a[2]) + return (viewControllers, changed) + } + + return ControlEvent(events: source) + } +} +#endif + +/** + iOS and tvOS + */ + + extension Reactive where Base: UITabBarController { + /// Reactive wrapper for `delegate`. + /// + /// For more information take a look at `DelegateProxyType` protocol documentation. + public var delegate: DelegateProxy { + RxTabBarControllerDelegateProxy.proxy(for: base) + } + + /// Reactive wrapper for `delegate` message `tabBarController:didSelect:`. + public var didSelect: ControlEvent { + let source = delegate.methodInvoked(#selector(UITabBarControllerDelegate.tabBarController(_:didSelect:))) + .map { a in + return try castOrThrow(UIViewController.self, a[1]) + } + + return ControlEvent(events: source) + } +} + +#endif diff --git a/Pods/RxCocoa/RxCocoa/iOS/UITableView+Rx.swift b/Pods/RxCocoa/RxCocoa/iOS/UITableView+Rx.swift new file mode 100644 index 0000000..f30197d --- /dev/null +++ b/Pods/RxCocoa/RxCocoa/iOS/UITableView+Rx.swift @@ -0,0 +1,429 @@ +// +// UITableView+Rx.swift +// RxCocoa +// +// Created by Krunoslav Zaher on 4/2/15. +// Copyright © 2015 Krunoslav Zaher. All rights reserved. +// + +#if os(iOS) || os(tvOS) + +import RxSwift +import UIKit + +// Items + +extension Reactive where Base: UITableView { + + /** + Binds sequences of elements to table view rows. + + - parameter source: Observable sequence of items. + - parameter cellFactory: Transform between sequence elements and view cells. + - returns: Disposable object that can be used to unbind. + + Example: + + let items = Observable.just([ + "First Item", + "Second Item", + "Third Item" + ]) + + items + .bind(to: tableView.rx.items) { (tableView, row, element) in + let cell = tableView.dequeueReusableCell(withIdentifier: "Cell")! + cell.textLabel?.text = "\(element) @ row \(row)" + return cell + } + .disposed(by: disposeBag) + + */ + public func items + (_ source: Source) + -> (_ cellFactory: @escaping (UITableView, Int, Sequence.Element) -> UITableViewCell) + -> Disposable + where Source.Element == Sequence { + return { cellFactory in + let dataSource = RxTableViewReactiveArrayDataSourceSequenceWrapper(cellFactory: cellFactory) + return self.items(dataSource: dataSource)(source) + } + } + + /** + Binds sequences of elements to table view rows. + + - parameter cellIdentifier: Identifier used to dequeue cells. + - parameter source: Observable sequence of items. + - parameter configureCell: Transform between sequence elements and view cells. + - parameter cellType: Type of table view cell. + - returns: Disposable object that can be used to unbind. + + Example: + + let items = Observable.just([ + "First Item", + "Second Item", + "Third Item" + ]) + + items + .bind(to: tableView.rx.items(cellIdentifier: "Cell", cellType: UITableViewCell.self)) { (row, element, cell) in + cell.textLabel?.text = "\(element) @ row \(row)" + } + .disposed(by: disposeBag) + */ + public func items + (cellIdentifier: String, cellType: Cell.Type = Cell.self) + -> (_ source: Source) + -> (_ configureCell: @escaping (Int, Sequence.Element, Cell) -> Void) + -> Disposable + where Source.Element == Sequence { + return { source in + return { configureCell in + let dataSource = RxTableViewReactiveArrayDataSourceSequenceWrapper { tv, i, item in + let indexPath = IndexPath(item: i, section: 0) + let cell = tv.dequeueReusableCell(withIdentifier: cellIdentifier, for: indexPath) as! Cell + configureCell(i, item, cell) + return cell + } + return self.items(dataSource: dataSource)(source) + } + } + } + + + /** + Binds sequences of elements to table view rows using a custom reactive data used to perform the transformation. + This method will retain the data source for as long as the subscription isn't disposed (result `Disposable` + being disposed). + In case `source` observable sequence terminates successfully, the data source will present latest element + until the subscription isn't disposed. + + - parameter dataSource: Data source used to transform elements to view cells. + - parameter source: Observable sequence of items. + - returns: Disposable object that can be used to unbind. + */ + public func items< + DataSource: RxTableViewDataSourceType & UITableViewDataSource, + Source: ObservableType> + (dataSource: DataSource) + -> (_ source: Source) + -> Disposable + where DataSource.Element == Source.Element { + return { source in + // This is called for side effects only, and to make sure delegate proxy is in place when + // data source is being bound. + // This is needed because theoretically the data source subscription itself might + // call `self.rx.delegate`. If that happens, it might cause weird side effects since + // setting data source will set delegate, and UITableView might get into a weird state. + // Therefore it's better to set delegate proxy first, just to be sure. + _ = self.delegate + // Strong reference is needed because data source is in use until result subscription is disposed + return source.subscribeProxyDataSource(ofObject: self.base, dataSource: dataSource as UITableViewDataSource, retainDataSource: true) { [weak tableView = self.base] (_: RxTableViewDataSourceProxy, event) -> Void in + guard let tableView = tableView else { + return + } + dataSource.tableView(tableView, observedEvent: event) + } + } + } + +} + +extension Reactive where Base: UITableView { + /** + Reactive wrapper for `dataSource`. + + For more information take a look at `DelegateProxyType` protocol documentation. + */ + public var dataSource: DelegateProxy { + RxTableViewDataSourceProxy.proxy(for: base) + } + + /** + Installs data source as forwarding delegate on `rx.dataSource`. + Data source won't be retained. + + It enables using normal delegate mechanism with reactive delegate mechanism. + + - parameter dataSource: Data source object. + - returns: Disposable object that can be used to unbind the data source. + */ + public func setDataSource(_ dataSource: UITableViewDataSource) + -> Disposable { + RxTableViewDataSourceProxy.installForwardDelegate(dataSource, retainDelegate: false, onProxyForObject: self.base) + } + + // events + + /** + Reactive wrapper for `delegate` message `tableView:didSelectRowAtIndexPath:`. + */ + public var itemSelected: ControlEvent { + let source = self.delegate.methodInvoked(#selector(UITableViewDelegate.tableView(_:didSelectRowAt:))) + .map { a in + return try castOrThrow(IndexPath.self, a[1]) + } + + return ControlEvent(events: source) + } + + /** + Reactive wrapper for `delegate` message `tableView:didDeselectRowAtIndexPath:`. + */ + public var itemDeselected: ControlEvent { + let source = self.delegate.methodInvoked(#selector(UITableViewDelegate.tableView(_:didDeselectRowAt:))) + .map { a in + return try castOrThrow(IndexPath.self, a[1]) + } + + return ControlEvent(events: source) + } + + /** + Reactive wrapper for `delegate` message `tableView:didHighlightRowAt:`. + */ + public var itemHighlighted: ControlEvent { + let source = self.delegate.methodInvoked(#selector(UITableViewDelegate.tableView(_:didHighlightRowAt:))) + .map { a in + return try castOrThrow(IndexPath.self, a[1]) + } + + return ControlEvent(events: source) + } + + /** + Reactive wrapper for `delegate` message `tableView:didUnhighlightRowAt:`. + */ + public var itemUnhighlighted: ControlEvent { + let source = self.delegate.methodInvoked(#selector(UITableViewDelegate.tableView(_:didUnhighlightRowAt:))) + .map { a in + return try castOrThrow(IndexPath.self, a[1]) + } + + return ControlEvent(events: source) + } + + /** + Reactive wrapper for `delegate` message `tableView:accessoryButtonTappedForRowWithIndexPath:`. + */ + public var itemAccessoryButtonTapped: ControlEvent { + let source: Observable = self.delegate.methodInvoked(#selector(UITableViewDelegate.tableView(_:accessoryButtonTappedForRowWith:))) + .map { a in + return try castOrThrow(IndexPath.self, a[1]) + } + + return ControlEvent(events: source) + } + + /** + Reactive wrapper for `delegate` message `tableView:commitEditingStyle:forRowAtIndexPath:`. + */ + public var itemInserted: ControlEvent { + let source = self.dataSource.methodInvoked(#selector(UITableViewDataSource.tableView(_:commit:forRowAt:))) + .filter { a in + return UITableViewCell.EditingStyle(rawValue: (try castOrThrow(NSNumber.self, a[1])).intValue) == .insert + } + .map { a in + return (try castOrThrow(IndexPath.self, a[2])) + } + + return ControlEvent(events: source) + } + + /** + Reactive wrapper for `delegate` message `tableView:commitEditingStyle:forRowAtIndexPath:`. + */ + public var itemDeleted: ControlEvent { + let source = self.dataSource.methodInvoked(#selector(UITableViewDataSource.tableView(_:commit:forRowAt:))) + .filter { a in + return UITableViewCell.EditingStyle(rawValue: (try castOrThrow(NSNumber.self, a[1])).intValue) == .delete + } + .map { a in + return try castOrThrow(IndexPath.self, a[2]) + } + + return ControlEvent(events: source) + } + + /** + Reactive wrapper for `delegate` message `tableView:moveRowAtIndexPath:toIndexPath:`. + */ + public var itemMoved: ControlEvent { + let source: Observable = self.dataSource.methodInvoked(#selector(UITableViewDataSource.tableView(_:moveRowAt:to:))) + .map { a in + return (try castOrThrow(IndexPath.self, a[1]), try castOrThrow(IndexPath.self, a[2])) + } + + return ControlEvent(events: source) + } + + /** + Reactive wrapper for `delegate` message `tableView:willDisplayCell:forRowAtIndexPath:`. + */ + public var willDisplayCell: ControlEvent { + let source: Observable = self.delegate.methodInvoked(#selector(UITableViewDelegate.tableView(_:willDisplay:forRowAt:))) + .map { a in + return (try castOrThrow(UITableViewCell.self, a[1]), try castOrThrow(IndexPath.self, a[2])) + } + + return ControlEvent(events: source) + } + + /** + Reactive wrapper for `delegate` message `tableView:didEndDisplayingCell:forRowAtIndexPath:`. + */ + public var didEndDisplayingCell: ControlEvent { + let source: Observable = self.delegate.methodInvoked(#selector(UITableViewDelegate.tableView(_:didEndDisplaying:forRowAt:))) + .map { a in + return (try castOrThrow(UITableViewCell.self, a[1]), try castOrThrow(IndexPath.self, a[2])) + } + + return ControlEvent(events: source) + } + + /** + Reactive wrapper for `delegate` message `tableView:didSelectRowAtIndexPath:`. + + It can be only used when one of the `rx.itemsWith*` methods is used to bind observable sequence, + or any other data source conforming to `SectionedViewDataSourceType` protocol. + + ``` + tableView.rx.modelSelected(MyModel.self) + .map { ... + ``` + */ + public func modelSelected(_ modelType: T.Type) -> ControlEvent { + let source: Observable = self.itemSelected.flatMap { [weak view = self.base as UITableView] indexPath -> Observable in + guard let view = view else { + return Observable.empty() + } + + return Observable.just(try view.rx.model(at: indexPath)) + } + + return ControlEvent(events: source) + } + + /** + Reactive wrapper for `delegate` message `tableView:didDeselectRowAtIndexPath:`. + + It can be only used when one of the `rx.itemsWith*` methods is used to bind observable sequence, + or any other data source conforming to `SectionedViewDataSourceType` protocol. + + ``` + tableView.rx.modelDeselected(MyModel.self) + .map { ... + ``` + */ + public func modelDeselected(_ modelType: T.Type) -> ControlEvent { + let source: Observable = self.itemDeselected.flatMap { [weak view = self.base as UITableView] indexPath -> Observable in + guard let view = view else { + return Observable.empty() + } + + return Observable.just(try view.rx.model(at: indexPath)) + } + + return ControlEvent(events: source) + } + + /** + Reactive wrapper for `delegate` message `tableView:commitEditingStyle:forRowAtIndexPath:`. + + It can be only used when one of the `rx.itemsWith*` methods is used to bind observable sequence, + or any other data source conforming to `SectionedViewDataSourceType` protocol. + + ``` + tableView.rx.modelDeleted(MyModel.self) + .map { ... + ``` + */ + public func modelDeleted(_ modelType: T.Type) -> ControlEvent { + let source: Observable = self.itemDeleted.flatMap { [weak view = self.base as UITableView] indexPath -> Observable in + guard let view = view else { + return Observable.empty() + } + + return Observable.just(try view.rx.model(at: indexPath)) + } + + return ControlEvent(events: source) + } + + /** + Synchronous helper method for retrieving a model at indexPath through a reactive data source. + */ + public func model(at indexPath: IndexPath) throws -> T { + let dataSource: SectionedViewDataSourceType = castOrFatalError(self.dataSource.forwardToDelegate(), message: "This method only works in case one of the `rx.items*` methods was used.") + + let element = try dataSource.model(at: indexPath) + + return castOrFatalError(element) + } +} + +@available(iOS 10.0, tvOS 10.0, *) +extension Reactive where Base: UITableView { + + /// Reactive wrapper for `prefetchDataSource`. + /// + /// For more information take a look at `DelegateProxyType` protocol documentation. + public var prefetchDataSource: DelegateProxy { + RxTableViewDataSourcePrefetchingProxy.proxy(for: base) + } + + /** + Installs prefetch data source as forwarding delegate on `rx.prefetchDataSource`. + Prefetch data source won't be retained. + + It enables using normal delegate mechanism with reactive delegate mechanism. + + - parameter prefetchDataSource: Prefetch data source object. + - returns: Disposable object that can be used to unbind the data source. + */ + public func setPrefetchDataSource(_ prefetchDataSource: UITableViewDataSourcePrefetching) + -> Disposable { + return RxTableViewDataSourcePrefetchingProxy.installForwardDelegate(prefetchDataSource, retainDelegate: false, onProxyForObject: self.base) + } + + /// Reactive wrapper for `prefetchDataSource` message `tableView(_:prefetchRowsAt:)`. + public var prefetchRows: ControlEvent<[IndexPath]> { + let source = RxTableViewDataSourcePrefetchingProxy.proxy(for: base).prefetchRowsPublishSubject + return ControlEvent(events: source) + } + + /// Reactive wrapper for `prefetchDataSource` message `tableView(_:cancelPrefetchingForRowsAt:)`. + public var cancelPrefetchingForRows: ControlEvent<[IndexPath]> { + let source = prefetchDataSource.methodInvoked(#selector(UITableViewDataSourcePrefetching.tableView(_:cancelPrefetchingForRowsAt:))) + .map { a in + return try castOrThrow(Array.self, a[1]) + } + + return ControlEvent(events: source) + } + +} +#endif + +#if os(tvOS) + + extension Reactive where Base: UITableView { + + /** + Reactive wrapper for `delegate` message `tableView:didUpdateFocusInContext:withAnimationCoordinator:`. + */ + public var didUpdateFocusInContextWithAnimationCoordinator: ControlEvent<(context: UITableViewFocusUpdateContext, animationCoordinator: UIFocusAnimationCoordinator)> { + + let source = delegate.methodInvoked(#selector(UITableViewDelegate.tableView(_:didUpdateFocusIn:with:))) + .map { a -> (context: UITableViewFocusUpdateContext, animationCoordinator: UIFocusAnimationCoordinator) in + let context = try castOrThrow(UITableViewFocusUpdateContext.self, a[1]) + let animationCoordinator = try castOrThrow(UIFocusAnimationCoordinator.self, a[2]) + return (context: context, animationCoordinator: animationCoordinator) + } + + return ControlEvent(events: source) + } + } +#endif diff --git a/Pods/RxCocoa/RxCocoa/iOS/UITextField+Rx.swift b/Pods/RxCocoa/RxCocoa/iOS/UITextField+Rx.swift new file mode 100644 index 0000000..46e0e48 --- /dev/null +++ b/Pods/RxCocoa/RxCocoa/iOS/UITextField+Rx.swift @@ -0,0 +1,55 @@ +// +// UITextField+Rx.swift +// RxCocoa +// +// Created by Krunoslav Zaher on 2/21/15. +// Copyright © 2015 Krunoslav Zaher. All rights reserved. +// + +#if os(iOS) || os(tvOS) + +import RxSwift +import UIKit + +extension Reactive where Base: UITextField { + /// Reactive wrapper for `text` property. + public var text: ControlProperty { + value + } + + /// Reactive wrapper for `text` property. + public var value: ControlProperty { + return base.rx.controlPropertyWithDefaultEvents( + getter: { textField in + textField.text + }, + setter: { textField, value in + // This check is important because setting text value always clears control state + // including marked text selection which is important for proper input + // when IME input method is used. + if textField.text != value { + textField.text = value + } + } + ) + } + + /// Bindable sink for `attributedText` property. + public var attributedText: ControlProperty { + return base.rx.controlPropertyWithDefaultEvents( + getter: { textField in + textField.attributedText + }, + setter: { textField, value in + // This check is important because setting text value always clears control state + // including marked text selection which is important for proper input + // when IME input method is used. + if textField.attributedText != value { + textField.attributedText = value + } + } + ) + } +} + +#endif diff --git a/Pods/RxCocoa/RxCocoa/iOS/UITextView+Rx.swift b/Pods/RxCocoa/RxCocoa/iOS/UITextView+Rx.swift new file mode 100644 index 0000000..3395d9b --- /dev/null +++ b/Pods/RxCocoa/RxCocoa/iOS/UITextView+Rx.swift @@ -0,0 +1,125 @@ +// +// UITextView+Rx.swift +// RxCocoa +// +// Created by Yuta ToKoRo on 7/19/15. +// Copyright © 2015 Krunoslav Zaher. All rights reserved. +// + +#if os(iOS) || os(tvOS) + +import UIKit +import RxSwift + +extension Reactive where Base: UITextView { + /// Reactive wrapper for `text` property + public var text: ControlProperty { + value + } + + /// Reactive wrapper for `text` property. + public var value: ControlProperty { + let source: Observable = Observable.deferred { [weak textView = self.base] in + let text = textView?.text + + let textChanged = textView?.textStorage + // This project uses text storage notifications because + // that's the only way to catch autocorrect changes + // in all cases. Other suggestions are welcome. + .rx.didProcessEditingRangeChangeInLength + // This observe on is here because text storage + // will emit event while process is not completely done, + // so rebinding a value will cause an exception to be thrown. + .observe(on:MainScheduler.asyncInstance) + .map { _ in + return textView?.textStorage.string + } + ?? Observable.empty() + + return textChanged + .startWith(text) + } + + let bindingObserver = Binder(self.base) { (textView, text: String?) in + // This check is important because setting text value always clears control state + // including marked text selection which is important for proper input + // when IME input method is used. + if textView.text != text { + textView.text = text + } + } + + return ControlProperty(values: source, valueSink: bindingObserver) + } + + + /// Reactive wrapper for `attributedText` property. + public var attributedText: ControlProperty { + let source: Observable = Observable.deferred { [weak textView = self.base] in + let attributedText = textView?.attributedText + + let textChanged: Observable = textView?.textStorage + // This project uses text storage notifications because + // that's the only way to catch autocorrect changes + // in all cases. Other suggestions are welcome. + .rx.didProcessEditingRangeChangeInLength + // This observe on is here because attributedText storage + // will emit event while process is not completely done, + // so rebinding a value will cause an exception to be thrown. + .observe(on:MainScheduler.asyncInstance) + .map { _ in + return textView?.attributedText + } + ?? Observable.empty() + + return textChanged + .startWith(attributedText) + } + + let bindingObserver = Binder(self.base) { (textView, attributedText: NSAttributedString?) in + // This check is important because setting text value always clears control state + // including marked text selection which is important for proper input + // when IME input method is used. + if textView.attributedText != attributedText { + textView.attributedText = attributedText + } + } + + return ControlProperty(values: source, valueSink: bindingObserver) + } + + /// Reactive wrapper for `delegate` message. + public var didBeginEditing: ControlEvent<()> { + return ControlEvent<()>(events: self.delegate.methodInvoked(#selector(UITextViewDelegate.textViewDidBeginEditing(_:))) + .map { _ in + return () + }) + } + + /// Reactive wrapper for `delegate` message. + public var didEndEditing: ControlEvent<()> { + return ControlEvent<()>(events: self.delegate.methodInvoked(#selector(UITextViewDelegate.textViewDidEndEditing(_:))) + .map { _ in + return () + }) + } + + /// Reactive wrapper for `delegate` message. + public var didChange: ControlEvent<()> { + return ControlEvent<()>(events: self.delegate.methodInvoked(#selector(UITextViewDelegate.textViewDidChange(_:))) + .map { _ in + return () + }) + } + + /// Reactive wrapper for `delegate` message. + public var didChangeSelection: ControlEvent<()> { + return ControlEvent<()>(events: self.delegate.methodInvoked(#selector(UITextViewDelegate.textViewDidChangeSelection(_:))) + .map { _ in + return () + }) + } + +} + +#endif diff --git a/Pods/RxCocoa/RxCocoa/iOS/WKWebView+Rx.swift b/Pods/RxCocoa/RxCocoa/iOS/WKWebView+Rx.swift new file mode 100644 index 0000000..b3b4d84 --- /dev/null +++ b/Pods/RxCocoa/RxCocoa/iOS/WKWebView+Rx.swift @@ -0,0 +1,57 @@ +// +// WKWebView+Rx.swift +// RxCocoa +// +// Created by Giuseppe Lanza on 14/02/2020. +// Copyright © 2020 Krunoslav Zaher. All rights reserved. +// + +#if os(iOS) || os(macOS) + +import RxSwift +import WebKit + +@available(iOS 8.0, OSX 10.10, OSXApplicationExtension 10.10, *) +extension Reactive where Base: WKWebView { + + /// Reactive wrapper for `navigationDelegate`. + /// For more information take a look at `DelegateProxyType` protocol documentation. + public var navigationDelegate: DelegateProxy { + RxWKNavigationDelegateProxy.proxy(for: base) + } + + /// Reactive wrapper for `navigationDelegate` message. + public var didCommit: Observable { + navigationDelegate + .methodInvoked(#selector(WKNavigationDelegate.webView(_:didCommit:))) + .map { a in try castOrThrow(WKNavigation.self, a[1]) } + } + + /// Reactive wrapper for `navigationDelegate` message. + public var didStartLoad: Observable { + navigationDelegate + .methodInvoked(#selector(WKNavigationDelegate.webView(_:didStartProvisionalNavigation:))) + .map { a in try castOrThrow(WKNavigation.self, a[1]) } + } + + /// Reactive wrapper for `navigationDelegate` message. + public var didFinishLoad: Observable { + navigationDelegate + .methodInvoked(#selector(WKNavigationDelegate.webView(_:didFinish:))) + .map { a in try castOrThrow(WKNavigation.self, a[1]) } + } + + /// Reactive wrapper for `navigationDelegate` message. + public var didFailLoad: Observable<(WKNavigation, Error)> { + navigationDelegate + .methodInvoked(#selector(WKNavigationDelegate.webView(_:didFail:withError:))) + .map { a in + ( + try castOrThrow(WKNavigation.self, a[1]), + try castOrThrow(Error.self, a[2]) + ) + } + } +} + +#endif diff --git a/Pods/RxCocoa/RxCocoa/macOS/NSButton+Rx.swift b/Pods/RxCocoa/RxCocoa/macOS/NSButton+Rx.swift new file mode 100644 index 0000000..7c22361 --- /dev/null +++ b/Pods/RxCocoa/RxCocoa/macOS/NSButton+Rx.swift @@ -0,0 +1,33 @@ +// +// NSButton+Rx.swift +// RxCocoa +// +// Created by Krunoslav Zaher on 5/17/15. +// Copyright © 2015 Krunoslav Zaher. All rights reserved. +// + +#if os(macOS) + +import RxSwift +import Cocoa + +extension Reactive where Base: NSButton { + + /// Reactive wrapper for control event. + public var tap: ControlEvent { + self.controlEvent + } + + /// Reactive wrapper for `state` property`. + public var state: ControlProperty { + return self.base.rx.controlProperty( + getter: { control in + return control.state + }, setter: { (control: NSButton, state: NSControl.StateValue) in + control.state = state + } + ) + } +} + +#endif diff --git a/Pods/RxCocoa/RxCocoa/macOS/NSControl+Rx.swift b/Pods/RxCocoa/RxCocoa/macOS/NSControl+Rx.swift new file mode 100644 index 0000000..534f40c --- /dev/null +++ b/Pods/RxCocoa/RxCocoa/macOS/NSControl+Rx.swift @@ -0,0 +1,87 @@ +// +// NSControl+Rx.swift +// RxCocoa +// +// Created by Krunoslav Zaher on 5/31/15. +// Copyright © 2015 Krunoslav Zaher. All rights reserved. +// + +#if os(macOS) + +import Cocoa +import RxSwift + +private var rx_value_key: UInt8 = 0 +private var rx_control_events_key: UInt8 = 0 + +extension Reactive where Base: NSControl { + + /// Reactive wrapper for control event. + public var controlEvent: ControlEvent<()> { + MainScheduler.ensureRunningOnMainThread() + + let source = self.lazyInstanceObservable(&rx_control_events_key) { () -> Observable in + Observable.create { [weak control = self.base] observer in + MainScheduler.ensureRunningOnMainThread() + + guard let control = control else { + observer.on(.completed) + return Disposables.create() + } + + let observer = ControlTarget(control: control) { _ in + observer.on(.next(())) + } + + return observer + } + .take(until: self.deallocated) + .share() + } + + return ControlEvent(events: source) + } + + /// Creates a `ControlProperty` that is triggered by target/action pattern value updates. + /// + /// - parameter getter: Property value getter. + /// - parameter setter: Property value setter. + public func controlProperty( + getter: @escaping (Base) -> T, + setter: @escaping (Base, T) -> Void + ) -> ControlProperty { + MainScheduler.ensureRunningOnMainThread() + + let source = self.base.rx.lazyInstanceObservable(&rx_value_key) { () -> Observable<()> in + return Observable.create { [weak weakControl = self.base] (observer: AnyObserver<()>) in + guard let control = weakControl else { + observer.on(.completed) + return Disposables.create() + } + + observer.on(.next(())) + + let observer = ControlTarget(control: control) { _ in + if weakControl != nil { + observer.on(.next(())) + } + } + + return observer + } + .take(until: self.deallocated) + .share(replay: 1, scope: .whileConnected) + } + .flatMap { [weak base] _ -> Observable in + guard let control = base else { return Observable.empty() } + return Observable.just(getter(control)) + } + + let bindingObserver = Binder(self.base, binding: setter) + + return ControlProperty(values: source, valueSink: bindingObserver) + } +} + + +#endif diff --git a/Pods/RxCocoa/RxCocoa/macOS/NSSlider+Rx.swift b/Pods/RxCocoa/RxCocoa/macOS/NSSlider+Rx.swift new file mode 100644 index 0000000..2e5b19a --- /dev/null +++ b/Pods/RxCocoa/RxCocoa/macOS/NSSlider+Rx.swift @@ -0,0 +1,30 @@ +// +// NSSlider+Rx.swift +// RxCocoa +// +// Created by Junior B. on 24/05/15. +// Copyright © 2015 Krunoslav Zaher. All rights reserved. +// + +#if os(macOS) + +import RxSwift +import Cocoa + +extension Reactive where Base: NSSlider { + + /// Reactive wrapper for `value` property. + public var value: ControlProperty { + return self.base.rx.controlProperty( + getter: { control -> Double in + return control.doubleValue + }, + setter: { control, value in + control.doubleValue = value + } + ) + } + +} + +#endif diff --git a/Pods/RxCocoa/RxCocoa/macOS/NSTextField+Rx.swift b/Pods/RxCocoa/RxCocoa/macOS/NSTextField+Rx.swift new file mode 100644 index 0000000..ce69f9e --- /dev/null +++ b/Pods/RxCocoa/RxCocoa/macOS/NSTextField+Rx.swift @@ -0,0 +1,87 @@ +// +// NSTextField+Rx.swift +// RxCocoa +// +// Created by Krunoslav Zaher on 5/17/15. +// Copyright © 2015 Krunoslav Zaher. All rights reserved. +// + +#if os(macOS) + +import Cocoa +import RxSwift + +/// Delegate proxy for `NSTextField`. +/// +/// For more information take a look at `DelegateProxyType`. +open class RxTextFieldDelegateProxy + : DelegateProxy + , DelegateProxyType + , NSTextFieldDelegate { + + /// Typed parent object. + public weak private(set) var textField: NSTextField? + + /// Initializes `RxTextFieldDelegateProxy` + /// + /// - parameter textField: Parent object for delegate proxy. + init(textField: NSTextField) { + self.textField = textField + super.init(parentObject: textField, delegateProxy: RxTextFieldDelegateProxy.self) + } + + public static func registerKnownImplementations() { + self.register { RxTextFieldDelegateProxy(textField: $0) } + } + + fileprivate let textSubject = PublishSubject() + + // MARK: Delegate methods + open func controlTextDidChange(_ notification: Notification) { + let textField: NSTextField = castOrFatalError(notification.object) + let nextValue = textField.stringValue + self.textSubject.on(.next(nextValue)) + _forwardToDelegate?.controlTextDidChange?(notification) + } + + // MARK: Delegate proxy methods + + /// For more information take a look at `DelegateProxyType`. + open class func currentDelegate(for object: ParentObject) -> NSTextFieldDelegate? { + object.delegate + } + + /// For more information take a look at `DelegateProxyType`. + open class func setCurrentDelegate(_ delegate: NSTextFieldDelegate?, to object: ParentObject) { + object.delegate = delegate + } + +} + +extension Reactive where Base: NSTextField { + + /// Reactive wrapper for `delegate`. + /// + /// For more information take a look at `DelegateProxyType` protocol documentation. + public var delegate: DelegateProxy { + RxTextFieldDelegateProxy.proxy(for: self.base) + } + + /// Reactive wrapper for `text` property. + public var text: ControlProperty { + let delegate = RxTextFieldDelegateProxy.proxy(for: self.base) + + let source = Observable.deferred { [weak textField = self.base] in + delegate.textSubject.startWith(textField?.stringValue) + }.take(until: self.deallocated) + + let observer = Binder(self.base) { (control, value: String?) in + control.stringValue = value ?? "" + } + + return ControlProperty(values: source, valueSink: observer.asObserver()) + } + +} + +#endif diff --git a/Pods/RxCocoa/RxCocoa/macOS/NSTextView+Rx.swift b/Pods/RxCocoa/RxCocoa/macOS/NSTextView+Rx.swift new file mode 100644 index 0000000..c3134e4 --- /dev/null +++ b/Pods/RxCocoa/RxCocoa/macOS/NSTextView+Rx.swift @@ -0,0 +1,94 @@ +// +// NSTextView+Rx.swift +// RxCocoa +// +// Created by Cee on 8/5/18. +// Copyright © 2018 Krunoslav Zaher. All rights reserved. +// + +#if os(macOS) + +import Cocoa +import RxSwift + +/// Delegate proxy for `NSTextView`. +/// +/// For more information take a look at `DelegateProxyType`. +open class RxTextViewDelegateProxy: DelegateProxy, DelegateProxyType, NSTextViewDelegate { + + #if compiler(>=5.2) + /// Typed parent object. + /// + /// - note: Since Swift 5.2 and Xcode 11.4, Apple have suddenly + /// disallowed using `weak` for NSTextView. For more details + /// see this GitHub Issue: https://git.io/JvSRn + public private(set) var textView: NSTextView? + #else + /// Typed parent object. + public weak private(set) var textView: NSTextView? + #endif + + /// Initializes `RxTextViewDelegateProxy` + /// + /// - parameter textView: Parent object for delegate proxy. + init(textView: NSTextView) { + self.textView = textView + super.init(parentObject: textView, delegateProxy: RxTextViewDelegateProxy.self) + } + + public static func registerKnownImplementations() { + self.register { RxTextViewDelegateProxy(textView: $0) } + } + + fileprivate let textSubject = PublishSubject() + + // MARK: Delegate methods + + open func textDidChange(_ notification: Notification) { + let textView: NSTextView = castOrFatalError(notification.object) + let nextValue = textView.string + self.textSubject.on(.next(nextValue)) + self._forwardToDelegate?.textDidChange?(notification) + } + + // MARK: Delegate proxy methods + + /// For more information take a look at `DelegateProxyType`. + open class func currentDelegate(for object: ParentObject) -> NSTextViewDelegate? { + object.delegate + } + + /// For more information take a look at `DelegateProxyType`. + open class func setCurrentDelegate(_ delegate: NSTextViewDelegate?, to object: ParentObject) { + object.delegate = delegate + } + +} + +extension Reactive where Base: NSTextView { + + /// Reactive wrapper for `delegate`. + /// + /// For more information take a look at `DelegateProxyType` protocol documentation. + public var delegate: DelegateProxy { + RxTextViewDelegateProxy.proxy(for: self.base) + } + + /// Reactive wrapper for `string` property. + public var string: ControlProperty { + let delegate = RxTextViewDelegateProxy.proxy(for: self.base) + + let source = Observable.deferred { [weak textView = self.base] in + delegate.textSubject.startWith(textView?.string ?? "") + }.take(until: self.deallocated) + + let observer = Binder(self.base) { control, value in + control.string = value + } + + return ControlProperty(values: source, valueSink: observer.asObserver()) + } + +} + +#endif diff --git a/Pods/RxCocoa/RxCocoa/macOS/NSView+Rx.swift b/Pods/RxCocoa/RxCocoa/macOS/NSView+Rx.swift new file mode 100644 index 0000000..f4256d1 --- /dev/null +++ b/Pods/RxCocoa/RxCocoa/macOS/NSView+Rx.swift @@ -0,0 +1,21 @@ +// +// NSView+Rx.swift +// RxCocoa +// +// Created by Krunoslav Zaher on 12/6/15. +// Copyright © 2015 Krunoslav Zaher. All rights reserved. +// + +#if os(macOS) + import Cocoa + import RxSwift + + extension Reactive where Base: NSView { + /// Bindable sink for `alphaValue` property. + public var alpha: Binder { + return Binder(self.base) { view, value in + view.alphaValue = value + } + } + } +#endif diff --git a/Pods/RxRelay/LICENSE.md b/Pods/RxRelay/LICENSE.md new file mode 100644 index 0000000..e32511b --- /dev/null +++ b/Pods/RxRelay/LICENSE.md @@ -0,0 +1,9 @@ +**The MIT License** +**Copyright © 2015 Krunoslav Zaher, Shai Mishali** +**All rights reserved.** + +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/RxRelay/README.md b/Pods/RxRelay/README.md new file mode 100644 index 0000000..a95d9e0 --- /dev/null +++ b/Pods/RxRelay/README.md @@ -0,0 +1,254 @@ +

+RxSwift Logo +
+
Build Status +Supported Platforms: iOS, macOS, tvOS, watchOS & Linux +
+ + + +

+ +Rx is a [generic abstraction of computation](https://youtu.be/looJcaeboBY) expressed through `Observable` interface, which lets you broadcast and subscribe to values and other events from an `Observable` stream. + +RxSwift is the Swift-specific implementation of the [Reactive Extensions](http://reactivex.io) standard. + +

RxSwift Observable Example of a price constantly changing and updating the app's UI

+ +While this version aims to stay true to the original spirit and naming conventions of Rx, this projects also aims to provide a true Swift-first API for Rx APIs. + +Cross platform documentation can be found on [ReactiveX.io](http://reactivex.io/). + +Like other Rx implementation, RxSwift's intention is to enable easy composition of asynchronous operations and streams of data in the form of `Observable` objects and a suite of methods to transform and compose these pieces of asynchronous work. + +KVO observation, async operations, UI Events and other streams of data are all unified under [abstraction of sequence](Documentation/GettingStarted.md#observables-aka-sequences). This is the reason why Rx is so simple, elegant and powerful. + +## I came here because I want to ... + +###### ... understand + +* [why use rx?](Documentation/Why.md) +* [the basics, getting started with RxSwift](Documentation/GettingStarted.md) +* [traits](Documentation/Traits.md) - what are `Single`, `Completable`, `Maybe`, `Driver`, and `ControlProperty` ... and why do they exist? +* [testing](Documentation/UnitTests.md) +* [tips and common errors](Documentation/Tips.md) +* [debugging](Documentation/GettingStarted.md#debugging) +* [the math behind Rx](Documentation/MathBehindRx.md) +* [what are hot and cold observable sequences?](Documentation/HotAndColdObservables.md) + +###### ... install + +* Integrate RxSwift/RxCocoa with my app. [Installation Guide](#installation) + +###### ... hack around + +* with the example app. [Running Example App](Documentation/ExampleApp.md) +* with operators in playgrounds. [Playgrounds](Documentation/Playgrounds.md) + +###### ... interact + +* All of this is great, but it would be nice to talk with other people using RxSwift and exchange experiences.
[Join Slack Channel](http://slack.rxswift.org) +* Report a problem using the library. [Open an Issue With Bug Template](.github/ISSUE_TEMPLATE.md) +* Request a new feature. [Open an Issue With Feature Request Template](Documentation/NewFeatureRequestTemplate.md) +* Help out [Check out contribution guide](CONTRIBUTING.md) + +###### ... compare + +* [with Combine and ReactiveSwift](Documentation/ComparisonWithOtherLibraries.md). + +###### ... understand the structure + +RxSwift is as compositional as the asynchronous work it drives. The core unit is RxSwift itself, while other dependencies can be added for UI Work, testing, and more. + +It comprises five separate components depending on each other in the following way: + +```none +┌──────────────┐ ┌──────────────┐ +│ RxCocoa ├────▶ RxRelay │ +└───────┬──────┘ └──────┬───────┘ + │ │ +┌───────▼──────────────────▼───────┐ +│ RxSwift │ +└───────▲──────────────────▲───────┘ + │ │ +┌───────┴──────┐ ┌──────┴───────┐ +│ RxTest │ │ RxBlocking │ +└──────────────┘ └──────────────┘ +``` + +* **RxSwift**: The core of RxSwift, providing the Rx standard as (mostly) defined by [ReactiveX](https://reactivex.io). It has no other dependencies. +* **RxCocoa**: Provides Cocoa-specific capabilities for general iOS/macOS/watchOS & tvOS app development, such as Shared Sequences, Traits, and much more. It depends on both `RxSwift` and `RxRelay`. +* **RxRelay**: Provides `PublishRelay`, `BehaviorRelay` and `ReplayRelay`, three [simple wrappers around Subjects](https://github.com/ReactiveX/RxSwift/blob/main/Documentation/Subjects.md#relays). It depends on `RxSwift`. +* **RxTest** and **RxBlocking**: Provides testing capabilities for Rx-based systems. It depends on `RxSwift`. + +## Usage + + + + + + + + + + + + + + + + + + + +
Here's an exampleIn Action
Define search for GitHub repositories ...
+let searchResults = searchBar.rx.text.orEmpty
+    .throttle(.milliseconds(300), scheduler: MainScheduler.instance)
+    .distinctUntilChanged()
+    .flatMapLatest { query -> Observable<[Repository]> in
+        if query.isEmpty {
+            return .just([])
+        }
+        return searchGitHub(query)
+            .catchAndReturn([])
+    }
+    .observe(on: MainScheduler.instance)
... then bind the results to your tableview
+searchResults
+    .bind(to: tableView.rx.items(cellIdentifier: "Cell")) {
+        (index, repository: Repository, cell) in
+        cell.textLabel?.text = repository.name
+        cell.detailTextLabel?.text = repository.url
+    }
+    .disposed(by: disposeBag)
+ + +## Requirements + +* Xcode 12.x +* Swift 5.x + +For Xcode 11 and below, [use RxSwift 5.x](https://github.com/ReactiveX/RxSwift/releases/tag/5.1.1). + +## Installation + +RxSwift doesn't contain any external dependencies. + +These are currently the supported installation options: + +### Manual + +Open Rx.xcworkspace, choose `RxExample` and hit run. This method will build everything and run the sample app + +### [CocoaPods](https://guides.cocoapods.org/using/using-cocoapods.html) + +```ruby +# Podfile +use_frameworks! + +target 'YOUR_TARGET_NAME' do + pod 'RxSwift', '6.5.0' + pod 'RxCocoa', '6.5.0' +end + +# RxTest and RxBlocking make the most sense in the context of unit/integration tests +target 'YOUR_TESTING_TARGET' do + pod 'RxBlocking', '6.5.0' + pod 'RxTest', '6.5.0' +end +``` + +Replace `YOUR_TARGET_NAME` and then, in the `Podfile` directory, type: + +```bash +$ pod install +``` + +### XCFrameworks + +Each release starting with RxSwift 6 includes `*.xcframework` framework binaries. + +Simply drag the needed framework binaries to your **Frameworks, Libraries, and Embedded Content** section under your target's **General** tab. + +> **Note**: If you're using `RxCocoa`, be sure to also drag **RxCocoaRuntime.xcframework** before importing `RxCocoa`. + +XCFrameworks instructions + +### [Carthage](https://github.com/Carthage/Carthage) + +Add this to `Cartfile` + +``` +github "ReactiveX/RxSwift" "6.5.0" +``` + +```bash +$ carthage update +``` + +#### Carthage as a Static Library + +Carthage defaults to building RxSwift as a Dynamic Library. + +If you wish to build RxSwift as a Static Library using Carthage you may use the script below to manually modify the framework type before building with Carthage: + +```bash +carthage update RxSwift --platform iOS --no-build +sed -i -e 's/MACH_O_TYPE = mh_dylib/MACH_O_TYPE = staticlib/g' Carthage/Checkouts/RxSwift/Rx.xcodeproj/project.pbxproj +carthage build RxSwift --platform iOS +``` + +### [Swift Package Manager](https://github.com/apple/swift-package-manager) + +> **Note**: There is a critical cross-dependency bug affecting many projects including RxSwift in Swift Package Manager. We've [filed a bug (SR-12303)](https://bugs.swift.org/browse/SR-12303) in early 2020 but have no answer yet. Your mileage may vary. A partial workaround can be found [here](https://github.com/ReactiveX/RxSwift/issues/2127#issuecomment-717830502). + +Create a `Package.swift` file. + +```swift +// swift-tools-version:5.0 + +import PackageDescription + +let package = Package( + name: "RxTestProject", + dependencies: [ + .package(url: "https://github.com/ReactiveX/RxSwift.git", .exact("6.5.0")) + ], + targets: [ + .target(name: "RxTestProject", dependencies: ["RxSwift", "RxCocoa"]) + ] +) +``` + +```bash +$ swift build +``` + +To build or test a module with RxTest dependency, set `TEST=1`. + +```bash +$ TEST=1 swift test +``` + +### Manually using git submodules + +* Add RxSwift as a submodule + +```bash +$ git submodule add git@github.com:ReactiveX/RxSwift.git +``` + +* Drag `Rx.xcodeproj` into Project Navigator +* Go to `Project > Targets > Build Phases > Link Binary With Libraries`, click `+` and select `RxSwift`, `RxCocoa` and `RxRelay` targets + +## References + +* [http://reactivex.io/](http://reactivex.io/) +* [Reactive Extensions GitHub (GitHub)](https://github.com/Reactive-Extensions) +* [RxSwift RayWenderlich.com Book](https://store.raywenderlich.com/products/rxswift-reactive-programming-with-swift) +* [RxSwift: Debunking the myth of hard (YouTube)](https://www.youtube.com/watch?v=GdvLP0ZAhhc) +* [Boxue.io RxSwift Online Course](https://boxueio.com/series/rxswift-101) (Chinese 🇨🇳) +* [Expert to Expert: Brian Beckman and Erik Meijer - Inside the .NET Reactive Framework (Rx) (video)](https://youtu.be/looJcaeboBY) +* [Reactive Programming Overview (Jafar Husain from Netflix)](https://youtu.be/-8Y1-lE6NSA) +* [Subject/Observer is Dual to Iterator (paper)](http://csl.stanford.edu/~christos/pldi2010.fit/meijer.duality.pdf) +* [Rx standard sequence operators visualized (visualization tool)](http://rxmarbles.com/) +* [Haskell](https://www.haskell.org/) diff --git a/Pods/RxRelay/RxRelay/BehaviorRelay.swift b/Pods/RxRelay/RxRelay/BehaviorRelay.swift new file mode 100644 index 0000000..e02fc8f --- /dev/null +++ b/Pods/RxRelay/RxRelay/BehaviorRelay.swift @@ -0,0 +1,42 @@ +// +// BehaviorRelay.swift +// RxRelay +// +// Created by Krunoslav Zaher on 10/7/17. +// Copyright © 2017 Krunoslav Zaher. All rights reserved. +// + +import RxSwift + +/// BehaviorRelay is a wrapper for `BehaviorSubject`. +/// +/// Unlike `BehaviorSubject` it can't terminate with error or completed. +public final class BehaviorRelay: ObservableType { + private let subject: BehaviorSubject + + /// Accepts `event` and emits it to subscribers + public func accept(_ event: Element) { + self.subject.onNext(event) + } + + /// Current value of behavior subject + public var value: Element { + // this try! is ok because subject can't error out or be disposed + return try! self.subject.value() + } + + /// Initializes behavior relay with initial value. + public init(value: Element) { + self.subject = BehaviorSubject(value: value) + } + + /// Subscribes observer + public func subscribe(_ observer: Observer) -> Disposable where Observer.Element == Element { + self.subject.subscribe(observer) + } + + /// - returns: Canonical interface for push style sequence + public func asObservable() -> Observable { + self.subject.asObservable() + } +} diff --git a/Pods/RxRelay/RxRelay/Observable+Bind.swift b/Pods/RxRelay/RxRelay/Observable+Bind.swift new file mode 100644 index 0000000..08c4a97 --- /dev/null +++ b/Pods/RxRelay/RxRelay/Observable+Bind.swift @@ -0,0 +1,149 @@ +// +// Observable+Bind.swift +// RxRelay +// +// Created by Shai Mishali on 09/04/2019. +// Copyright © 2019 Krunoslav Zaher. All rights reserved. +// + +import RxSwift + +extension ObservableType { + /** + Creates new subscription and sends elements to publish relay(s). + In case error occurs in debug mode, `fatalError` will be raised. + In case error occurs in release mode, `error` will be logged. + - parameter relays: Target publish relays for sequence elements. + - returns: Disposable object that can be used to unsubscribe the observer. + */ + public func bind(to relays: PublishRelay...) -> Disposable { + bind(to: relays) + } + + /** + Creates new subscription and sends elements to publish relay(s). + + In case error occurs in debug mode, `fatalError` will be raised. + In case error occurs in release mode, `error` will be logged. + + - parameter relays: Target publish relays for sequence elements. + - returns: Disposable object that can be used to unsubscribe the observer. + */ + public func bind(to relays: PublishRelay...) -> Disposable { + self.map { $0 as Element? }.bind(to: relays) + } + + /** + Creates new subscription and sends elements to publish relay(s). + In case error occurs in debug mode, `fatalError` will be raised. + In case error occurs in release mode, `error` will be logged. + - parameter relays: Target publish relays for sequence elements. + - returns: Disposable object that can be used to unsubscribe the observer. + */ + private func bind(to relays: [PublishRelay]) -> Disposable { + subscribe { e in + switch e { + case let .next(element): + relays.forEach { + $0.accept(element) + } + case let .error(error): + rxFatalErrorInDebug("Binding error to publish relay: \(error)") + case .completed: + break + } + } + } + + /** + Creates new subscription and sends elements to behavior relay(s). + In case error occurs in debug mode, `fatalError` will be raised. + In case error occurs in release mode, `error` will be logged. + - parameter relays: Target behavior relay for sequence elements. + - returns: Disposable object that can be used to unsubscribe the observer. + */ + public func bind(to relays: BehaviorRelay...) -> Disposable { + self.bind(to: relays) + } + + /** + Creates new subscription and sends elements to behavior relay(s). + + In case error occurs in debug mode, `fatalError` will be raised. + In case error occurs in release mode, `error` will be logged. + + - parameter relays: Target behavior relay for sequence elements. + - returns: Disposable object that can be used to unsubscribe the observer. + */ + public func bind(to relays: BehaviorRelay...) -> Disposable { + self.map { $0 as Element? }.bind(to: relays) + } + + /** + Creates new subscription and sends elements to behavior relay(s). + In case error occurs in debug mode, `fatalError` will be raised. + In case error occurs in release mode, `error` will be logged. + - parameter relays: Target behavior relay for sequence elements. + - returns: Disposable object that can be used to unsubscribe the observer. + */ + private func bind(to relays: [BehaviorRelay]) -> Disposable { + subscribe { e in + switch e { + case let .next(element): + relays.forEach { + $0.accept(element) + } + case let .error(error): + rxFatalErrorInDebug("Binding error to behavior relay: \(error)") + case .completed: + break + } + } + } + + /** + Creates new subscription and sends elements to replay relay(s). + In case error occurs in debug mode, `fatalError` will be raised. + In case error occurs in release mode, `error` will be logged. + - parameter relays: Target replay relay for sequence elements. + - returns: Disposable object that can be used to unsubscribe the observer. + */ + public func bind(to relays: ReplayRelay...) -> Disposable { + self.bind(to: relays) + } + + /** + Creates new subscription and sends elements to replay relay(s). + + In case error occurs in debug mode, `fatalError` will be raised. + In case error occurs in release mode, `error` will be logged. + + - parameter relays: Target replay relay for sequence elements. + - returns: Disposable object that can be used to unsubscribe the observer. + */ + public func bind(to relays: ReplayRelay...) -> Disposable { + self.map { $0 as Element? }.bind(to: relays) + } + + /** + Creates new subscription and sends elements to replay relay(s). + In case error occurs in debug mode, `fatalError` will be raised. + In case error occurs in release mode, `error` will be logged. + - parameter relays: Target replay relay for sequence elements. + - returns: Disposable object that can be used to unsubscribe the observer. + */ + private func bind(to relays: [ReplayRelay]) -> Disposable { + subscribe { e in + switch e { + case let .next(element): + relays.forEach { + $0.accept(element) + } + case let .error(error): + rxFatalErrorInDebug("Binding error to behavior relay: \(error)") + case .completed: + break + } + } + } +} diff --git a/Pods/RxRelay/RxRelay/PublishRelay.swift b/Pods/RxRelay/RxRelay/PublishRelay.swift new file mode 100644 index 0000000..a9c8ac4 --- /dev/null +++ b/Pods/RxRelay/RxRelay/PublishRelay.swift @@ -0,0 +1,36 @@ +// +// PublishRelay.swift +// RxRelay +// +// Created by Krunoslav Zaher on 3/28/15. +// Copyright © 2017 Krunoslav Zaher. All rights reserved. +// + +import RxSwift + +/// PublishRelay is a wrapper for `PublishSubject`. +/// +/// Unlike `PublishSubject` it can't terminate with error or completed. +public final class PublishRelay: ObservableType { + private let subject: PublishSubject + + // Accepts `event` and emits it to subscribers + public func accept(_ event: Element) { + self.subject.onNext(event) + } + + /// Initializes with internal empty subject. + public init() { + self.subject = PublishSubject() + } + + /// Subscribes observer + public func subscribe(_ observer: Observer) -> Disposable where Observer.Element == Element { + self.subject.subscribe(observer) + } + + /// - returns: Canonical interface for push style sequence + public func asObservable() -> Observable { + self.subject.asObservable() + } +} diff --git a/Pods/RxRelay/RxRelay/ReplayRelay.swift b/Pods/RxRelay/RxRelay/ReplayRelay.swift new file mode 100644 index 0000000..3cc87cd --- /dev/null +++ b/Pods/RxRelay/RxRelay/ReplayRelay.swift @@ -0,0 +1,50 @@ +// +// ReplayRelay.swift +// RxRelay +// +// Created by Zsolt Kovacs on 12/22/19. +// Copyright © 2019 Krunoslav Zaher. All rights reserved. +// + +import RxSwift + +/// ReplayRelay is a wrapper for `ReplaySubject`. +/// +/// Unlike `ReplaySubject` it can't terminate with an error or complete. +public final class ReplayRelay: ObservableType { + private let subject: ReplaySubject + + // Accepts `event` and emits it to subscribers + public func accept(_ event: Element) { + self.subject.onNext(event) + } + + private init(subject: ReplaySubject) { + self.subject = subject + } + + /// Creates new instance of `ReplayRelay` that replays at most `bufferSize` last elements sent to it. + /// + /// - parameter bufferSize: Maximal number of elements to replay to observers after subscription. + /// - returns: New instance of replay relay. + public static func create(bufferSize: Int) -> ReplayRelay { + ReplayRelay(subject: ReplaySubject.create(bufferSize: bufferSize)) + } + + /// Creates a new instance of `ReplayRelay` that buffers all the sent to it. + /// To avoid filling up memory, developer needs to make sure that the use case will only ever store a 'reasonable' + /// number of elements. + public static func createUnbound() -> ReplayRelay { + ReplayRelay(subject: ReplaySubject.createUnbounded()) + } + + /// Subscribes observer + public func subscribe(_ observer: Observer) -> Disposable where Observer.Element == Element { + self.subject.subscribe(observer) + } + + /// - returns: Canonical interface for push style sequence + public func asObservable() -> Observable { + self.subject.asObserver() + } +} diff --git a/Pods/RxRelay/RxRelay/Utils.swift b/Pods/RxRelay/RxRelay/Utils.swift new file mode 100644 index 0000000..5954fb9 --- /dev/null +++ b/Pods/RxRelay/RxRelay/Utils.swift @@ -0,0 +1,17 @@ +// +// Utils.swift +// RxRelay +// +// Created by Shai Mishali on 09/04/2019. +// Copyright © 2019 Krunoslav Zaher. All rights reserved. +// + +import Foundation + +func rxFatalErrorInDebug(_ lastMessage: @autoclosure () -> String, file: StaticString = #file, line: UInt = #line) { + #if DEBUG + fatalError(lastMessage(), file: file, line: line) + #else + print("\(file):\(line): \(lastMessage())") + #endif +} diff --git a/Pods/RxSwift/LICENSE.md b/Pods/RxSwift/LICENSE.md new file mode 100644 index 0000000..e32511b --- /dev/null +++ b/Pods/RxSwift/LICENSE.md @@ -0,0 +1,9 @@ +**The MIT License** +**Copyright © 2015 Krunoslav Zaher, Shai Mishali** +**All rights reserved.** + +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/RxSwift/Platform/AtomicInt.swift b/Pods/RxSwift/Platform/AtomicInt.swift new file mode 100644 index 0000000..98479fd --- /dev/null +++ b/Pods/RxSwift/Platform/AtomicInt.swift @@ -0,0 +1,71 @@ +// +// AtomicInt.swift +// Platform +// +// Created by Krunoslav Zaher on 10/28/18. +// Copyright © 2018 Krunoslav Zaher. All rights reserved. +// + +import Foundation + +final class AtomicInt: NSLock { + fileprivate var value: Int32 + public init(_ value: Int32 = 0) { + self.value = value + } +} + +@discardableResult +@inline(__always) +func add(_ this: AtomicInt, _ value: Int32) -> Int32 { + this.lock() + let oldValue = this.value + this.value += value + this.unlock() + return oldValue +} + +@discardableResult +@inline(__always) +func sub(_ this: AtomicInt, _ value: Int32) -> Int32 { + this.lock() + let oldValue = this.value + this.value -= value + this.unlock() + return oldValue +} + +@discardableResult +@inline(__always) +func fetchOr(_ this: AtomicInt, _ mask: Int32) -> Int32 { + this.lock() + let oldValue = this.value + this.value |= mask + this.unlock() + return oldValue +} + +@inline(__always) +func load(_ this: AtomicInt) -> Int32 { + this.lock() + let oldValue = this.value + this.unlock() + return oldValue +} + +@discardableResult +@inline(__always) +func increment(_ this: AtomicInt) -> Int32 { + add(this, 1) +} + +@discardableResult +@inline(__always) +func decrement(_ this: AtomicInt) -> Int32 { + sub(this, 1) +} + +@inline(__always) +func isFlagSet(_ this: AtomicInt, _ mask: Int32) -> Bool { + (load(this) & mask) != 0 +} diff --git a/Pods/RxSwift/Platform/DataStructures/Bag.swift b/Pods/RxSwift/Platform/DataStructures/Bag.swift new file mode 100644 index 0000000..5720a3b --- /dev/null +++ b/Pods/RxSwift/Platform/DataStructures/Bag.swift @@ -0,0 +1,181 @@ +// +// Bag.swift +// Platform +// +// Created by Krunoslav Zaher on 2/28/15. +// Copyright © 2015 Krunoslav Zaher. All rights reserved. +// + +import Swift + +let arrayDictionaryMaxSize = 30 + +struct BagKey { + /** + Unique identifier for object added to `Bag`. + + It's underlying type is UInt64. If we assume there in an idealized CPU that works at 4GHz, + it would take ~150 years of continuous running time for it to overflow. + */ + fileprivate let rawValue: UInt64 +} + +/** +Data structure that represents a bag of elements typed `T`. + +Single element can be stored multiple times. + +Time and space complexity of insertion and deletion is O(n). + +It is suitable for storing small number of elements. +*/ +struct Bag : CustomDebugStringConvertible { + /// Type of identifier for inserted elements. + typealias KeyType = BagKey + + typealias Entry = (key: BagKey, value: T) + + private var _nextKey: BagKey = BagKey(rawValue: 0) + + // data + + // first fill inline variables + var _key0: BagKey? + var _value0: T? + + // then fill "array dictionary" + var _pairs = ContiguousArray() + + // last is sparse dictionary + var _dictionary: [BagKey: T]? + + var _onlyFastPath = true + + /// Creates new empty `Bag`. + init() { + } + + /** + Inserts `value` into bag. + + - parameter element: Element to insert. + - returns: Key that can be used to remove element from bag. + */ + mutating func insert(_ element: T) -> BagKey { + let key = _nextKey + + _nextKey = BagKey(rawValue: _nextKey.rawValue &+ 1) + + if _key0 == nil { + _key0 = key + _value0 = element + return key + } + + _onlyFastPath = false + + if _dictionary != nil { + _dictionary![key] = element + return key + } + + if _pairs.count < arrayDictionaryMaxSize { + _pairs.append((key: key, value: element)) + return key + } + + _dictionary = [key: element] + + return key + } + + /// - returns: Number of elements in bag. + var count: Int { + let dictionaryCount: Int = _dictionary?.count ?? 0 + return (_value0 != nil ? 1 : 0) + _pairs.count + dictionaryCount + } + + /// Removes all elements from bag and clears capacity. + mutating func removeAll() { + _key0 = nil + _value0 = nil + + _pairs.removeAll(keepingCapacity: false) + _dictionary?.removeAll(keepingCapacity: false) + } + + /** + Removes element with a specific `key` from bag. + + - parameter key: Key that identifies element to remove from bag. + - returns: Element that bag contained, or nil in case element was already removed. + */ + mutating func removeKey(_ key: BagKey) -> T? { + if _key0 == key { + _key0 = nil + let value = _value0! + _value0 = nil + return value + } + + if let existingObject = _dictionary?.removeValue(forKey: key) { + return existingObject + } + + for i in 0 ..< _pairs.count where _pairs[i].key == key { + let value = _pairs[i].value + _pairs.remove(at: i) + return value + } + + return nil + } +} + +extension Bag { + /// A textual representation of `self`, suitable for debugging. + var debugDescription : String { + "\(self.count) elements in Bag" + } +} + +extension Bag { + /// Enumerates elements inside the bag. + /// + /// - parameter action: Enumeration closure. + func forEach(_ action: (T) -> Void) { + if _onlyFastPath { + if let value0 = _value0 { + action(value0) + } + return + } + + let value0 = _value0 + let dictionary = _dictionary + + if let value0 = value0 { + action(value0) + } + + for i in 0 ..< _pairs.count { + action(_pairs[i].value) + } + + if dictionary?.count ?? 0 > 0 { + for element in dictionary!.values { + action(element) + } + } + } +} + +extension BagKey: Hashable { + func hash(into hasher: inout Hasher) { + hasher.combine(rawValue) + } +} + +func ==(lhs: BagKey, rhs: BagKey) -> Bool { + lhs.rawValue == rhs.rawValue +} diff --git a/Pods/RxSwift/Platform/DataStructures/InfiniteSequence.swift b/Pods/RxSwift/Platform/DataStructures/InfiniteSequence.swift new file mode 100644 index 0000000..75d7bea --- /dev/null +++ b/Pods/RxSwift/Platform/DataStructures/InfiniteSequence.swift @@ -0,0 +1,23 @@ +// +// InfiniteSequence.swift +// Platform +// +// Created by Krunoslav Zaher on 6/13/15. +// Copyright © 2015 Krunoslav Zaher. All rights reserved. +// + +/// Sequence that repeats `repeatedValue` infinite number of times. +struct InfiniteSequence : Sequence { + typealias Iterator = AnyIterator + + private let repeatedValue: Element + + init(repeatedValue: Element) { + self.repeatedValue = repeatedValue + } + + func makeIterator() -> Iterator { + let repeatedValue = self.repeatedValue + return AnyIterator { repeatedValue } + } +} diff --git a/Pods/RxSwift/Platform/DataStructures/PriorityQueue.swift b/Pods/RxSwift/Platform/DataStructures/PriorityQueue.swift new file mode 100644 index 0000000..9ed856b --- /dev/null +++ b/Pods/RxSwift/Platform/DataStructures/PriorityQueue.swift @@ -0,0 +1,111 @@ +// +// PriorityQueue.swift +// Platform +// +// Created by Krunoslav Zaher on 12/27/15. +// Copyright © 2015 Krunoslav Zaher. All rights reserved. +// + +struct PriorityQueue { + private let hasHigherPriority: (Element, Element) -> Bool + private let isEqual: (Element, Element) -> Bool + + private var elements = [Element]() + + init(hasHigherPriority: @escaping (Element, Element) -> Bool, isEqual: @escaping (Element, Element) -> Bool) { + self.hasHigherPriority = hasHigherPriority + self.isEqual = isEqual + } + + mutating func enqueue(_ element: Element) { + elements.append(element) + bubbleToHigherPriority(elements.count - 1) + } + + func peek() -> Element? { + elements.first + } + + var isEmpty: Bool { + elements.count == 0 + } + + mutating func dequeue() -> Element? { + guard let front = peek() else { + return nil + } + + removeAt(0) + + return front + } + + mutating func remove(_ element: Element) { + for i in 0 ..< elements.count { + if self.isEqual(elements[i], element) { + removeAt(i) + return + } + } + } + + private mutating func removeAt(_ index: Int) { + let removingLast = index == elements.count - 1 + if !removingLast { + elements.swapAt(index, elements.count - 1) + } + + _ = elements.popLast() + + if !removingLast { + bubbleToHigherPriority(index) + bubbleToLowerPriority(index) + } + } + + private mutating func bubbleToHigherPriority(_ initialUnbalancedIndex: Int) { + precondition(initialUnbalancedIndex >= 0) + precondition(initialUnbalancedIndex < elements.count) + + var unbalancedIndex = initialUnbalancedIndex + + while unbalancedIndex > 0 { + let parentIndex = (unbalancedIndex - 1) / 2 + guard self.hasHigherPriority(elements[unbalancedIndex], elements[parentIndex]) else { break } + elements.swapAt(unbalancedIndex, parentIndex) + unbalancedIndex = parentIndex + } + } + + private mutating func bubbleToLowerPriority(_ initialUnbalancedIndex: Int) { + precondition(initialUnbalancedIndex >= 0) + precondition(initialUnbalancedIndex < elements.count) + + var unbalancedIndex = initialUnbalancedIndex + while true { + let leftChildIndex = unbalancedIndex * 2 + 1 + let rightChildIndex = unbalancedIndex * 2 + 2 + + var highestPriorityIndex = unbalancedIndex + + if leftChildIndex < elements.count && self.hasHigherPriority(elements[leftChildIndex], elements[highestPriorityIndex]) { + highestPriorityIndex = leftChildIndex + } + + if rightChildIndex < elements.count && self.hasHigherPriority(elements[rightChildIndex], elements[highestPriorityIndex]) { + highestPriorityIndex = rightChildIndex + } + + guard highestPriorityIndex != unbalancedIndex else { break } + elements.swapAt(highestPriorityIndex, unbalancedIndex) + + unbalancedIndex = highestPriorityIndex + } + } +} + +extension PriorityQueue : CustomDebugStringConvertible { + var debugDescription: String { + elements.debugDescription + } +} diff --git a/Pods/RxSwift/Platform/DataStructures/Queue.swift b/Pods/RxSwift/Platform/DataStructures/Queue.swift new file mode 100644 index 0000000..625d473 --- /dev/null +++ b/Pods/RxSwift/Platform/DataStructures/Queue.swift @@ -0,0 +1,148 @@ +// +// Queue.swift +// Platform +// +// Created by Krunoslav Zaher on 3/21/15. +// Copyright © 2015 Krunoslav Zaher. All rights reserved. +// + +/** +Data structure that represents queue. + +Complexity of `enqueue`, `dequeue` is O(1) when number of operations is +averaged over N operations. + +Complexity of `peek` is O(1). +*/ +struct Queue: Sequence { + /// Type of generator. + typealias Generator = AnyIterator + + private let resizeFactor = 2 + + private var storage: ContiguousArray + private var innerCount = 0 + private var pushNextIndex = 0 + private let initialCapacity: Int + + /** + Creates new queue. + + - parameter capacity: Capacity of newly created queue. + */ + init(capacity: Int) { + initialCapacity = capacity + + storage = ContiguousArray(repeating: nil, count: capacity) + } + + private var dequeueIndex: Int { + let index = pushNextIndex - count + return index < 0 ? index + storage.count : index + } + + /// - returns: Is queue empty. + var isEmpty: Bool { count == 0 } + + /// - returns: Number of elements inside queue. + var count: Int { innerCount } + + /// - returns: Element in front of a list of elements to `dequeue`. + func peek() -> T { + precondition(count > 0) + + return storage[dequeueIndex]! + } + + mutating private func resizeTo(_ size: Int) { + var newStorage = ContiguousArray(repeating: nil, count: size) + + let count = self.count + + let dequeueIndex = self.dequeueIndex + let spaceToEndOfQueue = storage.count - dequeueIndex + + // first batch is from dequeue index to end of array + let countElementsInFirstBatch = Swift.min(count, spaceToEndOfQueue) + // second batch is wrapped from start of array to end of queue + let numberOfElementsInSecondBatch = count - countElementsInFirstBatch + + newStorage[0 ..< countElementsInFirstBatch] = storage[dequeueIndex ..< (dequeueIndex + countElementsInFirstBatch)] + newStorage[countElementsInFirstBatch ..< (countElementsInFirstBatch + numberOfElementsInSecondBatch)] = storage[0 ..< numberOfElementsInSecondBatch] + + self.innerCount = count + pushNextIndex = count + storage = newStorage + } + + /// Enqueues `element`. + /// + /// - parameter element: Element to enqueue. + mutating func enqueue(_ element: T) { + if count == storage.count { + resizeTo(Swift.max(storage.count, 1) * resizeFactor) + } + + storage[pushNextIndex] = element + pushNextIndex += 1 + innerCount += 1 + + if pushNextIndex >= storage.count { + pushNextIndex -= storage.count + } + } + + private mutating func dequeueElementOnly() -> T { + precondition(count > 0) + + let index = dequeueIndex + + defer { + storage[index] = nil + innerCount -= 1 + } + + return storage[index]! + } + + /// Dequeues element or throws an exception in case queue is empty. + /// + /// - returns: Dequeued element. + mutating func dequeue() -> T? { + if self.count == 0 { + return nil + } + + defer { + let downsizeLimit = storage.count / (resizeFactor * resizeFactor) + if count < downsizeLimit && downsizeLimit >= initialCapacity { + resizeTo(storage.count / resizeFactor) + } + } + + return dequeueElementOnly() + } + + /// - returns: Generator of contained elements. + func makeIterator() -> AnyIterator { + var i = dequeueIndex + var innerCount = count + + return AnyIterator { + if innerCount == 0 { + return nil + } + + defer { + innerCount -= 1 + i += 1 + } + + if i >= self.storage.count { + i -= self.storage.count + } + + return self.storage[i] + } + } +} diff --git a/Pods/RxSwift/Platform/DispatchQueue+Extensions.swift b/Pods/RxSwift/Platform/DispatchQueue+Extensions.swift new file mode 100644 index 0000000..aaf24ca --- /dev/null +++ b/Pods/RxSwift/Platform/DispatchQueue+Extensions.swift @@ -0,0 +1,21 @@ +// +// DispatchQueue+Extensions.swift +// Platform +// +// Created by Krunoslav Zaher on 10/22/16. +// Copyright © 2016 Krunoslav Zaher. All rights reserved. +// + +import Dispatch + +extension DispatchQueue { + private static var token: DispatchSpecificKey<()> = { + let key = DispatchSpecificKey<()>() + DispatchQueue.main.setSpecific(key: key, value: ()) + return key + }() + + static var isMain: Bool { + DispatchQueue.getSpecific(key: token) != nil + } +} diff --git a/Pods/RxSwift/Platform/Platform.Darwin.swift b/Pods/RxSwift/Platform/Platform.Darwin.swift new file mode 100644 index 0000000..eacc194 --- /dev/null +++ b/Pods/RxSwift/Platform/Platform.Darwin.swift @@ -0,0 +1,35 @@ +// +// Platform.Darwin.swift +// Platform +// +// Created by Krunoslav Zaher on 12/29/15. +// Copyright © 2015 Krunoslav Zaher. All rights reserved. +// + +#if os(macOS) || os(iOS) || os(tvOS) || os(watchOS) + + import Darwin + import Foundation + + extension Thread { + static func setThreadLocalStorageValue(_ value: T?, forKey key: NSCopying) { + let currentThread = Thread.current + let threadDictionary = currentThread.threadDictionary + + if let newValue = value { + threadDictionary[key] = newValue + } + else { + threadDictionary[key] = nil + } + } + + static func getThreadLocalStorageValueForKey(_ key: NSCopying) -> T? { + let currentThread = Thread.current + let threadDictionary = currentThread.threadDictionary + + return threadDictionary[key] as? T + } + } + +#endif diff --git a/Pods/RxSwift/Platform/Platform.Linux.swift b/Pods/RxSwift/Platform/Platform.Linux.swift new file mode 100644 index 0000000..52a3e3a --- /dev/null +++ b/Pods/RxSwift/Platform/Platform.Linux.swift @@ -0,0 +1,32 @@ +// +// Platform.Linux.swift +// Platform +// +// Created by Krunoslav Zaher on 12/29/15. +// Copyright © 2015 Krunoslav Zaher. All rights reserved. +// + +#if os(Linux) + + import Foundation + + extension Thread { + + static func setThreadLocalStorageValue(_ value: T?, forKey key: String) { + if let newValue = value { + Thread.current.threadDictionary[key] = newValue + } + else { + Thread.current.threadDictionary[key] = nil + } + } + + static func getThreadLocalStorageValueForKey(_ key: String) -> T? { + let currentThread = Thread.current + let threadDictionary = currentThread.threadDictionary + + return threadDictionary[key] as? T + } + } + +#endif diff --git a/Pods/RxSwift/Platform/RecursiveLock.swift b/Pods/RxSwift/Platform/RecursiveLock.swift new file mode 100644 index 0000000..10b9bbb --- /dev/null +++ b/Pods/RxSwift/Platform/RecursiveLock.swift @@ -0,0 +1,34 @@ +// +// RecursiveLock.swift +// Platform +// +// Created by Krunoslav Zaher on 12/18/16. +// Copyright © 2016 Krunoslav Zaher. All rights reserved. +// + +import Foundation + +#if TRACE_RESOURCES + class RecursiveLock: NSRecursiveLock { + override init() { + _ = Resources.incrementTotal() + super.init() + } + + override func lock() { + super.lock() + _ = Resources.incrementTotal() + } + + override func unlock() { + super.unlock() + _ = Resources.decrementTotal() + } + + deinit { + _ = Resources.decrementTotal() + } + } +#else + typealias RecursiveLock = NSRecursiveLock +#endif diff --git a/Pods/RxSwift/README.md b/Pods/RxSwift/README.md new file mode 100644 index 0000000..a95d9e0 --- /dev/null +++ b/Pods/RxSwift/README.md @@ -0,0 +1,254 @@ +

+RxSwift Logo +
+Build Status +Supported Platforms: iOS, macOS, tvOS, watchOS & Linux +
+ + + +

+ +Rx is a [generic abstraction of computation](https://youtu.be/looJcaeboBY) expressed through `Observable` interface, which lets you broadcast and subscribe to values and other events from an `Observable` stream. + +RxSwift is the Swift-specific implementation of the [Reactive Extensions](http://reactivex.io) standard. + +

RxSwift Observable Example of a price constantly changing and updating the app's UI

+ +While this version aims to stay true to the original spirit and naming conventions of Rx, this projects also aims to provide a true Swift-first API for Rx APIs. + +Cross platform documentation can be found on [ReactiveX.io](http://reactivex.io/). + +Like other Rx implementation, RxSwift's intention is to enable easy composition of asynchronous operations and streams of data in the form of `Observable` objects and a suite of methods to transform and compose these pieces of asynchronous work. + +KVO observation, async operations, UI Events and other streams of data are all unified under [abstraction of sequence](Documentation/GettingStarted.md#observables-aka-sequences). This is the reason why Rx is so simple, elegant and powerful. + +## I came here because I want to ... + +###### ... understand + +* [why use rx?](Documentation/Why.md) +* [the basics, getting started with RxSwift](Documentation/GettingStarted.md) +* [traits](Documentation/Traits.md) - what are `Single`, `Completable`, `Maybe`, `Driver`, and `ControlProperty` ... and why do they exist? +* [testing](Documentation/UnitTests.md) +* [tips and common errors](Documentation/Tips.md) +* [debugging](Documentation/GettingStarted.md#debugging) +* [the math behind Rx](Documentation/MathBehindRx.md) +* [what are hot and cold observable sequences?](Documentation/HotAndColdObservables.md) + +###### ... install + +* Integrate RxSwift/RxCocoa with my app. [Installation Guide](#installation) + +###### ... hack around + +* with the example app. [Running Example App](Documentation/ExampleApp.md) +* with operators in playgrounds. [Playgrounds](Documentation/Playgrounds.md) + +###### ... interact + +* All of this is great, but it would be nice to talk with other people using RxSwift and exchange experiences.
[Join Slack Channel](http://slack.rxswift.org) +* Report a problem using the library. [Open an Issue With Bug Template](.github/ISSUE_TEMPLATE.md) +* Request a new feature. [Open an Issue With Feature Request Template](Documentation/NewFeatureRequestTemplate.md) +* Help out [Check out contribution guide](CONTRIBUTING.md) + +###### ... compare + +* [with Combine and ReactiveSwift](Documentation/ComparisonWithOtherLibraries.md). + +###### ... understand the structure + +RxSwift is as compositional as the asynchronous work it drives. The core unit is RxSwift itself, while other dependencies can be added for UI Work, testing, and more. + +It comprises five separate components depending on each other in the following way: + +```none +┌──────────────┐ ┌──────────────┐ +│ RxCocoa ├────▶ RxRelay │ +└───────┬──────┘ └──────┬───────┘ + │ │ +┌───────▼──────────────────▼───────┐ +│ RxSwift │ +└───────▲──────────────────▲───────┘ + │ │ +┌───────┴──────┐ ┌──────┴───────┐ +│ RxTest │ │ RxBlocking │ +└──────────────┘ └──────────────┘ +``` + +* **RxSwift**: The core of RxSwift, providing the Rx standard as (mostly) defined by [ReactiveX](https://reactivex.io). It has no other dependencies. +* **RxCocoa**: Provides Cocoa-specific capabilities for general iOS/macOS/watchOS & tvOS app development, such as Shared Sequences, Traits, and much more. It depends on both `RxSwift` and `RxRelay`. +* **RxRelay**: Provides `PublishRelay`, `BehaviorRelay` and `ReplayRelay`, three [simple wrappers around Subjects](https://github.com/ReactiveX/RxSwift/blob/main/Documentation/Subjects.md#relays). It depends on `RxSwift`. +* **RxTest** and **RxBlocking**: Provides testing capabilities for Rx-based systems. It depends on `RxSwift`. + +## Usage + + + + + + + + + + + + + + + + + + + +
Here's an exampleIn Action
Define search for GitHub repositories ...
+let searchResults = searchBar.rx.text.orEmpty
+    .throttle(.milliseconds(300), scheduler: MainScheduler.instance)
+    .distinctUntilChanged()
+    .flatMapLatest { query -> Observable<[Repository]> in
+        if query.isEmpty {
+            return .just([])
+        }
+        return searchGitHub(query)
+            .catchAndReturn([])
+    }
+    .observe(on: MainScheduler.instance)
... then bind the results to your tableview
+searchResults
+    .bind(to: tableView.rx.items(cellIdentifier: "Cell")) {
+        (index, repository: Repository, cell) in
+        cell.textLabel?.text = repository.name
+        cell.detailTextLabel?.text = repository.url
+    }
+    .disposed(by: disposeBag)
+ + +## Requirements + +* Xcode 12.x +* Swift 5.x + +For Xcode 11 and below, [use RxSwift 5.x](https://github.com/ReactiveX/RxSwift/releases/tag/5.1.1). + +## Installation + +RxSwift doesn't contain any external dependencies. + +These are currently the supported installation options: + +### Manual + +Open Rx.xcworkspace, choose `RxExample` and hit run. This method will build everything and run the sample app + +### [CocoaPods](https://guides.cocoapods.org/using/using-cocoapods.html) + +```ruby +# Podfile +use_frameworks! + +target 'YOUR_TARGET_NAME' do + pod 'RxSwift', '6.5.0' + pod 'RxCocoa', '6.5.0' +end + +# RxTest and RxBlocking make the most sense in the context of unit/integration tests +target 'YOUR_TESTING_TARGET' do + pod 'RxBlocking', '6.5.0' + pod 'RxTest', '6.5.0' +end +``` + +Replace `YOUR_TARGET_NAME` and then, in the `Podfile` directory, type: + +```bash +$ pod install +``` + +### XCFrameworks + +Each release starting with RxSwift 6 includes `*.xcframework` framework binaries. + +Simply drag the needed framework binaries to your **Frameworks, Libraries, and Embedded Content** section under your target's **General** tab. + +> **Note**: If you're using `RxCocoa`, be sure to also drag **RxCocoaRuntime.xcframework** before importing `RxCocoa`. + +XCFrameworks instructions + +### [Carthage](https://github.com/Carthage/Carthage) + +Add this to `Cartfile` + +``` +github "ReactiveX/RxSwift" "6.5.0" +``` + +```bash +$ carthage update +``` + +#### Carthage as a Static Library + +Carthage defaults to building RxSwift as a Dynamic Library. + +If you wish to build RxSwift as a Static Library using Carthage you may use the script below to manually modify the framework type before building with Carthage: + +```bash +carthage update RxSwift --platform iOS --no-build +sed -i -e 's/MACH_O_TYPE = mh_dylib/MACH_O_TYPE = staticlib/g' Carthage/Checkouts/RxSwift/Rx.xcodeproj/project.pbxproj +carthage build RxSwift --platform iOS +``` + +### [Swift Package Manager](https://github.com/apple/swift-package-manager) + +> **Note**: There is a critical cross-dependency bug affecting many projects including RxSwift in Swift Package Manager. We've [filed a bug (SR-12303)](https://bugs.swift.org/browse/SR-12303) in early 2020 but have no answer yet. Your mileage may vary. A partial workaround can be found [here](https://github.com/ReactiveX/RxSwift/issues/2127#issuecomment-717830502). + +Create a `Package.swift` file. + +```swift +// swift-tools-version:5.0 + +import PackageDescription + +let package = Package( + name: "RxTestProject", + dependencies: [ + .package(url: "https://github.com/ReactiveX/RxSwift.git", .exact("6.5.0")) + ], + targets: [ + .target(name: "RxTestProject", dependencies: ["RxSwift", "RxCocoa"]) + ] +) +``` + +```bash +$ swift build +``` + +To build or test a module with RxTest dependency, set `TEST=1`. + +```bash +$ TEST=1 swift test +``` + +### Manually using git submodules + +* Add RxSwift as a submodule + +```bash +$ git submodule add git@github.com:ReactiveX/RxSwift.git +``` + +* Drag `Rx.xcodeproj` into Project Navigator +* Go to `Project > Targets > Build Phases > Link Binary With Libraries`, click `+` and select `RxSwift`, `RxCocoa` and `RxRelay` targets + +## References + +* [http://reactivex.io/](http://reactivex.io/) +* [Reactive Extensions GitHub (GitHub)](https://github.com/Reactive-Extensions) +* [RxSwift RayWenderlich.com Book](https://store.raywenderlich.com/products/rxswift-reactive-programming-with-swift) +* [RxSwift: Debunking the myth of hard (YouTube)](https://www.youtube.com/watch?v=GdvLP0ZAhhc) +* [Boxue.io RxSwift Online Course](https://boxueio.com/series/rxswift-101) (Chinese 🇨🇳) +* [Expert to Expert: Brian Beckman and Erik Meijer - Inside the .NET Reactive Framework (Rx) (video)](https://youtu.be/looJcaeboBY) +* [Reactive Programming Overview (Jafar Husain from Netflix)](https://youtu.be/-8Y1-lE6NSA) +* [Subject/Observer is Dual to Iterator (paper)](http://csl.stanford.edu/~christos/pldi2010.fit/meijer.duality.pdf) +* [Rx standard sequence operators visualized (visualization tool)](http://rxmarbles.com/) +* [Haskell](https://www.haskell.org/) diff --git a/Pods/RxSwift/RxSwift/AnyObserver.swift b/Pods/RxSwift/RxSwift/AnyObserver.swift new file mode 100644 index 0000000..e92cc81 --- /dev/null +++ b/Pods/RxSwift/RxSwift/AnyObserver.swift @@ -0,0 +1,69 @@ +// +// AnyObserver.swift +// RxSwift +// +// Created by Krunoslav Zaher on 2/28/15. +// Copyright © 2015 Krunoslav Zaher. All rights reserved. +// + +/// A type-erased `ObserverType`. +/// +/// Forwards operations to an arbitrary underlying observer with the same `Element` type, hiding the specifics of the underlying observer type. +public struct AnyObserver : ObserverType { + /// Anonymous event handler type. + public typealias EventHandler = (Event) -> Void + + private let observer: EventHandler + + /// Construct an instance whose `on(event)` calls `eventHandler(event)` + /// + /// - parameter eventHandler: Event handler that observes sequences events. + public init(eventHandler: @escaping EventHandler) { + self.observer = eventHandler + } + + /// Construct an instance whose `on(event)` calls `observer.on(event)` + /// + /// - parameter observer: Observer that receives sequence events. + public init(_ observer: Observer) where Observer.Element == Element { + self.observer = observer.on + } + + /// Send `event` to this observer. + /// + /// - parameter event: Event instance. + public func on(_ event: Event) { + self.observer(event) + } + + /// Erases type of observer and returns canonical observer. + /// + /// - returns: type erased observer. + public func asObserver() -> AnyObserver { + self + } +} + +extension AnyObserver { + /// Collection of `AnyObserver`s + typealias s = Bag<(Event) -> Void> +} + +extension ObserverType { + /// Erases type of observer and returns canonical observer. + /// + /// - returns: type erased observer. + public func asObserver() -> AnyObserver { + AnyObserver(self) + } + + /// Transforms observer of type R to type E using custom transform method. + /// Each event sent to result observer is transformed and sent to `self`. + /// + /// - returns: observer that transforms events. + public func mapObserver(_ transform: @escaping (Result) throws -> Element) -> AnyObserver { + AnyObserver { e in + self.on(e.map(transform)) + } + } +} diff --git a/Pods/RxSwift/RxSwift/Binder.swift b/Pods/RxSwift/RxSwift/Binder.swift new file mode 100644 index 0000000..1aae095 --- /dev/null +++ b/Pods/RxSwift/RxSwift/Binder.swift @@ -0,0 +1,59 @@ +// +// Binder.swift +// RxSwift +// +// Created by Krunoslav Zaher on 9/17/17. +// Copyright © 2017 Krunoslav Zaher. All rights reserved. +// + +/** + Observer that enforces interface binding rules: + * can't bind errors (in debug builds binding of errors causes `fatalError` in release builds errors are being logged) + * ensures binding is performed on a specific scheduler + + `Binder` doesn't retain target and in case target is released, element isn't bound. + + By default it binds elements on main scheduler. + */ +public struct Binder: ObserverType { + public typealias Element = Value + + private let binding: (Event) -> Void + + /// Initializes `Binder` + /// + /// - parameter target: Target object. + /// - parameter scheduler: Scheduler used to bind the events. + /// - parameter binding: Binding logic. + public init(_ target: Target, scheduler: ImmediateSchedulerType = MainScheduler(), binding: @escaping (Target, Value) -> Void) { + weak var weakTarget = target + + self.binding = { event in + switch event { + case .next(let element): + _ = scheduler.schedule(element) { element in + if let target = weakTarget { + binding(target, element) + } + return Disposables.create() + } + case .error(let error): + rxFatalErrorInDebug("Binding error: \(error)") + case .completed: + break + } + } + } + + /// Binds next element to owner view as described in `binding`. + public func on(_ event: Event) { + self.binding(event) + } + + /// Erases type of observer. + /// + /// - returns: type erased observer. + public func asObserver() -> AnyObserver { + AnyObserver(eventHandler: self.on) + } +} diff --git a/Pods/RxSwift/RxSwift/Cancelable.swift b/Pods/RxSwift/RxSwift/Cancelable.swift new file mode 100644 index 0000000..1fa7a67 --- /dev/null +++ b/Pods/RxSwift/RxSwift/Cancelable.swift @@ -0,0 +1,13 @@ +// +// Cancelable.swift +// RxSwift +// +// Created by Krunoslav Zaher on 3/12/15. +// Copyright © 2015 Krunoslav Zaher. All rights reserved. +// + +/// Represents disposable resource with state tracking. +public protocol Cancelable : Disposable { + /// Was resource disposed. + var isDisposed: Bool { get } +} diff --git a/Pods/RxSwift/RxSwift/Concurrency/AsyncLock.swift b/Pods/RxSwift/RxSwift/Concurrency/AsyncLock.swift new file mode 100644 index 0000000..502597e --- /dev/null +++ b/Pods/RxSwift/RxSwift/Concurrency/AsyncLock.swift @@ -0,0 +1,100 @@ +// +// AsyncLock.swift +// RxSwift +// +// Created by Krunoslav Zaher on 3/21/15. +// Copyright © 2015 Krunoslav Zaher. All rights reserved. +// + +/** +In case nobody holds this lock, the work will be queued and executed immediately +on thread that is requesting lock. + +In case there is somebody currently holding that lock, action will be enqueued. +When owned of the lock finishes with it's processing, it will also execute +and pending work. + +That means that enqueued work could possibly be executed later on a different thread. +*/ +final class AsyncLock + : Disposable + , Lock + , SynchronizedDisposeType { + typealias Action = () -> Void + + private var _lock = SpinLock() + + private var queue: Queue = Queue(capacity: 0) + + private var isExecuting: Bool = false + private var hasFaulted: Bool = false + + // lock { + func lock() { + self._lock.lock() + } + + func unlock() { + self._lock.unlock() + } + // } + + private func enqueue(_ action: I) -> I? { + self.lock(); defer { self.unlock() } + if self.hasFaulted { + return nil + } + + if self.isExecuting { + self.queue.enqueue(action) + return nil + } + + self.isExecuting = true + + return action + } + + private func dequeue() -> I? { + self.lock(); defer { self.unlock() } + if !self.queue.isEmpty { + return self.queue.dequeue() + } + else { + self.isExecuting = false + return nil + } + } + + func invoke(_ action: I) { + let firstEnqueuedAction = self.enqueue(action) + + if let firstEnqueuedAction = firstEnqueuedAction { + firstEnqueuedAction.invoke() + } + else { + // action is enqueued, it's somebody else's concern now + return + } + + while true { + let nextAction = self.dequeue() + + if let nextAction = nextAction { + nextAction.invoke() + } + else { + return + } + } + } + + func dispose() { + self.synchronizedDispose() + } + + func synchronized_dispose() { + self.queue = Queue(capacity: 0) + self.hasFaulted = true + } +} diff --git a/Pods/RxSwift/RxSwift/Concurrency/Lock.swift b/Pods/RxSwift/RxSwift/Concurrency/Lock.swift new file mode 100644 index 0000000..7232f23 --- /dev/null +++ b/Pods/RxSwift/RxSwift/Concurrency/Lock.swift @@ -0,0 +1,23 @@ +// +// Lock.swift +// RxSwift +// +// Created by Krunoslav Zaher on 3/31/15. +// Copyright © 2015 Krunoslav Zaher. All rights reserved. +// + +protocol Lock { + func lock() + func unlock() +} + +// https://lists.swift.org/pipermail/swift-dev/Week-of-Mon-20151214/000321.html +typealias SpinLock = RecursiveLock + +extension RecursiveLock : Lock { + @inline(__always) + final func performLocked(_ action: () -> T) -> T { + self.lock(); defer { self.unlock() } + return action() + } +} diff --git a/Pods/RxSwift/RxSwift/Concurrency/LockOwnerType.swift b/Pods/RxSwift/RxSwift/Concurrency/LockOwnerType.swift new file mode 100644 index 0000000..8a98007 --- /dev/null +++ b/Pods/RxSwift/RxSwift/Concurrency/LockOwnerType.swift @@ -0,0 +1,16 @@ +// +// LockOwnerType.swift +// RxSwift +// +// Created by Krunoslav Zaher on 10/25/15. +// Copyright © 2015 Krunoslav Zaher. All rights reserved. +// + +protocol LockOwnerType: AnyObject, Lock { + var lock: RecursiveLock { get } +} + +extension LockOwnerType { + func lock() { self.lock.lock() } + func unlock() { self.lock.unlock() } +} diff --git a/Pods/RxSwift/RxSwift/Concurrency/SynchronizedDisposeType.swift b/Pods/RxSwift/RxSwift/Concurrency/SynchronizedDisposeType.swift new file mode 100644 index 0000000..527a2fb --- /dev/null +++ b/Pods/RxSwift/RxSwift/Concurrency/SynchronizedDisposeType.swift @@ -0,0 +1,18 @@ +// +// SynchronizedDisposeType.swift +// RxSwift +// +// Created by Krunoslav Zaher on 10/25/15. +// Copyright © 2015 Krunoslav Zaher. All rights reserved. +// + +protocol SynchronizedDisposeType: AnyObject, Disposable, Lock { + func synchronized_dispose() +} + +extension SynchronizedDisposeType { + func synchronizedDispose() { + self.lock(); defer { self.unlock() } + self.synchronized_dispose() + } +} diff --git a/Pods/RxSwift/RxSwift/Concurrency/SynchronizedOnType.swift b/Pods/RxSwift/RxSwift/Concurrency/SynchronizedOnType.swift new file mode 100644 index 0000000..19168d7 --- /dev/null +++ b/Pods/RxSwift/RxSwift/Concurrency/SynchronizedOnType.swift @@ -0,0 +1,18 @@ +// +// SynchronizedOnType.swift +// RxSwift +// +// Created by Krunoslav Zaher on 10/25/15. +// Copyright © 2015 Krunoslav Zaher. All rights reserved. +// + +protocol SynchronizedOnType: AnyObject, ObserverType, Lock { + func synchronized_on(_ event: Event) +} + +extension SynchronizedOnType { + func synchronizedOn(_ event: Event) { + self.lock(); defer { self.unlock() } + self.synchronized_on(event) + } +} diff --git a/Pods/RxSwift/RxSwift/Concurrency/SynchronizedUnsubscribeType.swift b/Pods/RxSwift/RxSwift/Concurrency/SynchronizedUnsubscribeType.swift new file mode 100644 index 0000000..988b86f --- /dev/null +++ b/Pods/RxSwift/RxSwift/Concurrency/SynchronizedUnsubscribeType.swift @@ -0,0 +1,13 @@ +// +// SynchronizedUnsubscribeType.swift +// RxSwift +// +// Created by Krunoslav Zaher on 10/25/15. +// Copyright © 2015 Krunoslav Zaher. All rights reserved. +// + +protocol SynchronizedUnsubscribeType: AnyObject { + associatedtype DisposeKey + + func synchronizedUnsubscribe(_ disposeKey: DisposeKey) +} diff --git a/Pods/RxSwift/RxSwift/ConnectableObservableType.swift b/Pods/RxSwift/RxSwift/ConnectableObservableType.swift new file mode 100644 index 0000000..52bf93c --- /dev/null +++ b/Pods/RxSwift/RxSwift/ConnectableObservableType.swift @@ -0,0 +1,19 @@ +// +// ConnectableObservableType.swift +// RxSwift +// +// Created by Krunoslav Zaher on 3/1/15. +// Copyright © 2015 Krunoslav Zaher. All rights reserved. +// + +/** +Represents an observable sequence wrapper that can be connected and disconnected from its underlying observable sequence. +*/ +public protocol ConnectableObservableType : ObservableType { + /** + Connects the observable wrapper to its source. All subscribed observers will receive values from the underlying observable sequence as long as the connection is established. + + - returns: Disposable used to disconnect the observable wrapper from its source, causing subscribed observer to stop receiving values from the underlying observable sequence. + */ + func connect() -> Disposable +} diff --git a/Pods/RxSwift/RxSwift/Date+Dispatch.swift b/Pods/RxSwift/RxSwift/Date+Dispatch.swift new file mode 100644 index 0000000..90f70c5 --- /dev/null +++ b/Pods/RxSwift/RxSwift/Date+Dispatch.swift @@ -0,0 +1,64 @@ +// +// Date+Dispatch.swift +// RxSwift +// +// Created by Krunoslav Zaher on 4/14/19. +// Copyright © 2019 Krunoslav Zaher. All rights reserved. +// + +import Dispatch +import Foundation + +extension DispatchTimeInterval { + var convertToSecondsFactor: Double { + switch self { + case .nanoseconds: return 1_000_000_000.0 + case .microseconds: return 1_000_000.0 + case .milliseconds: return 1_000.0 + case .seconds: return 1.0 + case .never: fatalError() + @unknown default: fatalError() + } + } + + func map(_ transform: (Int, Double) -> Int) -> DispatchTimeInterval { + switch self { + case .nanoseconds(let value): return .nanoseconds(transform(value, 1_000_000_000.0)) + case .microseconds(let value): return .microseconds(transform(value, 1_000_000.0)) + case .milliseconds(let value): return .milliseconds(transform(value, 1_000.0)) + case .seconds(let value): return .seconds(transform(value, 1.0)) + case .never: return .never + @unknown default: fatalError() + } + } + + var isNow: Bool { + switch self { + case .nanoseconds(let value), .microseconds(let value), .milliseconds(let value), .seconds(let value): return value == 0 + case .never: return false + @unknown default: fatalError() + } + } + + internal func reduceWithSpanBetween(earlierDate: Date, laterDate: Date) -> DispatchTimeInterval { + return self.map { value, factor in + let interval = laterDate.timeIntervalSince(earlierDate) + let remainder = Double(value) - interval * factor + guard remainder > 0 else { return 0 } + return Int(remainder.rounded(.toNearestOrAwayFromZero)) + } + } +} + +extension Date { + + internal func addingDispatchInterval(_ dispatchInterval: DispatchTimeInterval) -> Date { + switch dispatchInterval { + case .nanoseconds(let value), .microseconds(let value), .milliseconds(let value), .seconds(let value): + return self.addingTimeInterval(TimeInterval(value) / dispatchInterval.convertToSecondsFactor) + case .never: return Date.distantFuture + @unknown default: fatalError() + } + } + +} diff --git a/Pods/RxSwift/RxSwift/Disposable.swift b/Pods/RxSwift/RxSwift/Disposable.swift new file mode 100644 index 0000000..b79c77a --- /dev/null +++ b/Pods/RxSwift/RxSwift/Disposable.swift @@ -0,0 +1,13 @@ +// +// Disposable.swift +// RxSwift +// +// Created by Krunoslav Zaher on 2/8/15. +// Copyright © 2015 Krunoslav Zaher. All rights reserved. +// + +/// Represents a disposable resource. +public protocol Disposable { + /// Dispose resource. + func dispose() +} diff --git a/Pods/RxSwift/RxSwift/Disposables/AnonymousDisposable.swift b/Pods/RxSwift/RxSwift/Disposables/AnonymousDisposable.swift new file mode 100644 index 0000000..591aafa --- /dev/null +++ b/Pods/RxSwift/RxSwift/Disposables/AnonymousDisposable.swift @@ -0,0 +1,59 @@ +// +// AnonymousDisposable.swift +// RxSwift +// +// Created by Krunoslav Zaher on 2/15/15. +// Copyright © 2015 Krunoslav Zaher. All rights reserved. +// + +/// Represents an Action-based disposable. +/// +/// When dispose method is called, disposal action will be dereferenced. +private final class AnonymousDisposable : DisposeBase, Cancelable { + public typealias DisposeAction = () -> Void + + private let disposed = AtomicInt(0) + private var disposeAction: DisposeAction? + + /// - returns: Was resource disposed. + public var isDisposed: Bool { + isFlagSet(self.disposed, 1) + } + + /// Constructs a new disposable with the given action used for disposal. + /// + /// - parameter disposeAction: Disposal action which will be run upon calling `dispose`. + private init(_ disposeAction: @escaping DisposeAction) { + self.disposeAction = disposeAction + super.init() + } + + // Non-deprecated version of the constructor, used by `Disposables.create(with:)` + fileprivate init(disposeAction: @escaping DisposeAction) { + self.disposeAction = disposeAction + super.init() + } + + /// Calls the disposal action if and only if the current instance hasn't been disposed yet. + /// + /// After invoking disposal action, disposal action will be dereferenced. + fileprivate func dispose() { + if fetchOr(self.disposed, 1) == 0 { + if let action = self.disposeAction { + self.disposeAction = nil + action() + } + } + } +} + +extension Disposables { + + /// Constructs a new disposable with the given action used for disposal. + /// + /// - parameter dispose: Disposal action which will be run upon calling `dispose`. + public static func create(with dispose: @escaping () -> Void) -> Cancelable { + AnonymousDisposable(disposeAction: dispose) + } + +} diff --git a/Pods/RxSwift/RxSwift/Disposables/BinaryDisposable.swift b/Pods/RxSwift/RxSwift/Disposables/BinaryDisposable.swift new file mode 100644 index 0000000..a3d4937 --- /dev/null +++ b/Pods/RxSwift/RxSwift/Disposables/BinaryDisposable.swift @@ -0,0 +1,53 @@ +// +// BinaryDisposable.swift +// RxSwift +// +// Created by Krunoslav Zaher on 6/12/15. +// Copyright © 2015 Krunoslav Zaher. All rights reserved. +// + +/// Represents two disposable resources that are disposed together. +private final class BinaryDisposable : DisposeBase, Cancelable { + + private let disposed = AtomicInt(0) + + // state + private var disposable1: Disposable? + private var disposable2: Disposable? + + /// - returns: Was resource disposed. + var isDisposed: Bool { + isFlagSet(self.disposed, 1) + } + + /// Constructs new binary disposable from two disposables. + /// + /// - parameter disposable1: First disposable + /// - parameter disposable2: Second disposable + init(_ disposable1: Disposable, _ disposable2: Disposable) { + self.disposable1 = disposable1 + self.disposable2 = disposable2 + super.init() + } + + /// Calls the disposal action if and only if the current instance hasn't been disposed yet. + /// + /// After invoking disposal action, disposal action will be dereferenced. + func dispose() { + if fetchOr(self.disposed, 1) == 0 { + self.disposable1?.dispose() + self.disposable2?.dispose() + self.disposable1 = nil + self.disposable2 = nil + } + } +} + +extension Disposables { + + /// Creates a disposable with the given disposables. + public static func create(_ disposable1: Disposable, _ disposable2: Disposable) -> Cancelable { + BinaryDisposable(disposable1, disposable2) + } + +} diff --git a/Pods/RxSwift/RxSwift/Disposables/BooleanDisposable.swift b/Pods/RxSwift/RxSwift/Disposables/BooleanDisposable.swift new file mode 100644 index 0000000..c7d73e9 --- /dev/null +++ b/Pods/RxSwift/RxSwift/Disposables/BooleanDisposable.swift @@ -0,0 +1,33 @@ +// +// BooleanDisposable.swift +// RxSwift +// +// Created by Junior B. on 10/29/15. +// Copyright © 2015 Krunoslav Zaher. All rights reserved. +// + +/// Represents a disposable resource that can be checked for disposal status. +public final class BooleanDisposable : Cancelable { + + internal static let BooleanDisposableTrue = BooleanDisposable(isDisposed: true) + private var disposed = false + + /// Initializes a new instance of the `BooleanDisposable` class + public init() { + } + + /// Initializes a new instance of the `BooleanDisposable` class with given value + public init(isDisposed: Bool) { + self.disposed = isDisposed + } + + /// - returns: Was resource disposed. + public var isDisposed: Bool { + self.disposed + } + + /// Sets the status to disposed, which can be observer through the `isDisposed` property. + public func dispose() { + self.disposed = true + } +} diff --git a/Pods/RxSwift/RxSwift/Disposables/CompositeDisposable.swift b/Pods/RxSwift/RxSwift/Disposables/CompositeDisposable.swift new file mode 100644 index 0000000..bb4efe6 --- /dev/null +++ b/Pods/RxSwift/RxSwift/Disposables/CompositeDisposable.swift @@ -0,0 +1,147 @@ +// +// CompositeDisposable.swift +// RxSwift +// +// Created by Krunoslav Zaher on 2/20/15. +// Copyright © 2015 Krunoslav Zaher. All rights reserved. +// + +/// Represents a group of disposable resources that are disposed together. +public final class CompositeDisposable : DisposeBase, Cancelable { + /// Key used to remove disposable from composite disposable + public struct DisposeKey { + fileprivate let key: BagKey + fileprivate init(key: BagKey) { + self.key = key + } + } + + private var lock = SpinLock() + + // state + private var disposables: Bag? = Bag() + + public var isDisposed: Bool { + self.lock.performLocked { self.disposables == nil } + } + + public override init() { + } + + /// Initializes a new instance of composite disposable with the specified number of disposables. + public init(_ disposable1: Disposable, _ disposable2: Disposable) { + // This overload is here to make sure we are using optimized version up to 4 arguments. + _ = self.disposables!.insert(disposable1) + _ = self.disposables!.insert(disposable2) + } + + /// Initializes a new instance of composite disposable with the specified number of disposables. + public init(_ disposable1: Disposable, _ disposable2: Disposable, _ disposable3: Disposable) { + // This overload is here to make sure we are using optimized version up to 4 arguments. + _ = self.disposables!.insert(disposable1) + _ = self.disposables!.insert(disposable2) + _ = self.disposables!.insert(disposable3) + } + + /// Initializes a new instance of composite disposable with the specified number of disposables. + public init(_ disposable1: Disposable, _ disposable2: Disposable, _ disposable3: Disposable, _ disposable4: Disposable, _ disposables: Disposable...) { + // This overload is here to make sure we are using optimized version up to 4 arguments. + _ = self.disposables!.insert(disposable1) + _ = self.disposables!.insert(disposable2) + _ = self.disposables!.insert(disposable3) + _ = self.disposables!.insert(disposable4) + + for disposable in disposables { + _ = self.disposables!.insert(disposable) + } + } + + /// Initializes a new instance of composite disposable with the specified number of disposables. + public init(disposables: [Disposable]) { + for disposable in disposables { + _ = self.disposables!.insert(disposable) + } + } + + /** + Adds a disposable to the CompositeDisposable or disposes the disposable if the CompositeDisposable is disposed. + + - parameter disposable: Disposable to add. + - returns: Key that can be used to remove disposable from composite disposable. In case dispose bag was already + disposed `nil` will be returned. + */ + public func insert(_ disposable: Disposable) -> DisposeKey? { + let key = self._insert(disposable) + + if key == nil { + disposable.dispose() + } + + return key + } + + private func _insert(_ disposable: Disposable) -> DisposeKey? { + self.lock.performLocked { + let bagKey = self.disposables?.insert(disposable) + return bagKey.map(DisposeKey.init) + } + } + + /// - returns: Gets the number of disposables contained in the `CompositeDisposable`. + public var count: Int { + self.lock.performLocked { self.disposables?.count ?? 0 } + } + + /// Removes and disposes the disposable identified by `disposeKey` from the CompositeDisposable. + /// + /// - parameter disposeKey: Key used to identify disposable to be removed. + public func remove(for disposeKey: DisposeKey) { + self._remove(for: disposeKey)?.dispose() + } + + private func _remove(for disposeKey: DisposeKey) -> Disposable? { + self.lock.performLocked { self.disposables?.removeKey(disposeKey.key) } + } + + /// Disposes all disposables in the group and removes them from the group. + public func dispose() { + if let disposables = self._dispose() { + disposeAll(in: disposables) + } + } + + private func _dispose() -> Bag? { + self.lock.performLocked { + let current = self.disposables + self.disposables = nil + return current + } + } +} + +extension Disposables { + + /// Creates a disposable with the given disposables. + public static func create(_ disposable1: Disposable, _ disposable2: Disposable, _ disposable3: Disposable) -> Cancelable { + CompositeDisposable(disposable1, disposable2, disposable3) + } + + /// Creates a disposable with the given disposables. + public static func create(_ disposable1: Disposable, _ disposable2: Disposable, _ disposable3: Disposable, _ disposables: Disposable ...) -> Cancelable { + var disposables = disposables + disposables.append(disposable1) + disposables.append(disposable2) + disposables.append(disposable3) + return CompositeDisposable(disposables: disposables) + } + + /// Creates a disposable with the given disposables. + public static func create(_ disposables: [Disposable]) -> Cancelable { + switch disposables.count { + case 2: + return Disposables.create(disposables[0], disposables[1]) + default: + return CompositeDisposable(disposables: disposables) + } + } +} diff --git a/Pods/RxSwift/RxSwift/Disposables/Disposables.swift b/Pods/RxSwift/RxSwift/Disposables/Disposables.swift new file mode 100644 index 0000000..8cd6e28 --- /dev/null +++ b/Pods/RxSwift/RxSwift/Disposables/Disposables.swift @@ -0,0 +1,13 @@ +// +// Disposables.swift +// RxSwift +// +// Created by Mohsen Ramezanpoor on 01/08/2016. +// Copyright © 2016 Krunoslav Zaher. All rights reserved. +// + +/// A collection of utility methods for common disposable operations. +public struct Disposables { + private init() {} +} + diff --git a/Pods/RxSwift/RxSwift/Disposables/DisposeBag.swift b/Pods/RxSwift/RxSwift/Disposables/DisposeBag.swift new file mode 100644 index 0000000..1a673bc --- /dev/null +++ b/Pods/RxSwift/RxSwift/Disposables/DisposeBag.swift @@ -0,0 +1,144 @@ +// +// DisposeBag.swift +// RxSwift +// +// Created by Krunoslav Zaher on 3/25/15. +// Copyright © 2015 Krunoslav Zaher. All rights reserved. +// + +extension Disposable { + /// Adds `self` to `bag` + /// + /// - parameter bag: `DisposeBag` to add `self` to. + public func disposed(by bag: DisposeBag) { + bag.insert(self) + } +} + +/** +Thread safe bag that disposes added disposables on `deinit`. + +This returns ARC (RAII) like resource management to `RxSwift`. + +In case contained disposables need to be disposed, just put a different dispose bag +or create a new one in its place. + + self.existingDisposeBag = DisposeBag() + +In case explicit disposal is necessary, there is also `CompositeDisposable`. +*/ +public final class DisposeBag: DisposeBase { + + private var lock = SpinLock() + + // state + private var disposables = [Disposable]() + private var isDisposed = false + + /// Constructs new empty dispose bag. + public override init() { + super.init() + } + + /// Adds `disposable` to be disposed when dispose bag is being deinited. + /// + /// - parameter disposable: Disposable to add. + public func insert(_ disposable: Disposable) { + self._insert(disposable)?.dispose() + } + + private func _insert(_ disposable: Disposable) -> Disposable? { + self.lock.performLocked { + if self.isDisposed { + return disposable + } + + self.disposables.append(disposable) + + return nil + } + } + + /// This is internal on purpose, take a look at `CompositeDisposable` instead. + private func dispose() { + let oldDisposables = self._dispose() + + for disposable in oldDisposables { + disposable.dispose() + } + } + + private func _dispose() -> [Disposable] { + self.lock.performLocked { + let disposables = self.disposables + + self.disposables.removeAll(keepingCapacity: false) + self.isDisposed = true + + return disposables + } + } + + deinit { + self.dispose() + } +} + +extension DisposeBag { + /// Convenience init allows a list of disposables to be gathered for disposal. + public convenience init(disposing disposables: Disposable...) { + self.init() + self.disposables += disposables + } + + /// Convenience init which utilizes a function builder to let you pass in a list of + /// disposables to make a DisposeBag of. + public convenience init(@DisposableBuilder builder: () -> [Disposable]) { + self.init(disposing: builder()) + } + + /// Convenience init allows an array of disposables to be gathered for disposal. + public convenience init(disposing disposables: [Disposable]) { + self.init() + self.disposables += disposables + } + + /// Convenience function allows a list of disposables to be gathered for disposal. + public func insert(_ disposables: Disposable...) { + self.insert(disposables) + } + + /// Convenience function allows a list of disposables to be gathered for disposal. + public func insert(@DisposableBuilder builder: () -> [Disposable]) { + self.insert(builder()) + } + + /// Convenience function allows an array of disposables to be gathered for disposal. + public func insert(_ disposables: [Disposable]) { + self.lock.performLocked { + if self.isDisposed { + disposables.forEach { $0.dispose() } + } else { + self.disposables += disposables + } + } + } + + /// A function builder accepting a list of Disposables and returning them as an array. + #if swift(>=5.4) + @resultBuilder + public struct DisposableBuilder { + public static func buildBlock(_ disposables: Disposable...) -> [Disposable] { + return disposables + } + } + #else + @_functionBuilder + public struct DisposableBuilder { + public static func buildBlock(_ disposables: Disposable...) -> [Disposable] { + return disposables + } + } + #endif + +} diff --git a/Pods/RxSwift/RxSwift/Disposables/DisposeBase.swift b/Pods/RxSwift/RxSwift/Disposables/DisposeBase.swift new file mode 100644 index 0000000..0d4b2fb --- /dev/null +++ b/Pods/RxSwift/RxSwift/Disposables/DisposeBase.swift @@ -0,0 +1,22 @@ +// +// DisposeBase.swift +// RxSwift +// +// Created by Krunoslav Zaher on 4/4/15. +// Copyright © 2015 Krunoslav Zaher. All rights reserved. +// + +/// Base class for all disposables. +public class DisposeBase { + init() { +#if TRACE_RESOURCES + _ = Resources.incrementTotal() +#endif + } + + deinit { +#if TRACE_RESOURCES + _ = Resources.decrementTotal() +#endif + } +} diff --git a/Pods/RxSwift/RxSwift/Disposables/NopDisposable.swift b/Pods/RxSwift/RxSwift/Disposables/NopDisposable.swift new file mode 100644 index 0000000..dd436ba --- /dev/null +++ b/Pods/RxSwift/RxSwift/Disposables/NopDisposable.swift @@ -0,0 +1,30 @@ +// +// NopDisposable.swift +// RxSwift +// +// Created by Krunoslav Zaher on 2/15/15. +// Copyright © 2015 Krunoslav Zaher. All rights reserved. +// + +/// Represents a disposable that does nothing on disposal. +/// +/// Nop = No Operation +private struct NopDisposable : Disposable { + + fileprivate static let noOp: Disposable = NopDisposable() + + private init() { + + } + + /// Does nothing. + public func dispose() { + } +} + +extension Disposables { + /** + Creates a disposable that does nothing on disposal. + */ + static public func create() -> Disposable { NopDisposable.noOp } +} diff --git a/Pods/RxSwift/RxSwift/Disposables/RefCountDisposable.swift b/Pods/RxSwift/RxSwift/Disposables/RefCountDisposable.swift new file mode 100644 index 0000000..a59f778 --- /dev/null +++ b/Pods/RxSwift/RxSwift/Disposables/RefCountDisposable.swift @@ -0,0 +1,112 @@ +// +// RefCountDisposable.swift +// RxSwift +// +// Created by Junior B. on 10/29/15. +// Copyright © 2015 Krunoslav Zaher. All rights reserved. +// + +/// Represents a disposable resource that only disposes its underlying disposable resource when all dependent disposable objects have been disposed. +public final class RefCountDisposable : DisposeBase, Cancelable { + private var lock = SpinLock() + private var disposable = nil as Disposable? + private var primaryDisposed = false + private var count = 0 + + /// - returns: Was resource disposed. + public var isDisposed: Bool { + self.lock.performLocked { self.disposable == nil } + } + + /// Initializes a new instance of the `RefCountDisposable`. + public init(disposable: Disposable) { + self.disposable = disposable + super.init() + } + + /** + Holds a dependent disposable that when disposed decreases the refcount on the underlying disposable. + + When getter is called, a dependent disposable contributing to the reference count that manages the underlying disposable's lifetime is returned. + */ + public func retain() -> Disposable { + self.lock.performLocked { + if self.disposable != nil { + do { + _ = try incrementChecked(&self.count) + } catch { + rxFatalError("RefCountDisposable increment failed") + } + + return RefCountInnerDisposable(self) + } else { + return Disposables.create() + } + } + } + + /// Disposes the underlying disposable only when all dependent disposables have been disposed. + public func dispose() { + let oldDisposable: Disposable? = self.lock.performLocked { + if let oldDisposable = self.disposable, !self.primaryDisposed { + self.primaryDisposed = true + + if self.count == 0 { + self.disposable = nil + return oldDisposable + } + } + + return nil + } + + if let disposable = oldDisposable { + disposable.dispose() + } + } + + fileprivate func release() { + let oldDisposable: Disposable? = self.lock.performLocked { + if let oldDisposable = self.disposable { + do { + _ = try decrementChecked(&self.count) + } catch { + rxFatalError("RefCountDisposable decrement on release failed") + } + + guard self.count >= 0 else { + rxFatalError("RefCountDisposable counter is lower than 0") + } + + if self.primaryDisposed && self.count == 0 { + self.disposable = nil + return oldDisposable + } + } + + return nil + } + + if let disposable = oldDisposable { + disposable.dispose() + } + } +} + +internal final class RefCountInnerDisposable: DisposeBase, Disposable +{ + private let parent: RefCountDisposable + private let isDisposed = AtomicInt(0) + + init(_ parent: RefCountDisposable) { + self.parent = parent + super.init() + } + + internal func dispose() + { + if fetchOr(self.isDisposed, 1) == 0 { + self.parent.release() + } + } +} diff --git a/Pods/RxSwift/RxSwift/Disposables/ScheduledDisposable.swift b/Pods/RxSwift/RxSwift/Disposables/ScheduledDisposable.swift new file mode 100644 index 0000000..2cf997b --- /dev/null +++ b/Pods/RxSwift/RxSwift/Disposables/ScheduledDisposable.swift @@ -0,0 +1,50 @@ +// +// ScheduledDisposable.swift +// RxSwift +// +// Created by Krunoslav Zaher on 6/13/15. +// Copyright © 2015 Krunoslav Zaher. All rights reserved. +// + +private let disposeScheduledDisposable: (ScheduledDisposable) -> Disposable = { sd in + sd.disposeInner() + return Disposables.create() +} + +/// Represents a disposable resource whose disposal invocation will be scheduled on the specified scheduler. +public final class ScheduledDisposable : Cancelable { + public let scheduler: ImmediateSchedulerType + + private let disposed = AtomicInt(0) + + // state + private var disposable: Disposable? + + /// - returns: Was resource disposed. + public var isDisposed: Bool { + isFlagSet(self.disposed, 1) + } + + /** + Initializes a new instance of the `ScheduledDisposable` that uses a `scheduler` on which to dispose the `disposable`. + + - parameter scheduler: Scheduler where the disposable resource will be disposed on. + - parameter disposable: Disposable resource to dispose on the given scheduler. + */ + public init(scheduler: ImmediateSchedulerType, disposable: Disposable) { + self.scheduler = scheduler + self.disposable = disposable + } + + /// Disposes the wrapped disposable on the provided scheduler. + public func dispose() { + _ = self.scheduler.schedule(self, action: disposeScheduledDisposable) + } + + func disposeInner() { + if fetchOr(self.disposed, 1) == 0 { + self.disposable!.dispose() + self.disposable = nil + } + } +} diff --git a/Pods/RxSwift/RxSwift/Disposables/SerialDisposable.swift b/Pods/RxSwift/RxSwift/Disposables/SerialDisposable.swift new file mode 100644 index 0000000..ef4690d --- /dev/null +++ b/Pods/RxSwift/RxSwift/Disposables/SerialDisposable.swift @@ -0,0 +1,73 @@ +// +// SerialDisposable.swift +// RxSwift +// +// Created by Krunoslav Zaher on 3/12/15. +// Copyright © 2015 Krunoslav Zaher. All rights reserved. +// + +/// Represents a disposable resource whose underlying disposable resource can be replaced by another disposable resource, causing automatic disposal of the previous underlying disposable resource. +public final class SerialDisposable : DisposeBase, Cancelable { + private var lock = SpinLock() + + // state + private var current = nil as Disposable? + private var disposed = false + + /// - returns: Was resource disposed. + public var isDisposed: Bool { + self.disposed + } + + /// Initializes a new instance of the `SerialDisposable`. + override public init() { + super.init() + } + + /** + Gets or sets the underlying disposable. + + Assigning this property disposes the previous disposable object. + + If the `SerialDisposable` has already been disposed, assignment to this property causes immediate disposal of the given disposable object. + */ + public var disposable: Disposable { + get { + self.lock.performLocked { + self.current ?? Disposables.create() + } + } + set (newDisposable) { + let disposable: Disposable? = self.lock.performLocked { + if self.isDisposed { + return newDisposable + } + else { + let toDispose = self.current + self.current = newDisposable + return toDispose + } + } + + if let disposable = disposable { + disposable.dispose() + } + } + } + + /// Disposes the underlying disposable as well as all future replacements. + public func dispose() { + self._dispose()?.dispose() + } + + private func _dispose() -> Disposable? { + self.lock.performLocked { + guard !self.isDisposed else { return nil } + + self.disposed = true + let current = self.current + self.current = nil + return current + } + } +} diff --git a/Pods/RxSwift/RxSwift/Disposables/SingleAssignmentDisposable.swift b/Pods/RxSwift/RxSwift/Disposables/SingleAssignmentDisposable.swift new file mode 100644 index 0000000..4a5fb86 --- /dev/null +++ b/Pods/RxSwift/RxSwift/Disposables/SingleAssignmentDisposable.swift @@ -0,0 +1,72 @@ +// +// SingleAssignmentDisposable.swift +// RxSwift +// +// Created by Krunoslav Zaher on 2/15/15. +// Copyright © 2015 Krunoslav Zaher. All rights reserved. +// + +/** +Represents a disposable resource which only allows a single assignment of its underlying disposable resource. + +If an underlying disposable resource has already been set, future attempts to set the underlying disposable resource will throw an exception. +*/ +public final class SingleAssignmentDisposable : DisposeBase, Cancelable { + + private struct DisposeState: OptionSet { + let rawValue: Int32 + + static let disposed = DisposeState(rawValue: 1 << 0) + static let disposableSet = DisposeState(rawValue: 1 << 1) + } + + // state + private let state = AtomicInt(0) + private var disposable = nil as Disposable? + + /// - returns: A value that indicates whether the object is disposed. + public var isDisposed: Bool { + isFlagSet(self.state, DisposeState.disposed.rawValue) + } + + /// Initializes a new instance of the `SingleAssignmentDisposable`. + public override init() { + super.init() + } + + /// Gets or sets the underlying disposable. After disposal, the result of getting this property is undefined. + /// + /// **Throws exception if the `SingleAssignmentDisposable` has already been assigned to.** + public func setDisposable(_ disposable: Disposable) { + self.disposable = disposable + + let previousState = fetchOr(self.state, DisposeState.disposableSet.rawValue) + + if (previousState & DisposeState.disposableSet.rawValue) != 0 { + rxFatalError("oldState.disposable != nil") + } + + if (previousState & DisposeState.disposed.rawValue) != 0 { + disposable.dispose() + self.disposable = nil + } + } + + /// Disposes the underlying disposable. + public func dispose() { + let previousState = fetchOr(self.state, DisposeState.disposed.rawValue) + + if (previousState & DisposeState.disposed.rawValue) != 0 { + return + } + + if (previousState & DisposeState.disposableSet.rawValue) != 0 { + guard let disposable = self.disposable else { + rxFatalError("Disposable not set") + } + disposable.dispose() + self.disposable = nil + } + } + +} diff --git a/Pods/RxSwift/RxSwift/Disposables/SubscriptionDisposable.swift b/Pods/RxSwift/RxSwift/Disposables/SubscriptionDisposable.swift new file mode 100644 index 0000000..a406c84 --- /dev/null +++ b/Pods/RxSwift/RxSwift/Disposables/SubscriptionDisposable.swift @@ -0,0 +1,21 @@ +// +// SubscriptionDisposable.swift +// RxSwift +// +// Created by Krunoslav Zaher on 10/25/15. +// Copyright © 2015 Krunoslav Zaher. All rights reserved. +// + +struct SubscriptionDisposable : Disposable { + private let key: T.DisposeKey + private weak var owner: T? + + init(owner: T, key: T.DisposeKey) { + self.owner = owner + self.key = key + } + + func dispose() { + self.owner?.synchronizedUnsubscribe(self.key) + } +} diff --git a/Pods/RxSwift/RxSwift/Errors.swift b/Pods/RxSwift/RxSwift/Errors.swift new file mode 100644 index 0000000..d2d2917 --- /dev/null +++ b/Pods/RxSwift/RxSwift/Errors.swift @@ -0,0 +1,52 @@ +// +// Errors.swift +// RxSwift +// +// Created by Krunoslav Zaher on 3/28/15. +// Copyright © 2015 Krunoslav Zaher. All rights reserved. +// + +let RxErrorDomain = "RxErrorDomain" +let RxCompositeFailures = "RxCompositeFailures" + +/// Generic Rx error codes. +public enum RxError + : Swift.Error + , CustomDebugStringConvertible { + /// Unknown error occurred. + case unknown + /// Performing an action on disposed object. + case disposed(object: AnyObject) + /// Arithmetic overflow error. + case overflow + /// Argument out of range error. + case argumentOutOfRange + /// Sequence doesn't contain any elements. + case noElements + /// Sequence contains more than one element. + case moreThanOneElement + /// Timeout error. + case timeout +} + +extension RxError { + /// A textual representation of `self`, suitable for debugging. + public var debugDescription: String { + switch self { + case .unknown: + return "Unknown error occurred." + case .disposed(let object): + return "Object `\(object)` was already disposed." + case .overflow: + return "Arithmetic overflow occurred." + case .argumentOutOfRange: + return "Argument out of range." + case .noElements: + return "Sequence doesn't contain any elements." + case .moreThanOneElement: + return "Sequence contains more than one element." + case .timeout: + return "Sequence timeout." + } + } +} diff --git a/Pods/RxSwift/RxSwift/Event.swift b/Pods/RxSwift/RxSwift/Event.swift new file mode 100644 index 0000000..01861a8 --- /dev/null +++ b/Pods/RxSwift/RxSwift/Event.swift @@ -0,0 +1,104 @@ +// +// Event.swift +// RxSwift +// +// Created by Krunoslav Zaher on 2/8/15. +// Copyright © 2015 Krunoslav Zaher. All rights reserved. +// + +/// Represents a sequence event. +/// +/// Sequence grammar: +/// **next\* (error | completed)** +@frozen public enum Event { + /// Next element is produced. + case next(Element) + + /// Sequence terminated with an error. + case error(Swift.Error) + + /// Sequence completed successfully. + case completed +} + +extension Event: CustomDebugStringConvertible { + /// Description of event. + public var debugDescription: String { + switch self { + case .next(let value): + return "next(\(value))" + case .error(let error): + return "error(\(error))" + case .completed: + return "completed" + } + } +} + +extension Event { + /// Is `completed` or `error` event. + public var isStopEvent: Bool { + switch self { + case .next: return false + case .error, .completed: return true + } + } + + /// If `next` event, returns element value. + public var element: Element? { + if case .next(let value) = self { + return value + } + return nil + } + + /// If `error` event, returns error. + public var error: Swift.Error? { + if case .error(let error) = self { + return error + } + return nil + } + + /// If `completed` event, returns `true`. + public var isCompleted: Bool { + if case .completed = self { + return true + } + return false + } +} + +extension Event { + /// Maps sequence elements using transform. If error happens during the transform, `.error` + /// will be returned as value. + public func map(_ transform: (Element) throws -> Result) -> Event { + do { + switch self { + case let .next(element): + return .next(try transform(element)) + case let .error(error): + return .error(error) + case .completed: + return .completed + } + } + catch let e { + return .error(e) + } + } +} + +/// A type that can be converted to `Event`. +public protocol EventConvertible { + /// Type of element in event + associatedtype Element + + /// Event representation of this instance + var event: Event { get } +} + +extension Event: EventConvertible { + /// Event representation of this instance + public var event: Event { self } +} diff --git a/Pods/RxSwift/RxSwift/Extensions/Bag+Rx.swift b/Pods/RxSwift/RxSwift/Extensions/Bag+Rx.swift new file mode 100644 index 0000000..9794683 --- /dev/null +++ b/Pods/RxSwift/RxSwift/Extensions/Bag+Rx.swift @@ -0,0 +1,50 @@ +// +// Bag+Rx.swift +// RxSwift +// +// Created by Krunoslav Zaher on 10/19/16. +// Copyright © 2016 Krunoslav Zaher. All rights reserved. +// + + +// MARK: forEach + +@inline(__always) +func dispatch(_ bag: Bag<(Event) -> Void>, _ event: Event) { + bag._value0?(event) + + if bag._onlyFastPath { + return + } + + let pairs = bag._pairs + for i in 0 ..< pairs.count { + pairs[i].value(event) + } + + if let dictionary = bag._dictionary { + for element in dictionary.values { + element(event) + } + } +} + +/// Dispatches `dispose` to all disposables contained inside bag. +func disposeAll(in bag: Bag) { + bag._value0?.dispose() + + if bag._onlyFastPath { + return + } + + let pairs = bag._pairs + for i in 0 ..< pairs.count { + pairs[i].value.dispose() + } + + if let dictionary = bag._dictionary { + for element in dictionary.values { + element.dispose() + } + } +} diff --git a/Pods/RxSwift/RxSwift/GroupedObservable.swift b/Pods/RxSwift/RxSwift/GroupedObservable.swift new file mode 100644 index 0000000..189a8c4 --- /dev/null +++ b/Pods/RxSwift/RxSwift/GroupedObservable.swift @@ -0,0 +1,35 @@ +// +// GroupedObservable.swift +// RxSwift +// +// Created by Tomi Koskinen on 01/12/15. +// Copyright © 2015 Krunoslav Zaher. All rights reserved. +// + +/// Represents an observable sequence of elements that have a common key. +public struct GroupedObservable : ObservableType { + /// Gets the common key. + public let key: Key + + private let source: Observable + + /// Initializes grouped observable sequence with key and source observable sequence. + /// + /// - parameter key: Grouped observable sequence key + /// - parameter source: Observable sequence that represents sequence of elements for the key + /// - returns: Grouped observable sequence of elements for the specific key + public init(key: Key, source: Observable) { + self.key = key + self.source = source + } + + /// Subscribes `observer` to receive events for this sequence. + public func subscribe(_ observer: Observer) -> Disposable where Observer.Element == Element { + self.source.subscribe(observer) + } + + /// Converts `self` to `Observable` sequence. + public func asObservable() -> Observable { + self.source + } +} diff --git a/Pods/RxSwift/RxSwift/ImmediateSchedulerType.swift b/Pods/RxSwift/RxSwift/ImmediateSchedulerType.swift new file mode 100644 index 0000000..954fbf0 --- /dev/null +++ b/Pods/RxSwift/RxSwift/ImmediateSchedulerType.swift @@ -0,0 +1,36 @@ +// +// ImmediateSchedulerType.swift +// RxSwift +// +// Created by Krunoslav Zaher on 5/31/15. +// Copyright © 2015 Krunoslav Zaher. All rights reserved. +// + +/// Represents an object that immediately schedules units of work. +public protocol ImmediateSchedulerType { + /** + Schedules an action to be executed immediately. + + - parameter state: State passed to the action to be executed. + - parameter action: Action to be executed. + - returns: The disposable object used to cancel the scheduled action (best effort). + */ + func schedule(_ state: StateType, action: @escaping (StateType) -> Disposable) -> Disposable +} + +extension ImmediateSchedulerType { + /** + Schedules an action to be executed recursively. + + - parameter state: State passed to the action to be executed. + - parameter action: Action to execute recursively. The last parameter passed to the action is used to trigger recursive scheduling of the action, passing in recursive invocation state. + - returns: The disposable object used to cancel the scheduled action (best effort). + */ + public func scheduleRecursive(_ state: State, action: @escaping (_ state: State, _ recurse: (State) -> Void) -> Void) -> Disposable { + let recursiveScheduler = RecursiveImmediateScheduler(action: action, scheduler: self) + + recursiveScheduler.schedule(state) + + return Disposables.create(with: recursiveScheduler.dispose) + } +} diff --git a/Pods/RxSwift/RxSwift/Observable+Concurrency.swift b/Pods/RxSwift/RxSwift/Observable+Concurrency.swift new file mode 100644 index 0000000..c1df7ee --- /dev/null +++ b/Pods/RxSwift/RxSwift/Observable+Concurrency.swift @@ -0,0 +1,68 @@ +// +// Observable+Concurrency.swift +// RxSwift +// +// Created by Shai Mishali on 22/09/2021. +// Copyright © 2021 Krunoslav Zaher. All rights reserved. +// + +#if swift(>=5.5.2) && canImport(_Concurrency) +import Foundation + +@available(macOS 10.15, iOS 13.0, watchOS 6.0, tvOS 13.0, *) +public extension ObservableConvertibleType { + /// Allows iterating over the values of an Observable + /// asynchronously via Swift's concurrency features (`async/await`) + /// + /// A sample usage would look like so: + /// + /// ```swift + /// do { + /// for try await value in observable.values { + /// // Handle emitted values + /// } + /// } catch { + /// // Handle error + /// } + /// ``` + var values: AsyncThrowingStream { + AsyncThrowingStream { continuation in + let disposable = asObservable().subscribe( + onNext: { value in continuation.yield(value) }, + onError: { error in continuation.finish(throwing: error) }, + onCompleted: { continuation.finish() }, + onDisposed: { continuation.onTermination?(.cancelled) } + ) + + continuation.onTermination = { @Sendable _ in + disposable.dispose() + } + } + } +} + +@available(macOS 10.15, iOS 13.0, watchOS 6.0, tvOS 13.0, *) +public extension AsyncSequence { + /// Convert an `AsyncSequence` to an `Observable` emitting + /// values of the asynchronous sequence's type + /// + /// - returns: An `Observable` of the async sequence's type + func asObservable() -> Observable { + Observable.create { observer in + let task = Task { + do { + for try await value in self { + observer.onNext(value) + } + + observer.onCompleted() + } catch { + observer.onError(error) + } + } + + return Disposables.create { task.cancel() } + } + } +} +#endif diff --git a/Pods/RxSwift/RxSwift/Observable.swift b/Pods/RxSwift/RxSwift/Observable.swift new file mode 100644 index 0000000..93a3ed7 --- /dev/null +++ b/Pods/RxSwift/RxSwift/Observable.swift @@ -0,0 +1,31 @@ +// +// Observable.swift +// RxSwift +// +// Created by Krunoslav Zaher on 2/8/15. +// Copyright © 2015 Krunoslav Zaher. All rights reserved. +// + +/// A type-erased `ObservableType`. +/// +/// It represents a push style sequence. +public class Observable : ObservableType { + init() { +#if TRACE_RESOURCES + _ = Resources.incrementTotal() +#endif + } + + public func subscribe(_ observer: Observer) -> Disposable where Observer.Element == Element { + rxAbstractMethod() + } + + public func asObservable() -> Observable { self } + + deinit { +#if TRACE_RESOURCES + _ = Resources.decrementTotal() +#endif + } +} + diff --git a/Pods/RxSwift/RxSwift/ObservableConvertibleType.swift b/Pods/RxSwift/RxSwift/ObservableConvertibleType.swift new file mode 100644 index 0000000..0f56a81 --- /dev/null +++ b/Pods/RxSwift/RxSwift/ObservableConvertibleType.swift @@ -0,0 +1,18 @@ +// +// ObservableConvertibleType.swift +// RxSwift +// +// Created by Krunoslav Zaher on 9/17/15. +// Copyright © 2015 Krunoslav Zaher. All rights reserved. +// + +/// Type that can be converted to observable sequence (`Observable`). +public protocol ObservableConvertibleType { + /// Type of elements in sequence. + associatedtype Element + + /// Converts `self` to `Observable` sequence. + /// + /// - returns: Observable sequence that represents `self`. + func asObservable() -> Observable +} diff --git a/Pods/RxSwift/RxSwift/ObservableType+Extensions.swift b/Pods/RxSwift/RxSwift/ObservableType+Extensions.swift new file mode 100644 index 0000000..ac850c3 --- /dev/null +++ b/Pods/RxSwift/RxSwift/ObservableType+Extensions.swift @@ -0,0 +1,174 @@ +// +// ObservableType+Extensions.swift +// RxSwift +// +// Created by Krunoslav Zaher on 2/21/15. +// Copyright © 2015 Krunoslav Zaher. All rights reserved. +// + +#if DEBUG + import Foundation +#endif + +extension ObservableType { + /** + Subscribes an event handler to an observable sequence. + + - parameter on: Action to invoke for each event in the observable sequence. + - returns: Subscription object used to unsubscribe from the observable sequence. + */ + public func subscribe(_ on: @escaping (Event) -> Void) -> Disposable { + let observer = AnonymousObserver { e in + on(e) + } + return self.asObservable().subscribe(observer) + } + + /** + Subscribes an element handler, an error handler, a completion handler and disposed handler to an observable sequence. + + Also, take in an object and provide an unretained, safe to use (i.e. not implicitly unwrapped), reference to it along with the events emitted by the sequence. + + - Note: If `object` can't be retained, none of the other closures will be invoked. + + - parameter object: The object to provide an unretained reference on. + - parameter onNext: Action to invoke for each element in the observable sequence. + - parameter onError: Action to invoke upon errored termination of the observable sequence. + - parameter onCompleted: Action to invoke upon graceful termination of the observable sequence. + - parameter onDisposed: Action to invoke upon any type of termination of sequence (if the sequence has + gracefully completed, errored, or if the generation is canceled by disposing subscription). + - returns: Subscription object used to unsubscribe from the observable sequence. + */ + public func subscribe( + with object: Object, + onNext: ((Object, Element) -> Void)? = nil, + onError: ((Object, Swift.Error) -> Void)? = nil, + onCompleted: ((Object) -> Void)? = nil, + onDisposed: ((Object) -> Void)? = nil + ) -> Disposable { + subscribe( + onNext: { [weak object] in + guard let object = object else { return } + onNext?(object, $0) + }, + onError: { [weak object] in + guard let object = object else { return } + onError?(object, $0) + }, + onCompleted: { [weak object] in + guard let object = object else { return } + onCompleted?(object) + }, + onDisposed: { [weak object] in + guard let object = object else { return } + onDisposed?(object) + } + ) + } + + /** + Subscribes an element handler, an error handler, a completion handler and disposed handler to an observable sequence. + + - parameter onNext: Action to invoke for each element in the observable sequence. + - parameter onError: Action to invoke upon errored termination of the observable sequence. + - parameter onCompleted: Action to invoke upon graceful termination of the observable sequence. + - parameter onDisposed: Action to invoke upon any type of termination of sequence (if the sequence has + gracefully completed, errored, or if the generation is canceled by disposing subscription). + - returns: Subscription object used to unsubscribe from the observable sequence. + */ + public func subscribe( + onNext: ((Element) -> Void)? = nil, + onError: ((Swift.Error) -> Void)? = nil, + onCompleted: (() -> Void)? = nil, + onDisposed: (() -> Void)? = nil + ) -> Disposable { + let disposable: Disposable + + if let disposed = onDisposed { + disposable = Disposables.create(with: disposed) + } + else { + disposable = Disposables.create() + } + + #if DEBUG + let synchronizationTracker = SynchronizationTracker() + #endif + + let callStack = Hooks.recordCallStackOnError ? Hooks.customCaptureSubscriptionCallstack() : [] + + let observer = AnonymousObserver { event in + + #if DEBUG + synchronizationTracker.register(synchronizationErrorMessage: .default) + defer { synchronizationTracker.unregister() } + #endif + + switch event { + case .next(let value): + onNext?(value) + case .error(let error): + if let onError = onError { + onError(error) + } + else { + Hooks.defaultErrorHandler(callStack, error) + } + disposable.dispose() + case .completed: + onCompleted?() + disposable.dispose() + } + } + return Disposables.create( + self.asObservable().subscribe(observer), + disposable + ) + } +} + +import Foundation + +extension Hooks { + public typealias DefaultErrorHandler = (_ subscriptionCallStack: [String], _ error: Error) -> Void + public typealias CustomCaptureSubscriptionCallstack = () -> [String] + + private static let lock = RecursiveLock() + private static var _defaultErrorHandler: DefaultErrorHandler = { subscriptionCallStack, error in + #if DEBUG + let serializedCallStack = subscriptionCallStack.joined(separator: "\n") + print("Unhandled error happened: \(error)") + if !serializedCallStack.isEmpty { + print("subscription called from:\n\(serializedCallStack)") + } + #endif + } + private static var _customCaptureSubscriptionCallstack: CustomCaptureSubscriptionCallstack = { + #if DEBUG + return Thread.callStackSymbols + #else + return [] + #endif + } + + /// Error handler called in case onError handler wasn't provided. + public static var defaultErrorHandler: DefaultErrorHandler { + get { + lock.performLocked { _defaultErrorHandler } + } + set { + lock.performLocked { _defaultErrorHandler = newValue } + } + } + + /// Subscription callstack block to fetch custom callstack information. + public static var customCaptureSubscriptionCallstack: CustomCaptureSubscriptionCallstack { + get { + lock.performLocked { _customCaptureSubscriptionCallstack } + } + set { + lock.performLocked { _customCaptureSubscriptionCallstack = newValue } + } + } +} + diff --git a/Pods/RxSwift/RxSwift/ObservableType.swift b/Pods/RxSwift/RxSwift/ObservableType.swift new file mode 100644 index 0000000..279bf7f --- /dev/null +++ b/Pods/RxSwift/RxSwift/ObservableType.swift @@ -0,0 +1,45 @@ +// +// ObservableType.swift +// RxSwift +// +// Created by Krunoslav Zaher on 8/8/15. +// Copyright © 2015 Krunoslav Zaher. All rights reserved. +// + +/// Represents a push style sequence. +public protocol ObservableType: ObservableConvertibleType { + /** + Subscribes `observer` to receive events for this sequence. + + ### Grammar + + **Next\* (Error | Completed)?** + + * sequences can produce zero or more elements so zero or more `Next` events can be sent to `observer` + * once an `Error` or `Completed` event is sent, the sequence terminates and can't produce any other elements + + It is possible that events are sent from different threads, but no two events can be sent concurrently to + `observer`. + + ### Resource Management + + When sequence sends `Complete` or `Error` event all internal resources that compute sequence elements + will be freed. + + To cancel production of sequence elements and free resources immediately, call `dispose` on returned + subscription. + + - returns: Subscription for `observer` that can be used to cancel production of sequence elements and free resources. + */ + func subscribe(_ observer: Observer) -> Disposable where Observer.Element == Element +} + +extension ObservableType { + + /// Default implementation of converting `ObservableType` to `Observable`. + public func asObservable() -> Observable { + // temporary workaround + //return Observable.create(subscribe: self.subscribe) + Observable.create { o in self.subscribe(o) } + } +} diff --git a/Pods/RxSwift/RxSwift/Observables/AddRef.swift b/Pods/RxSwift/RxSwift/Observables/AddRef.swift new file mode 100644 index 0000000..a96dfcb --- /dev/null +++ b/Pods/RxSwift/RxSwift/Observables/AddRef.swift @@ -0,0 +1,44 @@ +// +// AddRef.swift +// RxSwift +// +// Created by Junior B. on 30/10/15. +// Copyright © 2015 Krunoslav Zaher. All rights reserved. +// + +final class AddRefSink : Sink, ObserverType { + typealias Element = Observer.Element + + override init(observer: Observer, cancel: Cancelable) { + super.init(observer: observer, cancel: cancel) + } + + func on(_ event: Event) { + switch event { + case .next: + self.forwardOn(event) + case .completed, .error: + self.forwardOn(event) + self.dispose() + } + } +} + +final class AddRef : Producer { + + private let source: Observable + private let refCount: RefCountDisposable + + init(source: Observable, refCount: RefCountDisposable) { + self.source = source + self.refCount = refCount + } + + override func run(_ observer: Observer, cancel: Cancelable) -> (sink: Disposable, subscription: Disposable) where Observer.Element == Element { + let releaseDisposable = self.refCount.retain() + let sink = AddRefSink(observer: observer, cancel: cancel) + let subscription = Disposables.create(releaseDisposable, self.source.subscribe(sink)) + + return (sink: sink, subscription: subscription) + } +} diff --git a/Pods/RxSwift/RxSwift/Observables/Amb.swift b/Pods/RxSwift/RxSwift/Observables/Amb.swift new file mode 100644 index 0000000..efc17a8 --- /dev/null +++ b/Pods/RxSwift/RxSwift/Observables/Amb.swift @@ -0,0 +1,157 @@ +// +// Amb.swift +// RxSwift +// +// Created by Krunoslav Zaher on 6/14/15. +// Copyright © 2015 Krunoslav Zaher. All rights reserved. +// + +extension ObservableType { + /** + Propagates the observable sequence that reacts first. + + - seealso: [amb operator on reactivex.io](http://reactivex.io/documentation/operators/amb.html) + + - returns: An observable sequence that surfaces any of the given sequences, whichever reacted first. + */ + public static func amb(_ sequence: Sequence) -> Observable + where Sequence.Element == Observable { + sequence.reduce(Observable.never()) { a, o in + a.amb(o.asObservable()) + } + } +} + +extension ObservableType { + + /** + Propagates the observable sequence that reacts first. + + - seealso: [amb operator on reactivex.io](http://reactivex.io/documentation/operators/amb.html) + + - parameter right: Second observable sequence. + - returns: An observable sequence that surfaces either of the given sequences, whichever reacted first. + */ + public func amb + (_ right: O2) + -> Observable where O2.Element == Element { + Amb(left: self.asObservable(), right: right.asObservable()) + } +} + +private enum AmbState { + case neither + case left + case right +} + +final private class AmbObserver: ObserverType { + typealias Element = Observer.Element + typealias Parent = AmbSink + typealias This = AmbObserver + typealias Sink = (This, Event) -> Void + + private let parent: Parent + fileprivate var sink: Sink + fileprivate var cancel: Disposable + + init(parent: Parent, cancel: Disposable, sink: @escaping Sink) { +#if TRACE_RESOURCES + _ = Resources.incrementTotal() +#endif + + self.parent = parent + self.sink = sink + self.cancel = cancel + } + + func on(_ event: Event) { + self.sink(self, event) + if event.isStopEvent { + self.cancel.dispose() + } + } + + deinit { +#if TRACE_RESOURCES + _ = Resources.decrementTotal() +#endif + } +} + +final private class AmbSink: Sink { + typealias Element = Observer.Element + typealias Parent = Amb + typealias AmbObserverType = AmbObserver + + private let parent: Parent + + private let lock = RecursiveLock() + // state + private var choice = AmbState.neither + + init(parent: Parent, observer: Observer, cancel: Cancelable) { + self.parent = parent + super.init(observer: observer, cancel: cancel) + } + + func run() -> Disposable { + let subscription1 = SingleAssignmentDisposable() + let subscription2 = SingleAssignmentDisposable() + let disposeAll = Disposables.create(subscription1, subscription2) + + let forwardEvent = { (o: AmbObserverType, event: Event) -> Void in + self.forwardOn(event) + if event.isStopEvent { + self.dispose() + } + } + + let decide = { (o: AmbObserverType, event: Event, me: AmbState, otherSubscription: Disposable) in + self.lock.performLocked { + if self.choice == .neither { + self.choice = me + o.sink = forwardEvent + o.cancel = disposeAll + otherSubscription.dispose() + } + + if self.choice == me { + self.forwardOn(event) + if event.isStopEvent { + self.dispose() + } + } + } + } + + let sink1 = AmbObserver(parent: self, cancel: subscription1) { o, e in + decide(o, e, .left, subscription2) + } + + let sink2 = AmbObserver(parent: self, cancel: subscription1) { o, e in + decide(o, e, .right, subscription1) + } + + subscription1.setDisposable(self.parent.left.subscribe(sink1)) + subscription2.setDisposable(self.parent.right.subscribe(sink2)) + + return disposeAll + } +} + +final private class Amb: Producer { + fileprivate let left: Observable + fileprivate let right: Observable + + init(left: Observable, right: Observable) { + self.left = left + self.right = right + } + + override func run(_ observer: Observer, cancel: Cancelable) -> (sink: Disposable, subscription: Disposable) where Observer.Element == Element { + let sink = AmbSink(parent: self, observer: observer, cancel: cancel) + let subscription = sink.run() + return (sink: sink, subscription: subscription) + } +} diff --git a/Pods/RxSwift/RxSwift/Observables/AsMaybe.swift b/Pods/RxSwift/RxSwift/Observables/AsMaybe.swift new file mode 100644 index 0000000..6fa6257 --- /dev/null +++ b/Pods/RxSwift/RxSwift/Observables/AsMaybe.swift @@ -0,0 +1,48 @@ +// +// AsMaybe.swift +// RxSwift +// +// Created by Krunoslav Zaher on 3/12/17. +// Copyright © 2017 Krunoslav Zaher. All rights reserved. +// + +private final class AsMaybeSink : Sink, ObserverType { + typealias Element = Observer.Element + + private var element: Event? + + func on(_ event: Event) { + switch event { + case .next: + if self.element != nil { + self.forwardOn(.error(RxError.moreThanOneElement)) + self.dispose() + } + + self.element = event + case .error: + self.forwardOn(event) + self.dispose() + case .completed: + if let element = self.element { + self.forwardOn(element) + } + self.forwardOn(.completed) + self.dispose() + } + } +} + +final class AsMaybe: Producer { + private let source: Observable + + init(source: Observable) { + self.source = source + } + + override func run(_ observer: Observer, cancel: Cancelable) -> (sink: Disposable, subscription: Disposable) where Observer.Element == Element { + let sink = AsMaybeSink(observer: observer, cancel: cancel) + let subscription = self.source.subscribe(sink) + return (sink: sink, subscription: subscription) + } +} diff --git a/Pods/RxSwift/RxSwift/Observables/AsSingle.swift b/Pods/RxSwift/RxSwift/Observables/AsSingle.swift new file mode 100644 index 0000000..b39932f --- /dev/null +++ b/Pods/RxSwift/RxSwift/Observables/AsSingle.swift @@ -0,0 +1,51 @@ +// +// AsSingle.swift +// RxSwift +// +// Created by Krunoslav Zaher on 3/12/17. +// Copyright © 2017 Krunoslav Zaher. All rights reserved. +// + +private final class AsSingleSink : Sink, ObserverType { + typealias Element = Observer.Element + + private var element: Event? + + func on(_ event: Event) { + switch event { + case .next: + if self.element != nil { + self.forwardOn(.error(RxError.moreThanOneElement)) + self.dispose() + } + + self.element = event + case .error: + self.forwardOn(event) + self.dispose() + case .completed: + if let element = self.element { + self.forwardOn(element) + self.forwardOn(.completed) + } + else { + self.forwardOn(.error(RxError.noElements)) + } + self.dispose() + } + } +} + +final class AsSingle: Producer { + private let source: Observable + + init(source: Observable) { + self.source = source + } + + override func run(_ observer: Observer, cancel: Cancelable) -> (sink: Disposable, subscription: Disposable) where Observer.Element == Element { + let sink = AsSingleSink(observer: observer, cancel: cancel) + let subscription = self.source.subscribe(sink) + return (sink: sink, subscription: subscription) + } +} diff --git a/Pods/RxSwift/RxSwift/Observables/Buffer.swift b/Pods/RxSwift/RxSwift/Observables/Buffer.swift new file mode 100644 index 0000000..087c4cf --- /dev/null +++ b/Pods/RxSwift/RxSwift/Observables/Buffer.swift @@ -0,0 +1,138 @@ +// +// Buffer.swift +// RxSwift +// +// Created by Krunoslav Zaher on 9/13/15. +// Copyright © 2015 Krunoslav Zaher. All rights reserved. +// + +extension ObservableType { + + /** + Projects each element of an observable sequence into a buffer that's sent out when either it's full or a given amount of time has elapsed, using the specified scheduler to run timers. + + A useful real-world analogy of this overload is the behavior of a ferry leaving the dock when all seats are taken, or at the scheduled time of departure, whichever event occurs first. + + - seealso: [buffer operator on reactivex.io](http://reactivex.io/documentation/operators/buffer.html) + + - parameter timeSpan: Maximum time length of a buffer. + - parameter count: Maximum element count of a buffer. + - parameter scheduler: Scheduler to run buffering timers on. + - returns: An observable sequence of buffers. + */ + public func buffer(timeSpan: RxTimeInterval, count: Int, scheduler: SchedulerType) + -> Observable<[Element]> { + BufferTimeCount(source: self.asObservable(), timeSpan: timeSpan, count: count, scheduler: scheduler) + } +} + +final private class BufferTimeCount: Producer<[Element]> { + + fileprivate let timeSpan: RxTimeInterval + fileprivate let count: Int + fileprivate let scheduler: SchedulerType + fileprivate let source: Observable + + init(source: Observable, timeSpan: RxTimeInterval, count: Int, scheduler: SchedulerType) { + self.source = source + self.timeSpan = timeSpan + self.count = count + self.scheduler = scheduler + } + + override func run(_ observer: Observer, cancel: Cancelable) -> (sink: Disposable, subscription: Disposable) where Observer.Element == [Element] { + let sink = BufferTimeCountSink(parent: self, observer: observer, cancel: cancel) + let subscription = sink.run() + return (sink: sink, subscription: subscription) + } +} + +final private class BufferTimeCountSink + : Sink + , LockOwnerType + , ObserverType + , SynchronizedOnType where Observer.Element == [Element] { + typealias Parent = BufferTimeCount + + private let parent: Parent + + let lock = RecursiveLock() + + // state + private let timerD = SerialDisposable() + private var buffer = [Element]() + private var windowID = 0 + + init(parent: Parent, observer: Observer, cancel: Cancelable) { + self.parent = parent + super.init(observer: observer, cancel: cancel) + } + + func run() -> Disposable { + self.createTimer(self.windowID) + return Disposables.create(timerD, parent.source.subscribe(self)) + } + + func startNewWindowAndSendCurrentOne() { + self.windowID = self.windowID &+ 1 + let windowID = self.windowID + + let buffer = self.buffer + self.buffer = [] + self.forwardOn(.next(buffer)) + + self.createTimer(windowID) + } + + func on(_ event: Event) { + self.synchronizedOn(event) + } + + func synchronized_on(_ event: Event) { + switch event { + case .next(let element): + self.buffer.append(element) + + if self.buffer.count == self.parent.count { + self.startNewWindowAndSendCurrentOne() + } + + case .error(let error): + self.buffer = [] + self.forwardOn(.error(error)) + self.dispose() + case .completed: + self.forwardOn(.next(self.buffer)) + self.forwardOn(.completed) + self.dispose() + } + } + + func createTimer(_ windowID: Int) { + if self.timerD.isDisposed { + return + } + + if self.windowID != windowID { + return + } + + let nextTimer = SingleAssignmentDisposable() + + self.timerD.disposable = nextTimer + + let disposable = self.parent.scheduler.scheduleRelative(windowID, dueTime: self.parent.timeSpan) { previousWindowID in + self.lock.performLocked { + if previousWindowID != self.windowID { + return + } + + self.startNewWindowAndSendCurrentOne() + } + + return Disposables.create() + } + + nextTimer.setDisposable(disposable) + } +} diff --git a/Pods/RxSwift/RxSwift/Observables/Catch.swift b/Pods/RxSwift/RxSwift/Observables/Catch.swift new file mode 100644 index 0000000..2efd660 --- /dev/null +++ b/Pods/RxSwift/RxSwift/Observables/Catch.swift @@ -0,0 +1,275 @@ +// +// Catch.swift +// RxSwift +// +// Created by Krunoslav Zaher on 4/19/15. +// Copyright © 2015 Krunoslav Zaher. All rights reserved. +// + +extension ObservableType { + + /** + Continues an observable sequence that is terminated by an error with the observable sequence produced by the handler. + + - seealso: [catch operator on reactivex.io](http://reactivex.io/documentation/operators/catch.html) + + - parameter handler: Error handler function, producing another observable sequence. + - returns: An observable sequence containing the source sequence's elements, followed by the elements produced by the handler's resulting observable sequence in case an error occurred. + */ + public func `catch`(_ handler: @escaping (Swift.Error) throws -> Observable) + -> Observable { + Catch(source: self.asObservable(), handler: handler) + } + + /** + Continues an observable sequence that is terminated by an error with the observable sequence produced by the handler. + + - seealso: [catch operator on reactivex.io](http://reactivex.io/documentation/operators/catch.html) + + - parameter handler: Error handler function, producing another observable sequence. + - returns: An observable sequence containing the source sequence's elements, followed by the elements produced by the handler's resulting observable sequence in case an error occurred. + */ + @available(*, deprecated, renamed: "catch(_:)") + public func catchError(_ handler: @escaping (Swift.Error) throws -> Observable) + -> Observable { + `catch`(handler) + } + + /** + Continues an observable sequence that is terminated by an error with a single element. + + - seealso: [catch operator on reactivex.io](http://reactivex.io/documentation/operators/catch.html) + + - parameter element: Last element in an observable sequence in case error occurs. + - returns: An observable sequence containing the source sequence's elements, followed by the `element` in case an error occurred. + */ + public func catchAndReturn(_ element: Element) + -> Observable { + Catch(source: self.asObservable(), handler: { _ in Observable.just(element) }) + } + + /** + Continues an observable sequence that is terminated by an error with a single element. + + - seealso: [catch operator on reactivex.io](http://reactivex.io/documentation/operators/catch.html) + + - parameter element: Last element in an observable sequence in case error occurs. + - returns: An observable sequence containing the source sequence's elements, followed by the `element` in case an error occurred. + */ + @available(*, deprecated, renamed: "catchAndReturn(_:)") + public func catchErrorJustReturn(_ element: Element) + -> Observable { + catchAndReturn(element) + } +} + +extension ObservableType { + /** + Continues an observable sequence that is terminated by an error with the next observable sequence. + + - seealso: [catch operator on reactivex.io](http://reactivex.io/documentation/operators/catch.html) + + - returns: An observable sequence containing elements from consecutive source sequences until a source sequence terminates successfully. + */ + @available(*, deprecated, renamed: "catch(onSuccess:onFailure:onDisposed:)") + public static func catchError(_ sequence: Sequence) -> Observable + where Sequence.Element == Observable { + `catch`(sequence: sequence) + } + + /** + Continues an observable sequence that is terminated by an error with the next observable sequence. + + - seealso: [catch operator on reactivex.io](http://reactivex.io/documentation/operators/catch.html) + + - returns: An observable sequence containing elements from consecutive source sequences until a source sequence terminates successfully. + */ + public static func `catch`(sequence: Sequence) -> Observable + where Sequence.Element == Observable { + CatchSequence(sources: sequence) + } +} + +extension ObservableType { + + /** + Repeats the source observable sequence until it successfully terminates. + + **This could potentially create an infinite sequence.** + + - seealso: [retry operator on reactivex.io](http://reactivex.io/documentation/operators/retry.html) + + - returns: Observable sequence to repeat until it successfully terminates. + */ + public func retry() -> Observable { + CatchSequence(sources: InfiniteSequence(repeatedValue: self.asObservable())) + } + + /** + Repeats the source observable sequence the specified number of times in case of an error or until it successfully terminates. + + If you encounter an error and want it to retry once, then you must use `retry(2)` + + - seealso: [retry operator on reactivex.io](http://reactivex.io/documentation/operators/retry.html) + + - parameter maxAttemptCount: Maximum number of times to repeat the sequence. + - returns: An observable sequence producing the elements of the given sequence repeatedly until it terminates successfully. + */ + public func retry(_ maxAttemptCount: Int) + -> Observable { + CatchSequence(sources: Swift.repeatElement(self.asObservable(), count: maxAttemptCount)) + } +} + +// catch with callback + +final private class CatchSinkProxy: ObserverType { + typealias Element = Observer.Element + typealias Parent = CatchSink + + private let parent: Parent + + init(parent: Parent) { + self.parent = parent + } + + func on(_ event: Event) { + self.parent.forwardOn(event) + + switch event { + case .next: + break + case .error, .completed: + self.parent.dispose() + } + } +} + +final private class CatchSink: Sink, ObserverType { + typealias Element = Observer.Element + typealias Parent = Catch + + private let parent: Parent + private let subscription = SerialDisposable() + + init(parent: Parent, observer: Observer, cancel: Cancelable) { + self.parent = parent + super.init(observer: observer, cancel: cancel) + } + + func run() -> Disposable { + let d1 = SingleAssignmentDisposable() + self.subscription.disposable = d1 + d1.setDisposable(self.parent.source.subscribe(self)) + + return self.subscription + } + + func on(_ event: Event) { + switch event { + case .next: + self.forwardOn(event) + case .completed: + self.forwardOn(event) + self.dispose() + case .error(let error): + do { + let catchSequence = try self.parent.handler(error) + + let observer = CatchSinkProxy(parent: self) + + self.subscription.disposable = catchSequence.subscribe(observer) + } + catch let e { + self.forwardOn(.error(e)) + self.dispose() + } + } + } +} + +final private class Catch: Producer { + typealias Handler = (Swift.Error) throws -> Observable + + fileprivate let source: Observable + fileprivate let handler: Handler + + init(source: Observable, handler: @escaping Handler) { + self.source = source + self.handler = handler + } + + override func run(_ observer: Observer, cancel: Cancelable) -> (sink: Disposable, subscription: Disposable) where Observer.Element == Element { + let sink = CatchSink(parent: self, observer: observer, cancel: cancel) + let subscription = sink.run() + return (sink: sink, subscription: subscription) + } +} + +// catch enumerable + +final private class CatchSequenceSink + : TailRecursiveSink + , ObserverType where Sequence.Element: ObservableConvertibleType, Sequence.Element.Element == Observer.Element { + typealias Element = Observer.Element + typealias Parent = CatchSequence + + private var lastError: Swift.Error? + + override init(observer: Observer, cancel: Cancelable) { + super.init(observer: observer, cancel: cancel) + } + + func on(_ event: Event) { + switch event { + case .next: + self.forwardOn(event) + case .error(let error): + self.lastError = error + self.schedule(.moveNext) + case .completed: + self.forwardOn(event) + self.dispose() + } + } + + override func subscribeToNext(_ source: Observable) -> Disposable { + source.subscribe(self) + } + + override func done() { + if let lastError = self.lastError { + self.forwardOn(.error(lastError)) + } + else { + self.forwardOn(.completed) + } + + self.dispose() + } + + override func extract(_ observable: Observable) -> SequenceGenerator? { + if let onError = observable as? CatchSequence { + return (onError.sources.makeIterator(), nil) + } + else { + return nil + } + } +} + +final private class CatchSequence: Producer where Sequence.Element: ObservableConvertibleType { + typealias Element = Sequence.Element.Element + + let sources: Sequence + + init(sources: Sequence) { + self.sources = sources + } + + override func run(_ observer: Observer, cancel: Cancelable) -> (sink: Disposable, subscription: Disposable) where Observer.Element == Element { + let sink = CatchSequenceSink(observer: observer, cancel: cancel) + let subscription = sink.run((self.sources.makeIterator(), nil)) + return (sink: sink, subscription: subscription) + } +} diff --git a/Pods/RxSwift/RxSwift/Observables/CombineLatest+Collection.swift b/Pods/RxSwift/RxSwift/Observables/CombineLatest+Collection.swift new file mode 100644 index 0000000..4350851 --- /dev/null +++ b/Pods/RxSwift/RxSwift/Observables/CombineLatest+Collection.swift @@ -0,0 +1,165 @@ +// +// CombineLatest+Collection.swift +// RxSwift +// +// Created by Krunoslav Zaher on 8/29/15. +// Copyright © 2015 Krunoslav Zaher. All rights reserved. +// + +extension ObservableType { + /** + Merges the specified observable sequences into one observable sequence by using the selector function whenever any of the observable sequences produces an element. + + - seealso: [combinelatest operator on reactivex.io](http://reactivex.io/documentation/operators/combinelatest.html) + + - parameter resultSelector: Function to invoke whenever any of the sources produces an element. + - returns: An observable sequence containing the result of combining elements of the sources using the specified result selector function. + */ + public static func combineLatest(_ collection: Collection, resultSelector: @escaping ([Collection.Element.Element]) throws -> Element) -> Observable + where Collection.Element: ObservableType { + CombineLatestCollectionType(sources: collection, resultSelector: resultSelector) + } + + /** + Merges the specified observable sequences into one observable sequence whenever any of the observable sequences produces an element. + + - seealso: [combinelatest operator on reactivex.io](http://reactivex.io/documentation/operators/combinelatest.html) + + - returns: An observable sequence containing the result of combining elements of the sources. + */ + public static func combineLatest(_ collection: Collection) -> Observable<[Element]> + where Collection.Element: ObservableType, Collection.Element.Element == Element { + CombineLatestCollectionType(sources: collection, resultSelector: { $0 }) + } +} + +final private class CombineLatestCollectionTypeSink + : Sink where Collection.Element: ObservableConvertibleType { + typealias Result = Observer.Element + typealias Parent = CombineLatestCollectionType + typealias SourceElement = Collection.Element.Element + + let parent: Parent + + let lock = RecursiveLock() + + // state + var numberOfValues = 0 + var values: [SourceElement?] + var isDone: [Bool] + var numberOfDone = 0 + var subscriptions: [SingleAssignmentDisposable] + + init(parent: Parent, observer: Observer, cancel: Cancelable) { + self.parent = parent + self.values = [SourceElement?](repeating: nil, count: parent.count) + self.isDone = [Bool](repeating: false, count: parent.count) + self.subscriptions = [SingleAssignmentDisposable]() + self.subscriptions.reserveCapacity(parent.count) + + for _ in 0 ..< parent.count { + self.subscriptions.append(SingleAssignmentDisposable()) + } + + super.init(observer: observer, cancel: cancel) + } + + func on(_ event: Event, atIndex: Int) { + self.lock.lock(); defer { self.lock.unlock() } + switch event { + case .next(let element): + if self.values[atIndex] == nil { + self.numberOfValues += 1 + } + + self.values[atIndex] = element + + if self.numberOfValues < self.parent.count { + let numberOfOthersThatAreDone = self.numberOfDone - (self.isDone[atIndex] ? 1 : 0) + if numberOfOthersThatAreDone == self.parent.count - 1 { + self.forwardOn(.completed) + self.dispose() + } + return + } + + do { + let result = try self.parent.resultSelector(self.values.map { $0! }) + self.forwardOn(.next(result)) + } + catch let error { + self.forwardOn(.error(error)) + self.dispose() + } + + case .error(let error): + self.forwardOn(.error(error)) + self.dispose() + case .completed: + if self.isDone[atIndex] { + return + } + + self.isDone[atIndex] = true + self.numberOfDone += 1 + + if self.numberOfDone == self.parent.count { + self.forwardOn(.completed) + self.dispose() + } + else { + self.subscriptions[atIndex].dispose() + } + } + } + + func run() -> Disposable { + var j = 0 + for i in self.parent.sources { + let index = j + let source = i.asObservable() + let disposable = source.subscribe(AnyObserver { event in + self.on(event, atIndex: index) + }) + + self.subscriptions[j].setDisposable(disposable) + + j += 1 + } + + if self.parent.sources.isEmpty { + do { + let result = try self.parent.resultSelector([]) + self.forwardOn(.next(result)) + self.forwardOn(.completed) + self.dispose() + } + catch let error { + self.forwardOn(.error(error)) + self.dispose() + } + } + + return Disposables.create(subscriptions) + } +} + +final private class CombineLatestCollectionType: Producer where Collection.Element: ObservableConvertibleType { + typealias ResultSelector = ([Collection.Element.Element]) throws -> Result + + let sources: Collection + let resultSelector: ResultSelector + let count: Int + + init(sources: Collection, resultSelector: @escaping ResultSelector) { + self.sources = sources + self.resultSelector = resultSelector + self.count = self.sources.count + } + + override func run(_ observer: Observer, cancel: Cancelable) -> (sink: Disposable, subscription: Disposable) where Observer.Element == Result { + let sink = CombineLatestCollectionTypeSink(parent: self, observer: observer, cancel: cancel) + let subscription = sink.run() + return (sink: sink, subscription: subscription) + } +} diff --git a/Pods/RxSwift/RxSwift/Observables/CombineLatest+arity.swift b/Pods/RxSwift/RxSwift/Observables/CombineLatest+arity.swift new file mode 100644 index 0000000..e69bbab --- /dev/null +++ b/Pods/RxSwift/RxSwift/Observables/CombineLatest+arity.swift @@ -0,0 +1,843 @@ +// This file is autogenerated. Take a look at `Preprocessor` target in RxSwift project +// +// CombineLatest+arity.swift +// RxSwift +// +// Created by Krunoslav Zaher on 4/22/15. +// Copyright © 2015 Krunoslav Zaher. All rights reserved. +// + + + +// 2 + +extension ObservableType { + /** + Merges the specified observable sequences into one observable sequence by using the selector function whenever any of the observable sequences produces an element. + + - seealso: [combineLatest operator on reactivex.io](http://reactivex.io/documentation/operators/combinelatest.html) + + - parameter resultSelector: Function to invoke whenever any of the sources produces an element. + - returns: An observable sequence containing the result of combining elements of the sources using the specified result selector function. + */ + public static func combineLatest + (_ source1: O1, _ source2: O2, resultSelector: @escaping (O1.Element, O2.Element) throws -> Element) + -> Observable { + return CombineLatest2( + source1: source1.asObservable(), source2: source2.asObservable(), + resultSelector: resultSelector + ) + } +} + +extension ObservableType where Element == Any { + /** + Merges the specified observable sequences into one observable sequence of tuples whenever any of the observable sequences produces an element. + + - seealso: [combineLatest operator on reactivex.io](http://reactivex.io/documentation/operators/combinelatest.html) + + - returns: An observable sequence containing the result of combining elements of the sources. + */ + public static func combineLatest + (_ source1: O1, _ source2: O2) + -> Observable<(O1.Element, O2.Element)> { + return CombineLatest2( + source1: source1.asObservable(), source2: source2.asObservable(), + resultSelector: { ($0, $1) } + ) + } +} + +final class CombineLatestSink2_ : CombineLatestSink { + typealias Result = Observer.Element + typealias Parent = CombineLatest2 + + let parent: Parent + + var latestElement1: E1! = nil + var latestElement2: E2! = nil + + init(parent: Parent, observer: Observer, cancel: Cancelable) { + self.parent = parent + super.init(arity: 2, observer: observer, cancel: cancel) + } + + func run() -> Disposable { + let subscription1 = SingleAssignmentDisposable() + let subscription2 = SingleAssignmentDisposable() + + let observer1 = CombineLatestObserver(lock: self.lock, parent: self, index: 0, setLatestValue: { (e: E1) -> Void in self.latestElement1 = e }, this: subscription1) + let observer2 = CombineLatestObserver(lock: self.lock, parent: self, index: 1, setLatestValue: { (e: E2) -> Void in self.latestElement2 = e }, this: subscription2) + + subscription1.setDisposable(self.parent.source1.subscribe(observer1)) + subscription2.setDisposable(self.parent.source2.subscribe(observer2)) + + return Disposables.create([ + subscription1, + subscription2 + ]) + } + + override func getResult() throws -> Result { + try self.parent.resultSelector(self.latestElement1, self.latestElement2) + } +} + +final class CombineLatest2 : Producer { + typealias ResultSelector = (E1, E2) throws -> Result + + let source1: Observable + let source2: Observable + + let resultSelector: ResultSelector + + init(source1: Observable, source2: Observable, resultSelector: @escaping ResultSelector) { + self.source1 = source1 + self.source2 = source2 + + self.resultSelector = resultSelector + } + + override func run(_ observer: Observer, cancel: Cancelable) -> (sink: Disposable, subscription: Disposable) where Observer.Element == Result { + let sink = CombineLatestSink2_(parent: self, observer: observer, cancel: cancel) + let subscription = sink.run() + return (sink: sink, subscription: subscription) + } +} + + + +// 3 + +extension ObservableType { + /** + Merges the specified observable sequences into one observable sequence by using the selector function whenever any of the observable sequences produces an element. + + - seealso: [combineLatest operator on reactivex.io](http://reactivex.io/documentation/operators/combinelatest.html) + + - parameter resultSelector: Function to invoke whenever any of the sources produces an element. + - returns: An observable sequence containing the result of combining elements of the sources using the specified result selector function. + */ + public static func combineLatest + (_ source1: O1, _ source2: O2, _ source3: O3, resultSelector: @escaping (O1.Element, O2.Element, O3.Element) throws -> Element) + -> Observable { + return CombineLatest3( + source1: source1.asObservable(), source2: source2.asObservable(), source3: source3.asObservable(), + resultSelector: resultSelector + ) + } +} + +extension ObservableType where Element == Any { + /** + Merges the specified observable sequences into one observable sequence of tuples whenever any of the observable sequences produces an element. + + - seealso: [combineLatest operator on reactivex.io](http://reactivex.io/documentation/operators/combinelatest.html) + + - returns: An observable sequence containing the result of combining elements of the sources. + */ + public static func combineLatest + (_ source1: O1, _ source2: O2, _ source3: O3) + -> Observable<(O1.Element, O2.Element, O3.Element)> { + return CombineLatest3( + source1: source1.asObservable(), source2: source2.asObservable(), source3: source3.asObservable(), + resultSelector: { ($0, $1, $2) } + ) + } +} + +final class CombineLatestSink3_ : CombineLatestSink { + typealias Result = Observer.Element + typealias Parent = CombineLatest3 + + let parent: Parent + + var latestElement1: E1! = nil + var latestElement2: E2! = nil + var latestElement3: E3! = nil + + init(parent: Parent, observer: Observer, cancel: Cancelable) { + self.parent = parent + super.init(arity: 3, observer: observer, cancel: cancel) + } + + func run() -> Disposable { + let subscription1 = SingleAssignmentDisposable() + let subscription2 = SingleAssignmentDisposable() + let subscription3 = SingleAssignmentDisposable() + + let observer1 = CombineLatestObserver(lock: self.lock, parent: self, index: 0, setLatestValue: { (e: E1) -> Void in self.latestElement1 = e }, this: subscription1) + let observer2 = CombineLatestObserver(lock: self.lock, parent: self, index: 1, setLatestValue: { (e: E2) -> Void in self.latestElement2 = e }, this: subscription2) + let observer3 = CombineLatestObserver(lock: self.lock, parent: self, index: 2, setLatestValue: { (e: E3) -> Void in self.latestElement3 = e }, this: subscription3) + + subscription1.setDisposable(self.parent.source1.subscribe(observer1)) + subscription2.setDisposable(self.parent.source2.subscribe(observer2)) + subscription3.setDisposable(self.parent.source3.subscribe(observer3)) + + return Disposables.create([ + subscription1, + subscription2, + subscription3 + ]) + } + + override func getResult() throws -> Result { + try self.parent.resultSelector(self.latestElement1, self.latestElement2, self.latestElement3) + } +} + +final class CombineLatest3 : Producer { + typealias ResultSelector = (E1, E2, E3) throws -> Result + + let source1: Observable + let source2: Observable + let source3: Observable + + let resultSelector: ResultSelector + + init(source1: Observable, source2: Observable, source3: Observable, resultSelector: @escaping ResultSelector) { + self.source1 = source1 + self.source2 = source2 + self.source3 = source3 + + self.resultSelector = resultSelector + } + + override func run(_ observer: Observer, cancel: Cancelable) -> (sink: Disposable, subscription: Disposable) where Observer.Element == Result { + let sink = CombineLatestSink3_(parent: self, observer: observer, cancel: cancel) + let subscription = sink.run() + return (sink: sink, subscription: subscription) + } +} + + + +// 4 + +extension ObservableType { + /** + Merges the specified observable sequences into one observable sequence by using the selector function whenever any of the observable sequences produces an element. + + - seealso: [combineLatest operator on reactivex.io](http://reactivex.io/documentation/operators/combinelatest.html) + + - parameter resultSelector: Function to invoke whenever any of the sources produces an element. + - returns: An observable sequence containing the result of combining elements of the sources using the specified result selector function. + */ + public static func combineLatest + (_ source1: O1, _ source2: O2, _ source3: O3, _ source4: O4, resultSelector: @escaping (O1.Element, O2.Element, O3.Element, O4.Element) throws -> Element) + -> Observable { + return CombineLatest4( + source1: source1.asObservable(), source2: source2.asObservable(), source3: source3.asObservable(), source4: source4.asObservable(), + resultSelector: resultSelector + ) + } +} + +extension ObservableType where Element == Any { + /** + Merges the specified observable sequences into one observable sequence of tuples whenever any of the observable sequences produces an element. + + - seealso: [combineLatest operator on reactivex.io](http://reactivex.io/documentation/operators/combinelatest.html) + + - returns: An observable sequence containing the result of combining elements of the sources. + */ + public static func combineLatest + (_ source1: O1, _ source2: O2, _ source3: O3, _ source4: O4) + -> Observable<(O1.Element, O2.Element, O3.Element, O4.Element)> { + return CombineLatest4( + source1: source1.asObservable(), source2: source2.asObservable(), source3: source3.asObservable(), source4: source4.asObservable(), + resultSelector: { ($0, $1, $2, $3) } + ) + } +} + +final class CombineLatestSink4_ : CombineLatestSink { + typealias Result = Observer.Element + typealias Parent = CombineLatest4 + + let parent: Parent + + var latestElement1: E1! = nil + var latestElement2: E2! = nil + var latestElement3: E3! = nil + var latestElement4: E4! = nil + + init(parent: Parent, observer: Observer, cancel: Cancelable) { + self.parent = parent + super.init(arity: 4, observer: observer, cancel: cancel) + } + + func run() -> Disposable { + let subscription1 = SingleAssignmentDisposable() + let subscription2 = SingleAssignmentDisposable() + let subscription3 = SingleAssignmentDisposable() + let subscription4 = SingleAssignmentDisposable() + + let observer1 = CombineLatestObserver(lock: self.lock, parent: self, index: 0, setLatestValue: { (e: E1) -> Void in self.latestElement1 = e }, this: subscription1) + let observer2 = CombineLatestObserver(lock: self.lock, parent: self, index: 1, setLatestValue: { (e: E2) -> Void in self.latestElement2 = e }, this: subscription2) + let observer3 = CombineLatestObserver(lock: self.lock, parent: self, index: 2, setLatestValue: { (e: E3) -> Void in self.latestElement3 = e }, this: subscription3) + let observer4 = CombineLatestObserver(lock: self.lock, parent: self, index: 3, setLatestValue: { (e: E4) -> Void in self.latestElement4 = e }, this: subscription4) + + subscription1.setDisposable(self.parent.source1.subscribe(observer1)) + subscription2.setDisposable(self.parent.source2.subscribe(observer2)) + subscription3.setDisposable(self.parent.source3.subscribe(observer3)) + subscription4.setDisposable(self.parent.source4.subscribe(observer4)) + + return Disposables.create([ + subscription1, + subscription2, + subscription3, + subscription4 + ]) + } + + override func getResult() throws -> Result { + try self.parent.resultSelector(self.latestElement1, self.latestElement2, self.latestElement3, self.latestElement4) + } +} + +final class CombineLatest4 : Producer { + typealias ResultSelector = (E1, E2, E3, E4) throws -> Result + + let source1: Observable + let source2: Observable + let source3: Observable + let source4: Observable + + let resultSelector: ResultSelector + + init(source1: Observable, source2: Observable, source3: Observable, source4: Observable, resultSelector: @escaping ResultSelector) { + self.source1 = source1 + self.source2 = source2 + self.source3 = source3 + self.source4 = source4 + + self.resultSelector = resultSelector + } + + override func run(_ observer: Observer, cancel: Cancelable) -> (sink: Disposable, subscription: Disposable) where Observer.Element == Result { + let sink = CombineLatestSink4_(parent: self, observer: observer, cancel: cancel) + let subscription = sink.run() + return (sink: sink, subscription: subscription) + } +} + + + +// 5 + +extension ObservableType { + /** + Merges the specified observable sequences into one observable sequence by using the selector function whenever any of the observable sequences produces an element. + + - seealso: [combineLatest operator on reactivex.io](http://reactivex.io/documentation/operators/combinelatest.html) + + - parameter resultSelector: Function to invoke whenever any of the sources produces an element. + - returns: An observable sequence containing the result of combining elements of the sources using the specified result selector function. + */ + public static func combineLatest + (_ source1: O1, _ source2: O2, _ source3: O3, _ source4: O4, _ source5: O5, resultSelector: @escaping (O1.Element, O2.Element, O3.Element, O4.Element, O5.Element) throws -> Element) + -> Observable { + return CombineLatest5( + source1: source1.asObservable(), source2: source2.asObservable(), source3: source3.asObservable(), source4: source4.asObservable(), source5: source5.asObservable(), + resultSelector: resultSelector + ) + } +} + +extension ObservableType where Element == Any { + /** + Merges the specified observable sequences into one observable sequence of tuples whenever any of the observable sequences produces an element. + + - seealso: [combineLatest operator on reactivex.io](http://reactivex.io/documentation/operators/combinelatest.html) + + - returns: An observable sequence containing the result of combining elements of the sources. + */ + public static func combineLatest + (_ source1: O1, _ source2: O2, _ source3: O3, _ source4: O4, _ source5: O5) + -> Observable<(O1.Element, O2.Element, O3.Element, O4.Element, O5.Element)> { + return CombineLatest5( + source1: source1.asObservable(), source2: source2.asObservable(), source3: source3.asObservable(), source4: source4.asObservable(), source5: source5.asObservable(), + resultSelector: { ($0, $1, $2, $3, $4) } + ) + } +} + +final class CombineLatestSink5_ : CombineLatestSink { + typealias Result = Observer.Element + typealias Parent = CombineLatest5 + + let parent: Parent + + var latestElement1: E1! = nil + var latestElement2: E2! = nil + var latestElement3: E3! = nil + var latestElement4: E4! = nil + var latestElement5: E5! = nil + + init(parent: Parent, observer: Observer, cancel: Cancelable) { + self.parent = parent + super.init(arity: 5, observer: observer, cancel: cancel) + } + + func run() -> Disposable { + let subscription1 = SingleAssignmentDisposable() + let subscription2 = SingleAssignmentDisposable() + let subscription3 = SingleAssignmentDisposable() + let subscription4 = SingleAssignmentDisposable() + let subscription5 = SingleAssignmentDisposable() + + let observer1 = CombineLatestObserver(lock: self.lock, parent: self, index: 0, setLatestValue: { (e: E1) -> Void in self.latestElement1 = e }, this: subscription1) + let observer2 = CombineLatestObserver(lock: self.lock, parent: self, index: 1, setLatestValue: { (e: E2) -> Void in self.latestElement2 = e }, this: subscription2) + let observer3 = CombineLatestObserver(lock: self.lock, parent: self, index: 2, setLatestValue: { (e: E3) -> Void in self.latestElement3 = e }, this: subscription3) + let observer4 = CombineLatestObserver(lock: self.lock, parent: self, index: 3, setLatestValue: { (e: E4) -> Void in self.latestElement4 = e }, this: subscription4) + let observer5 = CombineLatestObserver(lock: self.lock, parent: self, index: 4, setLatestValue: { (e: E5) -> Void in self.latestElement5 = e }, this: subscription5) + + subscription1.setDisposable(self.parent.source1.subscribe(observer1)) + subscription2.setDisposable(self.parent.source2.subscribe(observer2)) + subscription3.setDisposable(self.parent.source3.subscribe(observer3)) + subscription4.setDisposable(self.parent.source4.subscribe(observer4)) + subscription5.setDisposable(self.parent.source5.subscribe(observer5)) + + return Disposables.create([ + subscription1, + subscription2, + subscription3, + subscription4, + subscription5 + ]) + } + + override func getResult() throws -> Result { + try self.parent.resultSelector(self.latestElement1, self.latestElement2, self.latestElement3, self.latestElement4, self.latestElement5) + } +} + +final class CombineLatest5 : Producer { + typealias ResultSelector = (E1, E2, E3, E4, E5) throws -> Result + + let source1: Observable + let source2: Observable + let source3: Observable + let source4: Observable + let source5: Observable + + let resultSelector: ResultSelector + + init(source1: Observable, source2: Observable, source3: Observable, source4: Observable, source5: Observable, resultSelector: @escaping ResultSelector) { + self.source1 = source1 + self.source2 = source2 + self.source3 = source3 + self.source4 = source4 + self.source5 = source5 + + self.resultSelector = resultSelector + } + + override func run(_ observer: Observer, cancel: Cancelable) -> (sink: Disposable, subscription: Disposable) where Observer.Element == Result { + let sink = CombineLatestSink5_(parent: self, observer: observer, cancel: cancel) + let subscription = sink.run() + return (sink: sink, subscription: subscription) + } +} + + + +// 6 + +extension ObservableType { + /** + Merges the specified observable sequences into one observable sequence by using the selector function whenever any of the observable sequences produces an element. + + - seealso: [combineLatest operator on reactivex.io](http://reactivex.io/documentation/operators/combinelatest.html) + + - parameter resultSelector: Function to invoke whenever any of the sources produces an element. + - returns: An observable sequence containing the result of combining elements of the sources using the specified result selector function. + */ + public static func combineLatest + (_ source1: O1, _ source2: O2, _ source3: O3, _ source4: O4, _ source5: O5, _ source6: O6, resultSelector: @escaping (O1.Element, O2.Element, O3.Element, O4.Element, O5.Element, O6.Element) throws -> Element) + -> Observable { + return CombineLatest6( + source1: source1.asObservable(), source2: source2.asObservable(), source3: source3.asObservable(), source4: source4.asObservable(), source5: source5.asObservable(), source6: source6.asObservable(), + resultSelector: resultSelector + ) + } +} + +extension ObservableType where Element == Any { + /** + Merges the specified observable sequences into one observable sequence of tuples whenever any of the observable sequences produces an element. + + - seealso: [combineLatest operator on reactivex.io](http://reactivex.io/documentation/operators/combinelatest.html) + + - returns: An observable sequence containing the result of combining elements of the sources. + */ + public static func combineLatest + (_ source1: O1, _ source2: O2, _ source3: O3, _ source4: O4, _ source5: O5, _ source6: O6) + -> Observable<(O1.Element, O2.Element, O3.Element, O4.Element, O5.Element, O6.Element)> { + return CombineLatest6( + source1: source1.asObservable(), source2: source2.asObservable(), source3: source3.asObservable(), source4: source4.asObservable(), source5: source5.asObservable(), source6: source6.asObservable(), + resultSelector: { ($0, $1, $2, $3, $4, $5) } + ) + } +} + +final class CombineLatestSink6_ : CombineLatestSink { + typealias Result = Observer.Element + typealias Parent = CombineLatest6 + + let parent: Parent + + var latestElement1: E1! = nil + var latestElement2: E2! = nil + var latestElement3: E3! = nil + var latestElement4: E4! = nil + var latestElement5: E5! = nil + var latestElement6: E6! = nil + + init(parent: Parent, observer: Observer, cancel: Cancelable) { + self.parent = parent + super.init(arity: 6, observer: observer, cancel: cancel) + } + + func run() -> Disposable { + let subscription1 = SingleAssignmentDisposable() + let subscription2 = SingleAssignmentDisposable() + let subscription3 = SingleAssignmentDisposable() + let subscription4 = SingleAssignmentDisposable() + let subscription5 = SingleAssignmentDisposable() + let subscription6 = SingleAssignmentDisposable() + + let observer1 = CombineLatestObserver(lock: self.lock, parent: self, index: 0, setLatestValue: { (e: E1) -> Void in self.latestElement1 = e }, this: subscription1) + let observer2 = CombineLatestObserver(lock: self.lock, parent: self, index: 1, setLatestValue: { (e: E2) -> Void in self.latestElement2 = e }, this: subscription2) + let observer3 = CombineLatestObserver(lock: self.lock, parent: self, index: 2, setLatestValue: { (e: E3) -> Void in self.latestElement3 = e }, this: subscription3) + let observer4 = CombineLatestObserver(lock: self.lock, parent: self, index: 3, setLatestValue: { (e: E4) -> Void in self.latestElement4 = e }, this: subscription4) + let observer5 = CombineLatestObserver(lock: self.lock, parent: self, index: 4, setLatestValue: { (e: E5) -> Void in self.latestElement5 = e }, this: subscription5) + let observer6 = CombineLatestObserver(lock: self.lock, parent: self, index: 5, setLatestValue: { (e: E6) -> Void in self.latestElement6 = e }, this: subscription6) + + subscription1.setDisposable(self.parent.source1.subscribe(observer1)) + subscription2.setDisposable(self.parent.source2.subscribe(observer2)) + subscription3.setDisposable(self.parent.source3.subscribe(observer3)) + subscription4.setDisposable(self.parent.source4.subscribe(observer4)) + subscription5.setDisposable(self.parent.source5.subscribe(observer5)) + subscription6.setDisposable(self.parent.source6.subscribe(observer6)) + + return Disposables.create([ + subscription1, + subscription2, + subscription3, + subscription4, + subscription5, + subscription6 + ]) + } + + override func getResult() throws -> Result { + try self.parent.resultSelector(self.latestElement1, self.latestElement2, self.latestElement3, self.latestElement4, self.latestElement5, self.latestElement6) + } +} + +final class CombineLatest6 : Producer { + typealias ResultSelector = (E1, E2, E3, E4, E5, E6) throws -> Result + + let source1: Observable + let source2: Observable + let source3: Observable + let source4: Observable + let source5: Observable + let source6: Observable + + let resultSelector: ResultSelector + + init(source1: Observable, source2: Observable, source3: Observable, source4: Observable, source5: Observable, source6: Observable, resultSelector: @escaping ResultSelector) { + self.source1 = source1 + self.source2 = source2 + self.source3 = source3 + self.source4 = source4 + self.source5 = source5 + self.source6 = source6 + + self.resultSelector = resultSelector + } + + override func run(_ observer: Observer, cancel: Cancelable) -> (sink: Disposable, subscription: Disposable) where Observer.Element == Result { + let sink = CombineLatestSink6_(parent: self, observer: observer, cancel: cancel) + let subscription = sink.run() + return (sink: sink, subscription: subscription) + } +} + + + +// 7 + +extension ObservableType { + /** + Merges the specified observable sequences into one observable sequence by using the selector function whenever any of the observable sequences produces an element. + + - seealso: [combineLatest operator on reactivex.io](http://reactivex.io/documentation/operators/combinelatest.html) + + - parameter resultSelector: Function to invoke whenever any of the sources produces an element. + - returns: An observable sequence containing the result of combining elements of the sources using the specified result selector function. + */ + public static func combineLatest + (_ source1: O1, _ source2: O2, _ source3: O3, _ source4: O4, _ source5: O5, _ source6: O6, _ source7: O7, resultSelector: @escaping (O1.Element, O2.Element, O3.Element, O4.Element, O5.Element, O6.Element, O7.Element) throws -> Element) + -> Observable { + return CombineLatest7( + source1: source1.asObservable(), source2: source2.asObservable(), source3: source3.asObservable(), source4: source4.asObservable(), source5: source5.asObservable(), source6: source6.asObservable(), source7: source7.asObservable(), + resultSelector: resultSelector + ) + } +} + +extension ObservableType where Element == Any { + /** + Merges the specified observable sequences into one observable sequence of tuples whenever any of the observable sequences produces an element. + + - seealso: [combineLatest operator on reactivex.io](http://reactivex.io/documentation/operators/combinelatest.html) + + - returns: An observable sequence containing the result of combining elements of the sources. + */ + public static func combineLatest + (_ source1: O1, _ source2: O2, _ source3: O3, _ source4: O4, _ source5: O5, _ source6: O6, _ source7: O7) + -> Observable<(O1.Element, O2.Element, O3.Element, O4.Element, O5.Element, O6.Element, O7.Element)> { + return CombineLatest7( + source1: source1.asObservable(), source2: source2.asObservable(), source3: source3.asObservable(), source4: source4.asObservable(), source5: source5.asObservable(), source6: source6.asObservable(), source7: source7.asObservable(), + resultSelector: { ($0, $1, $2, $3, $4, $5, $6) } + ) + } +} + +final class CombineLatestSink7_ : CombineLatestSink { + typealias Result = Observer.Element + typealias Parent = CombineLatest7 + + let parent: Parent + + var latestElement1: E1! = nil + var latestElement2: E2! = nil + var latestElement3: E3! = nil + var latestElement4: E4! = nil + var latestElement5: E5! = nil + var latestElement6: E6! = nil + var latestElement7: E7! = nil + + init(parent: Parent, observer: Observer, cancel: Cancelable) { + self.parent = parent + super.init(arity: 7, observer: observer, cancel: cancel) + } + + func run() -> Disposable { + let subscription1 = SingleAssignmentDisposable() + let subscription2 = SingleAssignmentDisposable() + let subscription3 = SingleAssignmentDisposable() + let subscription4 = SingleAssignmentDisposable() + let subscription5 = SingleAssignmentDisposable() + let subscription6 = SingleAssignmentDisposable() + let subscription7 = SingleAssignmentDisposable() + + let observer1 = CombineLatestObserver(lock: self.lock, parent: self, index: 0, setLatestValue: { (e: E1) -> Void in self.latestElement1 = e }, this: subscription1) + let observer2 = CombineLatestObserver(lock: self.lock, parent: self, index: 1, setLatestValue: { (e: E2) -> Void in self.latestElement2 = e }, this: subscription2) + let observer3 = CombineLatestObserver(lock: self.lock, parent: self, index: 2, setLatestValue: { (e: E3) -> Void in self.latestElement3 = e }, this: subscription3) + let observer4 = CombineLatestObserver(lock: self.lock, parent: self, index: 3, setLatestValue: { (e: E4) -> Void in self.latestElement4 = e }, this: subscription4) + let observer5 = CombineLatestObserver(lock: self.lock, parent: self, index: 4, setLatestValue: { (e: E5) -> Void in self.latestElement5 = e }, this: subscription5) + let observer6 = CombineLatestObserver(lock: self.lock, parent: self, index: 5, setLatestValue: { (e: E6) -> Void in self.latestElement6 = e }, this: subscription6) + let observer7 = CombineLatestObserver(lock: self.lock, parent: self, index: 6, setLatestValue: { (e: E7) -> Void in self.latestElement7 = e }, this: subscription7) + + subscription1.setDisposable(self.parent.source1.subscribe(observer1)) + subscription2.setDisposable(self.parent.source2.subscribe(observer2)) + subscription3.setDisposable(self.parent.source3.subscribe(observer3)) + subscription4.setDisposable(self.parent.source4.subscribe(observer4)) + subscription5.setDisposable(self.parent.source5.subscribe(observer5)) + subscription6.setDisposable(self.parent.source6.subscribe(observer6)) + subscription7.setDisposable(self.parent.source7.subscribe(observer7)) + + return Disposables.create([ + subscription1, + subscription2, + subscription3, + subscription4, + subscription5, + subscription6, + subscription7 + ]) + } + + override func getResult() throws -> Result { + try self.parent.resultSelector(self.latestElement1, self.latestElement2, self.latestElement3, self.latestElement4, self.latestElement5, self.latestElement6, self.latestElement7) + } +} + +final class CombineLatest7 : Producer { + typealias ResultSelector = (E1, E2, E3, E4, E5, E6, E7) throws -> Result + + let source1: Observable + let source2: Observable + let source3: Observable + let source4: Observable + let source5: Observable + let source6: Observable + let source7: Observable + + let resultSelector: ResultSelector + + init(source1: Observable, source2: Observable, source3: Observable, source4: Observable, source5: Observable, source6: Observable, source7: Observable, resultSelector: @escaping ResultSelector) { + self.source1 = source1 + self.source2 = source2 + self.source3 = source3 + self.source4 = source4 + self.source5 = source5 + self.source6 = source6 + self.source7 = source7 + + self.resultSelector = resultSelector + } + + override func run(_ observer: Observer, cancel: Cancelable) -> (sink: Disposable, subscription: Disposable) where Observer.Element == Result { + let sink = CombineLatestSink7_(parent: self, observer: observer, cancel: cancel) + let subscription = sink.run() + return (sink: sink, subscription: subscription) + } +} + + + +// 8 + +extension ObservableType { + /** + Merges the specified observable sequences into one observable sequence by using the selector function whenever any of the observable sequences produces an element. + + - seealso: [combineLatest operator on reactivex.io](http://reactivex.io/documentation/operators/combinelatest.html) + + - parameter resultSelector: Function to invoke whenever any of the sources produces an element. + - returns: An observable sequence containing the result of combining elements of the sources using the specified result selector function. + */ + public static func combineLatest + (_ source1: O1, _ source2: O2, _ source3: O3, _ source4: O4, _ source5: O5, _ source6: O6, _ source7: O7, _ source8: O8, resultSelector: @escaping (O1.Element, O2.Element, O3.Element, O4.Element, O5.Element, O6.Element, O7.Element, O8.Element) throws -> Element) + -> Observable { + return CombineLatest8( + source1: source1.asObservable(), source2: source2.asObservable(), source3: source3.asObservable(), source4: source4.asObservable(), source5: source5.asObservable(), source6: source6.asObservable(), source7: source7.asObservable(), source8: source8.asObservable(), + resultSelector: resultSelector + ) + } +} + +extension ObservableType where Element == Any { + /** + Merges the specified observable sequences into one observable sequence of tuples whenever any of the observable sequences produces an element. + + - seealso: [combineLatest operator on reactivex.io](http://reactivex.io/documentation/operators/combinelatest.html) + + - returns: An observable sequence containing the result of combining elements of the sources. + */ + public static func combineLatest + (_ source1: O1, _ source2: O2, _ source3: O3, _ source4: O4, _ source5: O5, _ source6: O6, _ source7: O7, _ source8: O8) + -> Observable<(O1.Element, O2.Element, O3.Element, O4.Element, O5.Element, O6.Element, O7.Element, O8.Element)> { + return CombineLatest8( + source1: source1.asObservable(), source2: source2.asObservable(), source3: source3.asObservable(), source4: source4.asObservable(), source5: source5.asObservable(), source6: source6.asObservable(), source7: source7.asObservable(), source8: source8.asObservable(), + resultSelector: { ($0, $1, $2, $3, $4, $5, $6, $7) } + ) + } +} + +final class CombineLatestSink8_ : CombineLatestSink { + typealias Result = Observer.Element + typealias Parent = CombineLatest8 + + let parent: Parent + + var latestElement1: E1! = nil + var latestElement2: E2! = nil + var latestElement3: E3! = nil + var latestElement4: E4! = nil + var latestElement5: E5! = nil + var latestElement6: E6! = nil + var latestElement7: E7! = nil + var latestElement8: E8! = nil + + init(parent: Parent, observer: Observer, cancel: Cancelable) { + self.parent = parent + super.init(arity: 8, observer: observer, cancel: cancel) + } + + func run() -> Disposable { + let subscription1 = SingleAssignmentDisposable() + let subscription2 = SingleAssignmentDisposable() + let subscription3 = SingleAssignmentDisposable() + let subscription4 = SingleAssignmentDisposable() + let subscription5 = SingleAssignmentDisposable() + let subscription6 = SingleAssignmentDisposable() + let subscription7 = SingleAssignmentDisposable() + let subscription8 = SingleAssignmentDisposable() + + let observer1 = CombineLatestObserver(lock: self.lock, parent: self, index: 0, setLatestValue: { (e: E1) -> Void in self.latestElement1 = e }, this: subscription1) + let observer2 = CombineLatestObserver(lock: self.lock, parent: self, index: 1, setLatestValue: { (e: E2) -> Void in self.latestElement2 = e }, this: subscription2) + let observer3 = CombineLatestObserver(lock: self.lock, parent: self, index: 2, setLatestValue: { (e: E3) -> Void in self.latestElement3 = e }, this: subscription3) + let observer4 = CombineLatestObserver(lock: self.lock, parent: self, index: 3, setLatestValue: { (e: E4) -> Void in self.latestElement4 = e }, this: subscription4) + let observer5 = CombineLatestObserver(lock: self.lock, parent: self, index: 4, setLatestValue: { (e: E5) -> Void in self.latestElement5 = e }, this: subscription5) + let observer6 = CombineLatestObserver(lock: self.lock, parent: self, index: 5, setLatestValue: { (e: E6) -> Void in self.latestElement6 = e }, this: subscription6) + let observer7 = CombineLatestObserver(lock: self.lock, parent: self, index: 6, setLatestValue: { (e: E7) -> Void in self.latestElement7 = e }, this: subscription7) + let observer8 = CombineLatestObserver(lock: self.lock, parent: self, index: 7, setLatestValue: { (e: E8) -> Void in self.latestElement8 = e }, this: subscription8) + + subscription1.setDisposable(self.parent.source1.subscribe(observer1)) + subscription2.setDisposable(self.parent.source2.subscribe(observer2)) + subscription3.setDisposable(self.parent.source3.subscribe(observer3)) + subscription4.setDisposable(self.parent.source4.subscribe(observer4)) + subscription5.setDisposable(self.parent.source5.subscribe(observer5)) + subscription6.setDisposable(self.parent.source6.subscribe(observer6)) + subscription7.setDisposable(self.parent.source7.subscribe(observer7)) + subscription8.setDisposable(self.parent.source8.subscribe(observer8)) + + return Disposables.create([ + subscription1, + subscription2, + subscription3, + subscription4, + subscription5, + subscription6, + subscription7, + subscription8 + ]) + } + + override func getResult() throws -> Result { + try self.parent.resultSelector(self.latestElement1, self.latestElement2, self.latestElement3, self.latestElement4, self.latestElement5, self.latestElement6, self.latestElement7, self.latestElement8) + } +} + +final class CombineLatest8 : Producer { + typealias ResultSelector = (E1, E2, E3, E4, E5, E6, E7, E8) throws -> Result + + let source1: Observable + let source2: Observable + let source3: Observable + let source4: Observable + let source5: Observable + let source6: Observable + let source7: Observable + let source8: Observable + + let resultSelector: ResultSelector + + init(source1: Observable, source2: Observable, source3: Observable, source4: Observable, source5: Observable, source6: Observable, source7: Observable, source8: Observable, resultSelector: @escaping ResultSelector) { + self.source1 = source1 + self.source2 = source2 + self.source3 = source3 + self.source4 = source4 + self.source5 = source5 + self.source6 = source6 + self.source7 = source7 + self.source8 = source8 + + self.resultSelector = resultSelector + } + + override func run(_ observer: Observer, cancel: Cancelable) -> (sink: Disposable, subscription: Disposable) where Observer.Element == Result { + let sink = CombineLatestSink8_(parent: self, observer: observer, cancel: cancel) + let subscription = sink.run() + return (sink: sink, subscription: subscription) + } +} + + diff --git a/Pods/RxSwift/RxSwift/Observables/CombineLatest.swift b/Pods/RxSwift/RxSwift/Observables/CombineLatest.swift new file mode 100644 index 0000000..caa0256 --- /dev/null +++ b/Pods/RxSwift/RxSwift/Observables/CombineLatest.swift @@ -0,0 +1,131 @@ +// +// CombineLatest.swift +// RxSwift +// +// Created by Krunoslav Zaher on 3/21/15. +// Copyright © 2015 Krunoslav Zaher. All rights reserved. +// + +protocol CombineLatestProtocol: AnyObject { + func next(_ index: Int) + func fail(_ error: Swift.Error) + func done(_ index: Int) +} + +class CombineLatestSink + : Sink + , CombineLatestProtocol { + typealias Element = Observer.Element + + let lock = RecursiveLock() + + private let arity: Int + private var numberOfValues = 0 + private var numberOfDone = 0 + private var hasValue: [Bool] + private var isDone: [Bool] + + init(arity: Int, observer: Observer, cancel: Cancelable) { + self.arity = arity + self.hasValue = [Bool](repeating: false, count: arity) + self.isDone = [Bool](repeating: false, count: arity) + + super.init(observer: observer, cancel: cancel) + } + + func getResult() throws -> Element { + rxAbstractMethod() + } + + func next(_ index: Int) { + if !self.hasValue[index] { + self.hasValue[index] = true + self.numberOfValues += 1 + } + + if self.numberOfValues == self.arity { + do { + let result = try self.getResult() + self.forwardOn(.next(result)) + } + catch let e { + self.forwardOn(.error(e)) + self.dispose() + } + } + else { + var allOthersDone = true + + for i in 0 ..< self.arity { + if i != index && !self.isDone[i] { + allOthersDone = false + break + } + } + + if allOthersDone { + self.forwardOn(.completed) + self.dispose() + } + } + } + + func fail(_ error: Swift.Error) { + self.forwardOn(.error(error)) + self.dispose() + } + + func done(_ index: Int) { + if self.isDone[index] { + return + } + + self.isDone[index] = true + self.numberOfDone += 1 + + if self.numberOfDone == self.arity { + self.forwardOn(.completed) + self.dispose() + } + } +} + +final class CombineLatestObserver + : ObserverType + , LockOwnerType + , SynchronizedOnType { + typealias ValueSetter = (Element) -> Void + + private let parent: CombineLatestProtocol + + let lock: RecursiveLock + private let index: Int + private let this: Disposable + private let setLatestValue: ValueSetter + + init(lock: RecursiveLock, parent: CombineLatestProtocol, index: Int, setLatestValue: @escaping ValueSetter, this: Disposable) { + self.lock = lock + self.parent = parent + self.index = index + self.this = this + self.setLatestValue = setLatestValue + } + + func on(_ event: Event) { + self.synchronizedOn(event) + } + + func synchronized_on(_ event: Event) { + switch event { + case .next(let value): + self.setLatestValue(value) + self.parent.next(self.index) + case .error(let error): + self.this.dispose() + self.parent.fail(error) + case .completed: + self.this.dispose() + self.parent.done(self.index) + } + } +} diff --git a/Pods/RxSwift/RxSwift/Observables/CompactMap.swift b/Pods/RxSwift/RxSwift/Observables/CompactMap.swift new file mode 100644 index 0000000..7dbcdfb --- /dev/null +++ b/Pods/RxSwift/RxSwift/Observables/CompactMap.swift @@ -0,0 +1,76 @@ +// +// CompactMap.swift +// RxSwift +// +// Created by Michael Long on 04/09/2019. +// Copyright © 2015 Krunoslav Zaher. All rights reserved. +// + +extension ObservableType { + + /** + Projects each element of an observable sequence into an optional form and filters all optional results. + + - parameter transform: A transform function to apply to each source element and which returns an element or nil. + - returns: An observable sequence whose elements are the result of filtering the transform function for each element of the source. + + */ + public func compactMap(_ transform: @escaping (Element) throws -> Result?) + -> Observable { + CompactMap(source: self.asObservable(), transform: transform) + } +} + +final private class CompactMapSink: Sink, ObserverType { + typealias Transform = (SourceType) throws -> ResultType? + + typealias ResultType = Observer.Element + typealias Element = SourceType + + private let transform: Transform + + init(transform: @escaping Transform, observer: Observer, cancel: Cancelable) { + self.transform = transform + super.init(observer: observer, cancel: cancel) + } + + func on(_ event: Event) { + switch event { + case .next(let element): + do { + if let mappedElement = try self.transform(element) { + self.forwardOn(.next(mappedElement)) + } + } + catch let e { + self.forwardOn(.error(e)) + self.dispose() + } + case .error(let error): + self.forwardOn(.error(error)) + self.dispose() + case .completed: + self.forwardOn(.completed) + self.dispose() + } + } +} + +final private class CompactMap: Producer { + typealias Transform = (SourceType) throws -> ResultType? + + private let source: Observable + + private let transform: Transform + + init(source: Observable, transform: @escaping Transform) { + self.source = source + self.transform = transform + } + + override func run(_ observer: Observer, cancel: Cancelable) -> (sink: Disposable, subscription: Disposable) where Observer.Element == ResultType { + let sink = CompactMapSink(transform: self.transform, observer: observer, cancel: cancel) + let subscription = self.source.subscribe(sink) + return (sink: sink, subscription: subscription) + } +} diff --git a/Pods/RxSwift/RxSwift/Observables/Concat.swift b/Pods/RxSwift/RxSwift/Observables/Concat.swift new file mode 100644 index 0000000..b2fb1a2 --- /dev/null +++ b/Pods/RxSwift/RxSwift/Observables/Concat.swift @@ -0,0 +1,131 @@ +// +// Concat.swift +// RxSwift +// +// Created by Krunoslav Zaher on 3/21/15. +// Copyright © 2015 Krunoslav Zaher. All rights reserved. +// + +extension ObservableType { + + /** + Concatenates the second observable sequence to `self` upon successful termination of `self`. + + - seealso: [concat operator on reactivex.io](http://reactivex.io/documentation/operators/concat.html) + + - parameter second: Second observable sequence. + - returns: An observable sequence that contains the elements of `self`, followed by those of the second sequence. + */ + public func concat(_ second: Source) -> Observable where Source.Element == Element { + Observable.concat([self.asObservable(), second.asObservable()]) + } +} + +extension ObservableType { + /** + Concatenates all observable sequences in the given sequence, as long as the previous observable sequence terminated successfully. + + This operator has tail recursive optimizations that will prevent stack overflow. + + Optimizations will be performed in cases equivalent to following: + + [1, [2, [3, .....].concat()].concat].concat() + + - seealso: [concat operator on reactivex.io](http://reactivex.io/documentation/operators/concat.html) + + - returns: An observable sequence that contains the elements of each given sequence, in sequential order. + */ + public static func concat(_ sequence: Sequence) -> Observable + where Sequence.Element == Observable { + return Concat(sources: sequence, count: nil) + } + + /** + Concatenates all observable sequences in the given collection, as long as the previous observable sequence terminated successfully. + + This operator has tail recursive optimizations that will prevent stack overflow. + + Optimizations will be performed in cases equivalent to following: + + [1, [2, [3, .....].concat()].concat].concat() + + - seealso: [concat operator on reactivex.io](http://reactivex.io/documentation/operators/concat.html) + + - returns: An observable sequence that contains the elements of each given sequence, in sequential order. + */ + public static func concat(_ collection: Collection) -> Observable + where Collection.Element == Observable { + return Concat(sources: collection, count: Int64(collection.count)) + } + + /** + Concatenates all observable sequences in the given collection, as long as the previous observable sequence terminated successfully. + + This operator has tail recursive optimizations that will prevent stack overflow. + + Optimizations will be performed in cases equivalent to following: + + [1, [2, [3, .....].concat()].concat].concat() + + - seealso: [concat operator on reactivex.io](http://reactivex.io/documentation/operators/concat.html) + + - returns: An observable sequence that contains the elements of each given sequence, in sequential order. + */ + public static func concat(_ sources: Observable ...) -> Observable { + Concat(sources: sources, count: Int64(sources.count)) + } +} + +final private class ConcatSink + : TailRecursiveSink + , ObserverType where Sequence.Element: ObservableConvertibleType, Sequence.Element.Element == Observer.Element { + typealias Element = Observer.Element + + override init(observer: Observer, cancel: Cancelable) { + super.init(observer: observer, cancel: cancel) + } + + func on(_ event: Event){ + switch event { + case .next: + self.forwardOn(event) + case .error: + self.forwardOn(event) + self.dispose() + case .completed: + self.schedule(.moveNext) + } + } + + override func subscribeToNext(_ source: Observable) -> Disposable { + source.subscribe(self) + } + + override func extract(_ observable: Observable) -> SequenceGenerator? { + if let source = observable as? Concat { + return (source.sources.makeIterator(), source.count) + } + else { + return nil + } + } +} + +final private class Concat: Producer where Sequence.Element: ObservableConvertibleType { + typealias Element = Sequence.Element.Element + + fileprivate let sources: Sequence + fileprivate let count: IntMax? + + init(sources: Sequence, count: IntMax?) { + self.sources = sources + self.count = count + } + + override func run(_ observer: Observer, cancel: Cancelable) -> (sink: Disposable, subscription: Disposable) where Observer.Element == Element { + let sink = ConcatSink(observer: observer, cancel: cancel) + let subscription = sink.run((self.sources.makeIterator(), self.count)) + return (sink: sink, subscription: subscription) + } +} + diff --git a/Pods/RxSwift/RxSwift/Observables/Create.swift b/Pods/RxSwift/RxSwift/Observables/Create.swift new file mode 100644 index 0000000..ca81442 --- /dev/null +++ b/Pods/RxSwift/RxSwift/Observables/Create.swift @@ -0,0 +1,78 @@ +// +// Create.swift +// RxSwift +// +// Created by Krunoslav Zaher on 2/8/15. +// Copyright © 2015 Krunoslav Zaher. All rights reserved. +// + +extension ObservableType { + // MARK: create + + /** + Creates an observable sequence from a specified subscribe method implementation. + + - seealso: [create operator on reactivex.io](http://reactivex.io/documentation/operators/create.html) + + - parameter subscribe: Implementation of the resulting observable sequence's `subscribe` method. + - returns: The observable sequence with the specified implementation for the `subscribe` method. + */ + public static func create(_ subscribe: @escaping (AnyObserver) -> Disposable) -> Observable { + AnonymousObservable(subscribe) + } +} + +final private class AnonymousObservableSink: Sink, ObserverType { + typealias Element = Observer.Element + typealias Parent = AnonymousObservable + + // state + private let isStopped = AtomicInt(0) + + #if DEBUG + private let synchronizationTracker = SynchronizationTracker() + #endif + + override init(observer: Observer, cancel: Cancelable) { + super.init(observer: observer, cancel: cancel) + } + + func on(_ event: Event) { + #if DEBUG + self.synchronizationTracker.register(synchronizationErrorMessage: .default) + defer { self.synchronizationTracker.unregister() } + #endif + switch event { + case .next: + if load(self.isStopped) == 1 { + return + } + self.forwardOn(event) + case .error, .completed: + if fetchOr(self.isStopped, 1) == 0 { + self.forwardOn(event) + self.dispose() + } + } + } + + func run(_ parent: Parent) -> Disposable { + parent.subscribeHandler(AnyObserver(self)) + } +} + +final private class AnonymousObservable: Producer { + typealias SubscribeHandler = (AnyObserver) -> Disposable + + let subscribeHandler: SubscribeHandler + + init(_ subscribeHandler: @escaping SubscribeHandler) { + self.subscribeHandler = subscribeHandler + } + + override func run(_ observer: Observer, cancel: Cancelable) -> (sink: Disposable, subscription: Disposable) where Observer.Element == Element { + let sink = AnonymousObservableSink(observer: observer, cancel: cancel) + let subscription = sink.run(self) + return (sink: sink, subscription: subscription) + } +} diff --git a/Pods/RxSwift/RxSwift/Observables/Debounce.swift b/Pods/RxSwift/RxSwift/Observables/Debounce.swift new file mode 100644 index 0000000..dfab004 --- /dev/null +++ b/Pods/RxSwift/RxSwift/Observables/Debounce.swift @@ -0,0 +1,119 @@ +// +// Debounce.swift +// RxSwift +// +// Created by Krunoslav Zaher on 9/11/16. +// Copyright © 2016 Krunoslav Zaher. All rights reserved. +// + +extension ObservableType { + + /** + Ignores elements from an observable sequence which are followed by another element within a specified relative time duration, using the specified scheduler to run throttling timers. + + - seealso: [debounce operator on reactivex.io](http://reactivex.io/documentation/operators/debounce.html) + + - parameter dueTime: Throttling duration for each element. + - parameter scheduler: Scheduler to run the throttle timers on. + - returns: The throttled sequence. + */ + public func debounce(_ dueTime: RxTimeInterval, scheduler: SchedulerType) + -> Observable { + return Debounce(source: self.asObservable(), dueTime: dueTime, scheduler: scheduler) + } +} + +final private class DebounceSink + : Sink + , ObserverType + , LockOwnerType + , SynchronizedOnType { + typealias Element = Observer.Element + typealias ParentType = Debounce + + private let parent: ParentType + + let lock = RecursiveLock() + + // state + private var id = 0 as UInt64 + private var value: Element? + + let cancellable = SerialDisposable() + + init(parent: ParentType, observer: Observer, cancel: Cancelable) { + self.parent = parent + + super.init(observer: observer, cancel: cancel) + } + + func run() -> Disposable { + let subscription = self.parent.source.subscribe(self) + + return Disposables.create(subscription, cancellable) + } + + func on(_ event: Event) { + self.synchronizedOn(event) + } + + func synchronized_on(_ event: Event) { + switch event { + case .next(let element): + self.id = self.id &+ 1 + let currentId = self.id + self.value = element + + + let scheduler = self.parent.scheduler + let dueTime = self.parent.dueTime + + let d = SingleAssignmentDisposable() + self.cancellable.disposable = d + d.setDisposable(scheduler.scheduleRelative(currentId, dueTime: dueTime, action: self.propagate)) + case .error: + self.value = nil + self.forwardOn(event) + self.dispose() + case .completed: + if let value = self.value { + self.value = nil + self.forwardOn(.next(value)) + } + self.forwardOn(.completed) + self.dispose() + } + } + + func propagate(_ currentId: UInt64) -> Disposable { + self.lock.performLocked { + let originalValue = self.value + + if let value = originalValue, self.id == currentId { + self.value = nil + self.forwardOn(.next(value)) + } + + return Disposables.create() + } + } +} + +final private class Debounce: Producer { + fileprivate let source: Observable + fileprivate let dueTime: RxTimeInterval + fileprivate let scheduler: SchedulerType + + init(source: Observable, dueTime: RxTimeInterval, scheduler: SchedulerType) { + self.source = source + self.dueTime = dueTime + self.scheduler = scheduler + } + + override func run(_ observer: Observer, cancel: Cancelable) -> (sink: Disposable, subscription: Disposable) where Observer.Element == Element { + let sink = DebounceSink(parent: self, observer: observer, cancel: cancel) + let subscription = sink.run() + return (sink: sink, subscription: subscription) + } + +} diff --git a/Pods/RxSwift/RxSwift/Observables/Debug.swift b/Pods/RxSwift/RxSwift/Observables/Debug.swift new file mode 100644 index 0000000..762e394 --- /dev/null +++ b/Pods/RxSwift/RxSwift/Observables/Debug.swift @@ -0,0 +1,102 @@ +// +// Debug.swift +// RxSwift +// +// Created by Krunoslav Zaher on 5/2/15. +// Copyright © 2015 Krunoslav Zaher. All rights reserved. +// + +import Foundation + +extension ObservableType { + + /** + Prints received events for all observers on standard output. + + - seealso: [do operator on reactivex.io](http://reactivex.io/documentation/operators/do.html) + + - parameter identifier: Identifier that is printed together with event description to standard output. + - parameter trimOutput: Should output be trimmed to max 40 characters. + - returns: An observable sequence whose events are printed to standard output. + */ + public func debug(_ identifier: String? = nil, trimOutput: Bool = false, file: String = #file, line: UInt = #line, function: String = #function) + -> Observable { + return Debug(source: self, identifier: identifier, trimOutput: trimOutput, file: file, line: line, function: function) + } +} + +private let dateFormat = "yyyy-MM-dd HH:mm:ss.SSS" + +private func logEvent(_ identifier: String, dateFormat: DateFormatter, content: String) { + print("\(dateFormat.string(from: Date())): \(identifier) -> \(content)") +} + +final private class DebugSink: Sink, ObserverType where Observer.Element == Source.Element { + typealias Element = Observer.Element + typealias Parent = Debug + + private let parent: Parent + private let timestampFormatter = DateFormatter() + + init(parent: Parent, observer: Observer, cancel: Cancelable) { + self.parent = parent + self.timestampFormatter.dateFormat = dateFormat + + logEvent(self.parent.identifier, dateFormat: self.timestampFormatter, content: "subscribed") + + super.init(observer: observer, cancel: cancel) + } + + func on(_ event: Event) { + let maxEventTextLength = 40 + let eventText = "\(event)" + + let eventNormalized = (eventText.count > maxEventTextLength) && self.parent.trimOutput + ? String(eventText.prefix(maxEventTextLength / 2)) + "..." + String(eventText.suffix(maxEventTextLength / 2)) + : eventText + + logEvent(self.parent.identifier, dateFormat: self.timestampFormatter, content: "Event \(eventNormalized)") + + self.forwardOn(event) + if event.isStopEvent { + self.dispose() + } + } + + override func dispose() { + if !self.isDisposed { + logEvent(self.parent.identifier, dateFormat: self.timestampFormatter, content: "isDisposed") + } + super.dispose() + } +} + +final private class Debug: Producer { + fileprivate let identifier: String + fileprivate let trimOutput: Bool + private let source: Source + + init(source: Source, identifier: String?, trimOutput: Bool, file: String, line: UInt, function: String) { + self.trimOutput = trimOutput + if let identifier = identifier { + self.identifier = identifier + } + else { + let trimmedFile: String + if let lastIndex = file.lastIndex(of: "/") { + trimmedFile = String(file[file.index(after: lastIndex) ..< file.endIndex]) + } + else { + trimmedFile = file + } + self.identifier = "\(trimmedFile):\(line) (\(function))" + } + self.source = source + } + + override func run(_ observer: Observer, cancel: Cancelable) -> (sink: Disposable, subscription: Disposable) where Observer.Element == Source.Element { + let sink = DebugSink(parent: self, observer: observer, cancel: cancel) + let subscription = self.source.subscribe(sink) + return (sink: sink, subscription: subscription) + } +} diff --git a/Pods/RxSwift/RxSwift/Observables/Decode.swift b/Pods/RxSwift/RxSwift/Observables/Decode.swift new file mode 100644 index 0000000..8bc7342 --- /dev/null +++ b/Pods/RxSwift/RxSwift/Observables/Decode.swift @@ -0,0 +1,34 @@ +// +// Decode.swift +// RxSwift +// +// Created by Shai Mishali on 24/07/2020. +// Copyright © 2020 Krunoslav Zaher. All rights reserved. +// + +import Foundation + +public extension ObservableType where Element == Data { + /// Attempt to decode the emitted `Data` using a provided decoder. + /// + /// - parameter type: A `Decodable`-conforming type to attempt to decode to + /// - parameter decoder: A capable decoder, e.g. `JSONDecoder` or `PropertyListDecoder` + /// + /// - note: If using a custom decoder, it must conform to the `DataDecoder` protocol. + /// + /// - returns: An `Observable` of the decoded type + func decode(type: Item.Type, + decoder: Decoder) -> Observable { + map { try decoder.decode(type, from: $0) } + } +} + +/// Represents an entity capable of decoding raw `Data` +/// into a concrete `Decodable` type +public protocol DataDecoder { + func decode(_ type: Item.Type, from data: Data) throws -> Item +} + +extension JSONDecoder: DataDecoder {} +extension PropertyListDecoder: DataDecoder {} diff --git a/Pods/RxSwift/RxSwift/Observables/DefaultIfEmpty.swift b/Pods/RxSwift/RxSwift/Observables/DefaultIfEmpty.swift new file mode 100644 index 0000000..8d133d8 --- /dev/null +++ b/Pods/RxSwift/RxSwift/Observables/DefaultIfEmpty.swift @@ -0,0 +1,66 @@ +// +// DefaultIfEmpty.swift +// RxSwift +// +// Created by sergdort on 23/12/2016. +// Copyright © 2016 Krunoslav Zaher. All rights reserved. +// + +extension ObservableType { + + /** + Emits elements from the source observable sequence, or a default element if the source observable sequence is empty. + + - seealso: [DefaultIfEmpty operator on reactivex.io](http://reactivex.io/documentation/operators/defaultifempty.html) + + - parameter default: Default element to be sent if the source does not emit any elements + - returns: An observable sequence which emits default element end completes in case the original sequence is empty + */ + public func ifEmpty(default: Element) -> Observable { + DefaultIfEmpty(source: self.asObservable(), default: `default`) + } +} + +final private class DefaultIfEmptySink: Sink, ObserverType { + typealias Element = Observer.Element + private let `default`: Element + private var isEmpty = true + + init(default: Element, observer: Observer, cancel: Cancelable) { + self.default = `default` + super.init(observer: observer, cancel: cancel) + } + + func on(_ event: Event) { + switch event { + case .next: + self.isEmpty = false + self.forwardOn(event) + case .error: + self.forwardOn(event) + self.dispose() + case .completed: + if self.isEmpty { + self.forwardOn(.next(self.default)) + } + self.forwardOn(.completed) + self.dispose() + } + } +} + +final private class DefaultIfEmpty: Producer { + private let source: Observable + private let `default`: SourceType + + init(source: Observable, `default`: SourceType) { + self.source = source + self.default = `default` + } + + override func run(_ observer: Observer, cancel: Cancelable) -> (sink: Disposable, subscription: Disposable) where Observer.Element == SourceType { + let sink = DefaultIfEmptySink(default: self.default, observer: observer, cancel: cancel) + let subscription = self.source.subscribe(sink) + return (sink: sink, subscription: subscription) + } +} diff --git a/Pods/RxSwift/RxSwift/Observables/Deferred.swift b/Pods/RxSwift/RxSwift/Observables/Deferred.swift new file mode 100644 index 0000000..b81cb16 --- /dev/null +++ b/Pods/RxSwift/RxSwift/Observables/Deferred.swift @@ -0,0 +1,75 @@ +// +// Deferred.swift +// RxSwift +// +// Created by Krunoslav Zaher on 4/19/15. +// Copyright © 2015 Krunoslav Zaher. All rights reserved. +// + +extension ObservableType { + /** + Returns an observable sequence that invokes the specified factory function whenever a new observer subscribes. + + - seealso: [defer operator on reactivex.io](http://reactivex.io/documentation/operators/defer.html) + + - parameter observableFactory: Observable factory function to invoke for each observer that subscribes to the resulting sequence. + - returns: An observable sequence whose observers trigger an invocation of the given observable factory function. + */ + public static func deferred(_ observableFactory: @escaping () throws -> Observable) + -> Observable { + Deferred(observableFactory: observableFactory) + } +} + +final private class DeferredSink: Sink, ObserverType where Source.Element == Observer.Element { + typealias Element = Observer.Element + + private let observableFactory: () throws -> Source + + init(observableFactory: @escaping () throws -> Source, observer: Observer, cancel: Cancelable) { + self.observableFactory = observableFactory + super.init(observer: observer, cancel: cancel) + } + + func run() -> Disposable { + do { + let result = try self.observableFactory() + return result.subscribe(self) + } + catch let e { + self.forwardOn(.error(e)) + self.dispose() + return Disposables.create() + } + } + + func on(_ event: Event) { + self.forwardOn(event) + + switch event { + case .next: + break + case .error: + self.dispose() + case .completed: + self.dispose() + } + } +} + +final private class Deferred: Producer { + typealias Factory = () throws -> Source + + private let observableFactory : Factory + + init(observableFactory: @escaping Factory) { + self.observableFactory = observableFactory + } + + override func run(_ observer: Observer, cancel: Cancelable) -> (sink: Disposable, subscription: Disposable) + where Observer.Element == Source.Element { + let sink = DeferredSink(observableFactory: self.observableFactory, observer: observer, cancel: cancel) + let subscription = sink.run() + return (sink: sink, subscription: subscription) + } +} diff --git a/Pods/RxSwift/RxSwift/Observables/Delay.swift b/Pods/RxSwift/RxSwift/Observables/Delay.swift new file mode 100644 index 0000000..9f71c32 --- /dev/null +++ b/Pods/RxSwift/RxSwift/Observables/Delay.swift @@ -0,0 +1,174 @@ +// +// Delay.swift +// RxSwift +// +// Created by tarunon on 2016/02/09. +// Copyright © 2016 Krunoslav Zaher. All rights reserved. +// + +import Foundation + +extension ObservableType { + + /** + Returns an observable sequence by the source observable sequence shifted forward in time by a specified delay. Error events from the source observable sequence are not delayed. + + - seealso: [delay operator on reactivex.io](http://reactivex.io/documentation/operators/delay.html) + + - parameter dueTime: Relative time shift of the source by. + - parameter scheduler: Scheduler to run the subscription delay timer on. + - returns: the source Observable shifted in time by the specified delay. + */ + public func delay(_ dueTime: RxTimeInterval, scheduler: SchedulerType) + -> Observable { + return Delay(source: self.asObservable(), dueTime: dueTime, scheduler: scheduler) + } +} + +final private class DelaySink + : Sink + , ObserverType { + typealias Element = Observer.Element + typealias Source = Observable + typealias DisposeKey = Bag.KeyType + + private let lock = RecursiveLock() + + private let dueTime: RxTimeInterval + private let scheduler: SchedulerType + + private let sourceSubscription = SingleAssignmentDisposable() + private let cancelable = SerialDisposable() + + // is scheduled some action + private var active = false + // is "run loop" on different scheduler running + private var running = false + private var errorEvent: Event? + + // state + private var queue = Queue<(eventTime: RxTime, event: Event)>(capacity: 0) + + init(observer: Observer, dueTime: RxTimeInterval, scheduler: SchedulerType, cancel: Cancelable) { + self.dueTime = dueTime + self.scheduler = scheduler + super.init(observer: observer, cancel: cancel) + } + + // All of these complications in this method are caused by the fact that + // error should be propagated immediately. Error can be potentially received on different + // scheduler so this process needs to be synchronized somehow. + // + // Another complication is that scheduler is potentially concurrent so internal queue is used. + func drainQueue(state: (), scheduler: AnyRecursiveScheduler<()>) { + self.lock.lock() + let hasFailed = self.errorEvent != nil + if !hasFailed { + self.running = true + } + self.lock.unlock() + + if hasFailed { + return + } + + var ranAtLeastOnce = false + + while true { + self.lock.lock() + let errorEvent = self.errorEvent + + let eventToForwardImmediately = ranAtLeastOnce ? nil : self.queue.dequeue()?.event + let nextEventToScheduleOriginalTime: Date? = ranAtLeastOnce && !self.queue.isEmpty ? self.queue.peek().eventTime : nil + + if errorEvent == nil { + if eventToForwardImmediately != nil { + } + else if nextEventToScheduleOriginalTime != nil { + self.running = false + } + else { + self.running = false + self.active = false + } + } + self.lock.unlock() + + if let errorEvent = errorEvent { + self.forwardOn(errorEvent) + self.dispose() + return + } + else { + if let eventToForwardImmediately = eventToForwardImmediately { + ranAtLeastOnce = true + self.forwardOn(eventToForwardImmediately) + if case .completed = eventToForwardImmediately { + self.dispose() + return + } + } + else if let nextEventToScheduleOriginalTime = nextEventToScheduleOriginalTime { + scheduler.schedule((), dueTime: self.dueTime.reduceWithSpanBetween(earlierDate: nextEventToScheduleOriginalTime, laterDate: self.scheduler.now)) + return + } + else { + return + } + } + } + } + + func on(_ event: Event) { + if event.isStopEvent { + self.sourceSubscription.dispose() + } + + switch event { + case .error: + self.lock.lock() + let shouldSendImmediately = !self.running + self.queue = Queue(capacity: 0) + self.errorEvent = event + self.lock.unlock() + + if shouldSendImmediately { + self.forwardOn(event) + self.dispose() + } + default: + self.lock.lock() + let shouldSchedule = !self.active + self.active = true + self.queue.enqueue((self.scheduler.now, event)) + self.lock.unlock() + + if shouldSchedule { + self.cancelable.disposable = self.scheduler.scheduleRecursive((), dueTime: self.dueTime, action: self.drainQueue) + } + } + } + + func run(source: Observable) -> Disposable { + self.sourceSubscription.setDisposable(source.subscribe(self)) + return Disposables.create(sourceSubscription, cancelable) + } +} + +final private class Delay: Producer { + private let source: Observable + private let dueTime: RxTimeInterval + private let scheduler: SchedulerType + + init(source: Observable, dueTime: RxTimeInterval, scheduler: SchedulerType) { + self.source = source + self.dueTime = dueTime + self.scheduler = scheduler + } + + override func run(_ observer: Observer, cancel: Cancelable) -> (sink: Disposable, subscription: Disposable) where Observer.Element == Element { + let sink = DelaySink(observer: observer, dueTime: self.dueTime, scheduler: self.scheduler, cancel: cancel) + let subscription = sink.run(source: self.source) + return (sink: sink, subscription: subscription) + } +} diff --git a/Pods/RxSwift/RxSwift/Observables/DelaySubscription.swift b/Pods/RxSwift/RxSwift/Observables/DelaySubscription.swift new file mode 100644 index 0000000..fd8c495 --- /dev/null +++ b/Pods/RxSwift/RxSwift/Observables/DelaySubscription.swift @@ -0,0 +1,58 @@ +// +// DelaySubscription.swift +// RxSwift +// +// Created by Krunoslav Zaher on 6/14/15. +// Copyright © 2015 Krunoslav Zaher. All rights reserved. +// + +extension ObservableType { + + /** + Time shifts the observable sequence by delaying the subscription with the specified relative time duration, using the specified scheduler to run timers. + + - seealso: [delay operator on reactivex.io](http://reactivex.io/documentation/operators/delay.html) + + - parameter dueTime: Relative time shift of the subscription. + - parameter scheduler: Scheduler to run the subscription delay timer on. + - returns: Time-shifted sequence. + */ + public func delaySubscription(_ dueTime: RxTimeInterval, scheduler: SchedulerType) + -> Observable { + DelaySubscription(source: self.asObservable(), dueTime: dueTime, scheduler: scheduler) + } +} + +final private class DelaySubscriptionSink + : Sink, ObserverType { + typealias Element = Observer.Element + + func on(_ event: Event) { + self.forwardOn(event) + if event.isStopEvent { + self.dispose() + } + } + +} + +final private class DelaySubscription: Producer { + private let source: Observable + private let dueTime: RxTimeInterval + private let scheduler: SchedulerType + + init(source: Observable, dueTime: RxTimeInterval, scheduler: SchedulerType) { + self.source = source + self.dueTime = dueTime + self.scheduler = scheduler + } + + override func run(_ observer: Observer, cancel: Cancelable) -> (sink: Disposable, subscription: Disposable) where Observer.Element == Element { + let sink = DelaySubscriptionSink(observer: observer, cancel: cancel) + let subscription = self.scheduler.scheduleRelative((), dueTime: self.dueTime) { _ in + return self.source.subscribe(sink) + } + + return (sink: sink, subscription: subscription) + } +} diff --git a/Pods/RxSwift/RxSwift/Observables/Dematerialize.swift b/Pods/RxSwift/RxSwift/Observables/Dematerialize.swift new file mode 100644 index 0000000..2ccd546 --- /dev/null +++ b/Pods/RxSwift/RxSwift/Observables/Dematerialize.swift @@ -0,0 +1,51 @@ +// +// Dematerialize.swift +// RxSwift +// +// Created by Jamie Pinkham on 3/13/17. +// Copyright © 2017 Krunoslav Zaher. All rights reserved. +// + +extension ObservableType where Element: EventConvertible { + /** + Convert any previously materialized Observable into it's original form. + - seealso: [materialize operator on reactivex.io](http://reactivex.io/documentation/operators/materialize-dematerialize.html) + - returns: The dematerialized observable sequence. + */ + public func dematerialize() -> Observable { + Dematerialize(source: self.asObservable()) + } + +} + +private final class DematerializeSink: Sink, ObserverType where Observer.Element == T.Element { + fileprivate func on(_ event: Event) { + switch event { + case .next(let element): + self.forwardOn(element.event) + if element.event.isStopEvent { + self.dispose() + } + case .completed: + self.forwardOn(.completed) + self.dispose() + case .error(let error): + self.forwardOn(.error(error)) + self.dispose() + } + } +} + +final private class Dematerialize: Producer { + private let source: Observable + + init(source: Observable) { + self.source = source + } + + override func run(_ observer: Observer, cancel: Cancelable) -> (sink: Disposable, subscription: Disposable) where Observer.Element == T.Element { + let sink = DematerializeSink(observer: observer, cancel: cancel) + let subscription = self.source.subscribe(sink) + return (sink: sink, subscription: subscription) + } +} diff --git a/Pods/RxSwift/RxSwift/Observables/DistinctUntilChanged.swift b/Pods/RxSwift/RxSwift/Observables/DistinctUntilChanged.swift new file mode 100644 index 0000000..c127b5a --- /dev/null +++ b/Pods/RxSwift/RxSwift/Observables/DistinctUntilChanged.swift @@ -0,0 +1,137 @@ +// +// DistinctUntilChanged.swift +// RxSwift +// +// Created by Krunoslav Zaher on 3/15/15. +// Copyright © 2015 Krunoslav Zaher. All rights reserved. +// + +extension ObservableType where Element: Equatable { + + /** + Returns an observable sequence that contains only distinct contiguous elements according to equality operator. + + - seealso: [distinct operator on reactivex.io](http://reactivex.io/documentation/operators/distinct.html) + + - returns: An observable sequence only containing the distinct contiguous elements, based on equality operator, from the source sequence. + */ + public func distinctUntilChanged() + -> Observable { + self.distinctUntilChanged({ $0 }, comparer: { ($0 == $1) }) + } +} + +extension ObservableType { + /** + Returns an observable sequence that contains only distinct contiguous elements according to the `keySelector`. + + - seealso: [distinct operator on reactivex.io](http://reactivex.io/documentation/operators/distinct.html) + + - parameter keySelector: A function to compute the comparison key for each element. + - returns: An observable sequence only containing the distinct contiguous elements, based on a computed key value, from the source sequence. + */ + public func distinctUntilChanged(_ keySelector: @escaping (Element) throws -> Key) + -> Observable { + self.distinctUntilChanged(keySelector, comparer: { $0 == $1 }) + } + + /** + Returns an observable sequence that contains only distinct contiguous elements according to the `comparer`. + + - seealso: [distinct operator on reactivex.io](http://reactivex.io/documentation/operators/distinct.html) + + - parameter comparer: Equality comparer for computed key values. + - returns: An observable sequence only containing the distinct contiguous elements, based on `comparer`, from the source sequence. + */ + public func distinctUntilChanged(_ comparer: @escaping (Element, Element) throws -> Bool) + -> Observable { + self.distinctUntilChanged({ $0 }, comparer: comparer) + } + + /** + Returns an observable sequence that contains only distinct contiguous elements according to the keySelector and the comparer. + + - seealso: [distinct operator on reactivex.io](http://reactivex.io/documentation/operators/distinct.html) + + - parameter keySelector: A function to compute the comparison key for each element. + - parameter comparer: Equality comparer for computed key values. + - returns: An observable sequence only containing the distinct contiguous elements, based on a computed key value and the comparer, from the source sequence. + */ + public func distinctUntilChanged(_ keySelector: @escaping (Element) throws -> K, comparer: @escaping (K, K) throws -> Bool) + -> Observable { + return DistinctUntilChanged(source: self.asObservable(), selector: keySelector, comparer: comparer) + } + + /** + Returns an observable sequence that contains only contiguous elements with distinct values in the provided key path on each object. + + - seealso: [distinct operator on reactivex.io](http://reactivex.io/documentation/operators/distinct.html) + + - returns: An observable sequence only containing the distinct contiguous elements, based on equality operator on the provided key path + */ + public func distinctUntilChanged(at keyPath: KeyPath) -> + Observable { + self.distinctUntilChanged { $0[keyPath: keyPath] == $1[keyPath: keyPath] } + } +} + +final private class DistinctUntilChangedSink: Sink, ObserverType { + typealias Element = Observer.Element + + private let parent: DistinctUntilChanged + private var currentKey: Key? + + init(parent: DistinctUntilChanged, observer: Observer, cancel: Cancelable) { + self.parent = parent + super.init(observer: observer, cancel: cancel) + } + + func on(_ event: Event) { + switch event { + case .next(let value): + do { + let key = try self.parent.selector(value) + var areEqual = false + if let currentKey = self.currentKey { + areEqual = try self.parent.comparer(currentKey, key) + } + + if areEqual { + return + } + + self.currentKey = key + + self.forwardOn(event) + } + catch let error { + self.forwardOn(.error(error)) + self.dispose() + } + case .error, .completed: + self.forwardOn(event) + self.dispose() + } + } +} + +final private class DistinctUntilChanged: Producer { + typealias KeySelector = (Element) throws -> Key + typealias EqualityComparer = (Key, Key) throws -> Bool + + private let source: Observable + fileprivate let selector: KeySelector + fileprivate let comparer: EqualityComparer + + init(source: Observable, selector: @escaping KeySelector, comparer: @escaping EqualityComparer) { + self.source = source + self.selector = selector + self.comparer = comparer + } + + override func run(_ observer: Observer, cancel: Cancelable) -> (sink: Disposable, subscription: Disposable) where Observer.Element == Element { + let sink = DistinctUntilChangedSink(parent: self, observer: observer, cancel: cancel) + let subscription = self.source.subscribe(sink) + return (sink: sink, subscription: subscription) + } +} diff --git a/Pods/RxSwift/RxSwift/Observables/Do.swift b/Pods/RxSwift/RxSwift/Observables/Do.swift new file mode 100644 index 0000000..3c8c68b --- /dev/null +++ b/Pods/RxSwift/RxSwift/Observables/Do.swift @@ -0,0 +1,112 @@ +// +// Do.swift +// RxSwift +// +// Created by Krunoslav Zaher on 2/21/15. +// Copyright © 2015 Krunoslav Zaher. All rights reserved. +// + +extension ObservableType { + /** + Invokes an action for each event in the observable sequence, and propagates all observer messages through the result sequence. + + - seealso: [do operator on reactivex.io](http://reactivex.io/documentation/operators/do.html) + + - parameter onNext: Action to invoke for each element in the observable sequence. + - parameter afterNext: Action to invoke for each element after the observable has passed an onNext event along to its downstream. + - parameter onError: Action to invoke upon errored termination of the observable sequence. + - parameter afterError: Action to invoke after errored termination of the observable sequence. + - parameter onCompleted: Action to invoke upon graceful termination of the observable sequence. + - parameter afterCompleted: Action to invoke after graceful termination of the observable sequence. + - parameter onSubscribe: Action to invoke before subscribing to source observable sequence. + - parameter onSubscribed: Action to invoke after subscribing to source observable sequence. + - parameter onDispose: Action to invoke after subscription to source observable has been disposed for any reason. It can be either because sequence terminates for some reason or observer subscription being disposed. + - returns: The source sequence with the side-effecting behavior applied. + */ + public func `do`(onNext: ((Element) throws -> Void)? = nil, afterNext: ((Element) throws -> Void)? = nil, onError: ((Swift.Error) throws -> Void)? = nil, afterError: ((Swift.Error) throws -> Void)? = nil, onCompleted: (() throws -> Void)? = nil, afterCompleted: (() throws -> Void)? = nil, onSubscribe: (() -> Void)? = nil, onSubscribed: (() -> Void)? = nil, onDispose: (() -> Void)? = nil) + -> Observable { + return Do(source: self.asObservable(), eventHandler: { e in + switch e { + case .next(let element): + try onNext?(element) + case .error(let e): + try onError?(e) + case .completed: + try onCompleted?() + } + }, afterEventHandler: { e in + switch e { + case .next(let element): + try afterNext?(element) + case .error(let e): + try afterError?(e) + case .completed: + try afterCompleted?() + } + }, onSubscribe: onSubscribe, onSubscribed: onSubscribed, onDispose: onDispose) + } +} + +final private class DoSink: Sink, ObserverType { + typealias Element = Observer.Element + typealias EventHandler = (Event) throws -> Void + typealias AfterEventHandler = (Event) throws -> Void + + private let eventHandler: EventHandler + private let afterEventHandler: AfterEventHandler + + init(eventHandler: @escaping EventHandler, afterEventHandler: @escaping AfterEventHandler, observer: Observer, cancel: Cancelable) { + self.eventHandler = eventHandler + self.afterEventHandler = afterEventHandler + super.init(observer: observer, cancel: cancel) + } + + func on(_ event: Event) { + do { + try self.eventHandler(event) + self.forwardOn(event) + try self.afterEventHandler(event) + if event.isStopEvent { + self.dispose() + } + } + catch let error { + self.forwardOn(.error(error)) + self.dispose() + } + } +} + +final private class Do: Producer { + typealias EventHandler = (Event) throws -> Void + typealias AfterEventHandler = (Event) throws -> Void + + private let source: Observable + private let eventHandler: EventHandler + private let afterEventHandler: AfterEventHandler + private let onSubscribe: (() -> Void)? + private let onSubscribed: (() -> Void)? + private let onDispose: (() -> Void)? + + init(source: Observable, eventHandler: @escaping EventHandler, afterEventHandler: @escaping AfterEventHandler, onSubscribe: (() -> Void)?, onSubscribed: (() -> Void)?, onDispose: (() -> Void)?) { + self.source = source + self.eventHandler = eventHandler + self.afterEventHandler = afterEventHandler + self.onSubscribe = onSubscribe + self.onSubscribed = onSubscribed + self.onDispose = onDispose + } + + override func run(_ observer: Observer, cancel: Cancelable) -> (sink: Disposable, subscription: Disposable) where Observer.Element == Element { + self.onSubscribe?() + let sink = DoSink(eventHandler: self.eventHandler, afterEventHandler: self.afterEventHandler, observer: observer, cancel: cancel) + let subscription = self.source.subscribe(sink) + self.onSubscribed?() + let onDispose = self.onDispose + let allSubscriptions = Disposables.create { + subscription.dispose() + onDispose?() + } + return (sink: sink, subscription: allSubscriptions) + } +} diff --git a/Pods/RxSwift/RxSwift/Observables/ElementAt.swift b/Pods/RxSwift/RxSwift/Observables/ElementAt.swift new file mode 100644 index 0000000..3f09c70 --- /dev/null +++ b/Pods/RxSwift/RxSwift/Observables/ElementAt.swift @@ -0,0 +1,105 @@ +// +// ElementAt.swift +// RxSwift +// +// Created by Junior B. on 21/10/15. +// Copyright © 2015 Krunoslav Zaher. All rights reserved. +// + +extension ObservableType { + /** + Returns a sequence emitting only element _n_ emitted by an Observable + + - seealso: [elementAt operator on reactivex.io](http://reactivex.io/documentation/operators/elementat.html) + + - parameter index: The index of the required element (starting from 0). + - returns: An observable sequence that emits the desired element as its own sole emission. + */ + @available(*, deprecated, renamed: "element(at:)") + public func elementAt(_ index: Int) + -> Observable { + element(at: index) + } + + /** + Returns a sequence emitting only element _n_ emitted by an Observable + + - seealso: [elementAt operator on reactivex.io](http://reactivex.io/documentation/operators/elementat.html) + + - parameter index: The index of the required element (starting from 0). + - returns: An observable sequence that emits the desired element as its own sole emission. + */ + public func element(at index: Int) + -> Observable { + ElementAt(source: self.asObservable(), index: index, throwOnEmpty: true) + } +} + +final private class ElementAtSink: Sink, ObserverType { + typealias SourceType = Observer.Element + typealias Parent = ElementAt + + let parent: Parent + var i: Int + + init(parent: Parent, observer: Observer, cancel: Cancelable) { + self.parent = parent + self.i = parent.index + + super.init(observer: observer, cancel: cancel) + } + + func on(_ event: Event) { + switch event { + case .next: + + if self.i == 0 { + self.forwardOn(event) + self.forwardOn(.completed) + self.dispose() + } + + do { + _ = try decrementChecked(&self.i) + } catch let e { + self.forwardOn(.error(e)) + self.dispose() + return + } + + case .error(let e): + self.forwardOn(.error(e)) + self.dispose() + case .completed: + if self.parent.throwOnEmpty { + self.forwardOn(.error(RxError.argumentOutOfRange)) + } else { + self.forwardOn(.completed) + } + + self.dispose() + } + } +} + +final private class ElementAt: Producer { + let source: Observable + let throwOnEmpty: Bool + let index: Int + + init(source: Observable, index: Int, throwOnEmpty: Bool) { + if index < 0 { + rxFatalError("index can't be negative") + } + + self.source = source + self.index = index + self.throwOnEmpty = throwOnEmpty + } + + override func run(_ observer: Observer, cancel: Cancelable) -> (sink: Disposable, subscription: Disposable) where Observer.Element == SourceType { + let sink = ElementAtSink(parent: self, observer: observer, cancel: cancel) + let subscription = self.source.subscribe(sink) + return (sink: sink, subscription: subscription) + } +} diff --git a/Pods/RxSwift/RxSwift/Observables/Empty.swift b/Pods/RxSwift/RxSwift/Observables/Empty.swift new file mode 100644 index 0000000..9ca5965 --- /dev/null +++ b/Pods/RxSwift/RxSwift/Observables/Empty.swift @@ -0,0 +1,27 @@ +// +// Empty.swift +// RxSwift +// +// Created by Krunoslav Zaher on 8/30/15. +// Copyright © 2015 Krunoslav Zaher. All rights reserved. +// + +extension ObservableType { + /** + Returns an empty observable sequence, using the specified scheduler to send out the single `Completed` message. + + - seealso: [empty operator on reactivex.io](http://reactivex.io/documentation/operators/empty-never-throw.html) + + - returns: An observable sequence with no elements. + */ + public static func empty() -> Observable { + EmptyProducer() + } +} + +final private class EmptyProducer: Producer { + override func subscribe(_ observer: Observer) -> Disposable where Observer.Element == Element { + observer.on(.completed) + return Disposables.create() + } +} diff --git a/Pods/RxSwift/RxSwift/Observables/Enumerated.swift b/Pods/RxSwift/RxSwift/Observables/Enumerated.swift new file mode 100644 index 0000000..ef8a0ff --- /dev/null +++ b/Pods/RxSwift/RxSwift/Observables/Enumerated.swift @@ -0,0 +1,61 @@ +// +// Enumerated.swift +// RxSwift +// +// Created by Krunoslav Zaher on 8/6/17. +// Copyright © 2017 Krunoslav Zaher. All rights reserved. +// + +extension ObservableType { + + /** + Enumerates the elements of an observable sequence. + + - seealso: [map operator on reactivex.io](http://reactivex.io/documentation/operators/map.html) + + - returns: An observable sequence that contains tuples of source sequence elements and their indexes. + */ + public func enumerated() + -> Observable<(index: Int, element: Element)> { + Enumerated(source: self.asObservable()) + } +} + +final private class EnumeratedSink: Sink, ObserverType where Observer.Element == (index: Int, element: Element) { + var index = 0 + + func on(_ event: Event) { + switch event { + case .next(let value): + do { + let nextIndex = try incrementChecked(&self.index) + let next = (index: nextIndex, element: value) + self.forwardOn(.next(next)) + } + catch let e { + self.forwardOn(.error(e)) + self.dispose() + } + case .completed: + self.forwardOn(.completed) + self.dispose() + case .error(let error): + self.forwardOn(.error(error)) + self.dispose() + } + } +} + +final private class Enumerated: Producer<(index: Int, element: Element)> { + private let source: Observable + + init(source: Observable) { + self.source = source + } + + override func run(_ observer: Observer, cancel: Cancelable) -> (sink: Disposable, subscription: Disposable) where Observer.Element == (index: Int, element: Element) { + let sink = EnumeratedSink(observer: observer, cancel: cancel) + let subscription = self.source.subscribe(sink) + return (sink: sink, subscription: subscription) + } +} diff --git a/Pods/RxSwift/RxSwift/Observables/Error.swift b/Pods/RxSwift/RxSwift/Observables/Error.swift new file mode 100644 index 0000000..2e722d6 --- /dev/null +++ b/Pods/RxSwift/RxSwift/Observables/Error.swift @@ -0,0 +1,33 @@ +// +// Error.swift +// RxSwift +// +// Created by Krunoslav Zaher on 8/30/15. +// Copyright © 2015 Krunoslav Zaher. All rights reserved. +// + +extension ObservableType { + /** + Returns an observable sequence that terminates with an `error`. + + - seealso: [throw operator on reactivex.io](http://reactivex.io/documentation/operators/empty-never-throw.html) + + - returns: The observable sequence that terminates with specified error. + */ + public static func error(_ error: Swift.Error) -> Observable { + ErrorProducer(error: error) + } +} + +final private class ErrorProducer: Producer { + private let error: Swift.Error + + init(error: Swift.Error) { + self.error = error + } + + override func subscribe(_ observer: Observer) -> Disposable where Observer.Element == Element { + observer.on(.error(self.error)) + return Disposables.create() + } +} diff --git a/Pods/RxSwift/RxSwift/Observables/Filter.swift b/Pods/RxSwift/RxSwift/Observables/Filter.swift new file mode 100644 index 0000000..61d3ce7 --- /dev/null +++ b/Pods/RxSwift/RxSwift/Observables/Filter.swift @@ -0,0 +1,86 @@ +// +// Filter.swift +// RxSwift +// +// Created by Krunoslav Zaher on 2/17/15. +// Copyright © 2015 Krunoslav Zaher. All rights reserved. +// + +extension ObservableType { + + /** + Filters the elements of an observable sequence based on a predicate. + + - seealso: [filter operator on reactivex.io](http://reactivex.io/documentation/operators/filter.html) + + - parameter predicate: A function to test each source element for a condition. + - returns: An observable sequence that contains elements from the input sequence that satisfy the condition. + */ + public func filter(_ predicate: @escaping (Element) throws -> Bool) + -> Observable { + Filter(source: self.asObservable(), predicate: predicate) + } +} + +extension ObservableType { + /** + Skips elements and completes (or errors) when the observable sequence completes (or errors). Equivalent to filter that always returns false. + + - seealso: [ignoreElements operator on reactivex.io](http://reactivex.io/documentation/operators/ignoreelements.html) + + - returns: An observable sequence that skips all elements of the source sequence. + */ + public func ignoreElements() + -> Observable { + self.flatMap { _ in Observable.empty() } + } +} + +final private class FilterSink: Sink, ObserverType { + typealias Predicate = (Element) throws -> Bool + typealias Element = Observer.Element + + private let predicate: Predicate + + init(predicate: @escaping Predicate, observer: Observer, cancel: Cancelable) { + self.predicate = predicate + super.init(observer: observer, cancel: cancel) + } + + func on(_ event: Event) { + switch event { + case .next(let value): + do { + let satisfies = try self.predicate(value) + if satisfies { + self.forwardOn(.next(value)) + } + } + catch let e { + self.forwardOn(.error(e)) + self.dispose() + } + case .completed, .error: + self.forwardOn(event) + self.dispose() + } + } +} + +final private class Filter: Producer { + typealias Predicate = (Element) throws -> Bool + + private let source: Observable + private let predicate: Predicate + + init(source: Observable, predicate: @escaping Predicate) { + self.source = source + self.predicate = predicate + } + + override func run(_ observer: Observer, cancel: Cancelable) -> (sink: Disposable, subscription: Disposable) where Observer.Element == Element { + let sink = FilterSink(predicate: self.predicate, observer: observer, cancel: cancel) + let subscription = self.source.subscribe(sink) + return (sink: sink, subscription: subscription) + } +} diff --git a/Pods/RxSwift/RxSwift/Observables/First.swift b/Pods/RxSwift/RxSwift/Observables/First.swift new file mode 100644 index 0000000..0014114 --- /dev/null +++ b/Pods/RxSwift/RxSwift/Observables/First.swift @@ -0,0 +1,41 @@ +// +// First.swift +// RxSwift +// +// Created by Krunoslav Zaher on 7/31/17. +// Copyright © 2017 Krunoslav Zaher. All rights reserved. +// + +private final class FirstSink : Sink, ObserverType where Observer.Element == Element? { + typealias Parent = First + + func on(_ event: Event) { + switch event { + case .next(let value): + self.forwardOn(.next(value)) + self.forwardOn(.completed) + self.dispose() + case .error(let error): + self.forwardOn(.error(error)) + self.dispose() + case .completed: + self.forwardOn(.next(nil)) + self.forwardOn(.completed) + self.dispose() + } + } +} + +final class First: Producer { + private let source: Observable + + init(source: Observable) { + self.source = source + } + + override func run(_ observer: Observer, cancel: Cancelable) -> (sink: Disposable, subscription: Disposable) where Observer.Element == Element? { + let sink = FirstSink(observer: observer, cancel: cancel) + let subscription = self.source.subscribe(sink) + return (sink: sink, subscription: subscription) + } +} diff --git a/Pods/RxSwift/RxSwift/Observables/Generate.swift b/Pods/RxSwift/RxSwift/Observables/Generate.swift new file mode 100644 index 0000000..7b924b3 --- /dev/null +++ b/Pods/RxSwift/RxSwift/Observables/Generate.swift @@ -0,0 +1,87 @@ +// +// Generate.swift +// RxSwift +// +// Created by Krunoslav Zaher on 9/2/15. +// Copyright © 2015 Krunoslav Zaher. All rights reserved. +// + +extension ObservableType { + /** + Generates an observable sequence by running a state-driven loop producing the sequence's elements, using the specified scheduler + to run the loop send out observer messages. + + - seealso: [create operator on reactivex.io](http://reactivex.io/documentation/operators/create.html) + + - parameter initialState: Initial state. + - parameter condition: Condition to terminate generation (upon returning `false`). + - parameter iterate: Iteration step function. + - parameter scheduler: Scheduler on which to run the generator loop. + - returns: The generated sequence. + */ + public static func generate(initialState: Element, condition: @escaping (Element) throws -> Bool, scheduler: ImmediateSchedulerType = CurrentThreadScheduler.instance, iterate: @escaping (Element) throws -> Element) -> Observable { + Generate(initialState: initialState, condition: condition, iterate: iterate, resultSelector: { $0 }, scheduler: scheduler) + } +} + +final private class GenerateSink: Sink { + typealias Parent = Generate + + private let parent: Parent + + private var state: Sequence + + init(parent: Parent, observer: Observer, cancel: Cancelable) { + self.parent = parent + self.state = parent.initialState + super.init(observer: observer, cancel: cancel) + } + + func run() -> Disposable { + return self.parent.scheduler.scheduleRecursive(true) { isFirst, recurse -> Void in + do { + if !isFirst { + self.state = try self.parent.iterate(self.state) + } + + if try self.parent.condition(self.state) { + let result = try self.parent.resultSelector(self.state) + self.forwardOn(.next(result)) + + recurse(false) + } + else { + self.forwardOn(.completed) + self.dispose() + } + } + catch let error { + self.forwardOn(.error(error)) + self.dispose() + } + } + } +} + +final private class Generate: Producer { + fileprivate let initialState: Sequence + fileprivate let condition: (Sequence) throws -> Bool + fileprivate let iterate: (Sequence) throws -> Sequence + fileprivate let resultSelector: (Sequence) throws -> Element + fileprivate let scheduler: ImmediateSchedulerType + + init(initialState: Sequence, condition: @escaping (Sequence) throws -> Bool, iterate: @escaping (Sequence) throws -> Sequence, resultSelector: @escaping (Sequence) throws -> Element, scheduler: ImmediateSchedulerType) { + self.initialState = initialState + self.condition = condition + self.iterate = iterate + self.resultSelector = resultSelector + self.scheduler = scheduler + super.init() + } + + override func run(_ observer: Observer, cancel: Cancelable) -> (sink: Disposable, subscription: Disposable) where Observer.Element == Element { + let sink = GenerateSink(parent: self, observer: observer, cancel: cancel) + let subscription = sink.run() + return (sink: sink, subscription: subscription) + } +} diff --git a/Pods/RxSwift/RxSwift/Observables/GroupBy.swift b/Pods/RxSwift/RxSwift/Observables/GroupBy.swift new file mode 100644 index 0000000..88cbda7 --- /dev/null +++ b/Pods/RxSwift/RxSwift/Observables/GroupBy.swift @@ -0,0 +1,133 @@ +// +// GroupBy.swift +// RxSwift +// +// Created by Tomi Koskinen on 01/12/15. +// Copyright © 2015 Krunoslav Zaher. All rights reserved. +// + +extension ObservableType { + /* + Groups the elements of an observable sequence according to a specified key selector function. + + - seealso: [groupBy operator on reactivex.io](http://reactivex.io/documentation/operators/groupby.html) + + - parameter keySelector: A function to extract the key for each element. + - returns: A sequence of observable groups, each of which corresponds to a unique key value, containing all elements that share that same key value. + */ + public func groupBy(keySelector: @escaping (Element) throws -> Key) + -> Observable> { + GroupBy(source: self.asObservable(), selector: keySelector) + } +} + +final private class GroupedObservableImpl: Observable { + private var subject: PublishSubject + private var refCount: RefCountDisposable + + init(subject: PublishSubject, refCount: RefCountDisposable) { + self.subject = subject + self.refCount = refCount + } + + override public func subscribe(_ observer: Observer) -> Disposable where Observer.Element == Element { + let release = self.refCount.retain() + let subscription = self.subject.subscribe(observer) + return Disposables.create(release, subscription) + } +} + + +final private class GroupBySink + : Sink + , ObserverType where Observer.Element == GroupedObservable { + typealias ResultType = Observer.Element + typealias Parent = GroupBy + + private let parent: Parent + private let subscription = SingleAssignmentDisposable() + private var refCountDisposable: RefCountDisposable! + private var groupedSubjectTable: [Key: PublishSubject] + + init(parent: Parent, observer: Observer, cancel: Cancelable) { + self.parent = parent + self.groupedSubjectTable = [Key: PublishSubject]() + super.init(observer: observer, cancel: cancel) + } + + func run() -> Disposable { + self.refCountDisposable = RefCountDisposable(disposable: self.subscription) + + self.subscription.setDisposable(self.parent.source.subscribe(self)) + + return self.refCountDisposable + } + + private func onGroupEvent(key: Key, value: Element) { + if let writer = self.groupedSubjectTable[key] { + writer.on(.next(value)) + } else { + let writer = PublishSubject() + self.groupedSubjectTable[key] = writer + + let group = GroupedObservable( + key: key, + source: GroupedObservableImpl(subject: writer, refCount: refCountDisposable) + ) + + self.forwardOn(.next(group)) + writer.on(.next(value)) + } + } + + final func on(_ event: Event) { + switch event { + case let .next(value): + do { + let groupKey = try self.parent.selector(value) + self.onGroupEvent(key: groupKey, value: value) + } + catch let e { + self.error(e) + return + } + case let .error(e): + self.error(e) + case .completed: + self.forwardOnGroups(event: .completed) + self.forwardOn(.completed) + self.subscription.dispose() + self.dispose() + } + } + + final func error(_ error: Swift.Error) { + self.forwardOnGroups(event: .error(error)) + self.forwardOn(.error(error)) + self.subscription.dispose() + self.dispose() + } + + final func forwardOnGroups(event: Event) { + for writer in self.groupedSubjectTable.values { + writer.on(event) + } + } +} + +final private class GroupBy: Producer> { + typealias KeySelector = (Element) throws -> Key + + fileprivate let source: Observable + fileprivate let selector: KeySelector + + init(source: Observable, selector: @escaping KeySelector) { + self.source = source + self.selector = selector + } + + override func run(_ observer: Observer, cancel: Cancelable) -> (sink: Disposable, subscription: Disposable) where Observer.Element == GroupedObservable { + let sink = GroupBySink(parent: self, observer: observer, cancel: cancel) + return (sink: sink, subscription: sink.run()) + } +} diff --git a/Pods/RxSwift/RxSwift/Observables/Just.swift b/Pods/RxSwift/RxSwift/Observables/Just.swift new file mode 100644 index 0000000..9349083 --- /dev/null +++ b/Pods/RxSwift/RxSwift/Observables/Just.swift @@ -0,0 +1,87 @@ +// +// Just.swift +// RxSwift +// +// Created by Krunoslav Zaher on 8/30/15. +// Copyright © 2015 Krunoslav Zaher. All rights reserved. +// + +extension ObservableType { + /** + Returns an observable sequence that contains a single element. + + - seealso: [just operator on reactivex.io](http://reactivex.io/documentation/operators/just.html) + + - parameter element: Single element in the resulting observable sequence. + - returns: An observable sequence containing the single specified element. + */ + public static func just(_ element: Element) -> Observable { + Just(element: element) + } + + /** + Returns an observable sequence that contains a single element. + + - seealso: [just operator on reactivex.io](http://reactivex.io/documentation/operators/just.html) + + - parameter element: Single element in the resulting observable sequence. + - parameter scheduler: Scheduler to send the single element on. + - returns: An observable sequence containing the single specified element. + */ + public static func just(_ element: Element, scheduler: ImmediateSchedulerType) -> Observable { + JustScheduled(element: element, scheduler: scheduler) + } +} + +final private class JustScheduledSink: Sink { + typealias Parent = JustScheduled + + private let parent: Parent + + init(parent: Parent, observer: Observer, cancel: Cancelable) { + self.parent = parent + super.init(observer: observer, cancel: cancel) + } + + func run() -> Disposable { + let scheduler = self.parent.scheduler + return scheduler.schedule(self.parent.element) { element in + self.forwardOn(.next(element)) + return scheduler.schedule(()) { _ in + self.forwardOn(.completed) + self.dispose() + return Disposables.create() + } + } + } +} + +final private class JustScheduled: Producer { + fileprivate let scheduler: ImmediateSchedulerType + fileprivate let element: Element + + init(element: Element, scheduler: ImmediateSchedulerType) { + self.scheduler = scheduler + self.element = element + } + + override func run(_ observer: Observer, cancel: Cancelable) -> (sink: Disposable, subscription: Disposable) where Observer.Element == Element { + let sink = JustScheduledSink(parent: self, observer: observer, cancel: cancel) + let subscription = sink.run() + return (sink: sink, subscription: subscription) + } +} + +final private class Just: Producer { + private let element: Element + + init(element: Element) { + self.element = element + } + + override func subscribe(_ observer: Observer) -> Disposable where Observer.Element == Element { + observer.on(.next(self.element)) + observer.on(.completed) + return Disposables.create() + } +} diff --git a/Pods/RxSwift/RxSwift/Observables/Map.swift b/Pods/RxSwift/RxSwift/Observables/Map.swift new file mode 100644 index 0000000..0691273 --- /dev/null +++ b/Pods/RxSwift/RxSwift/Observables/Map.swift @@ -0,0 +1,77 @@ +// +// Map.swift +// RxSwift +// +// Created by Krunoslav Zaher on 3/15/15. +// Copyright © 2015 Krunoslav Zaher. All rights reserved. +// + +extension ObservableType { + + /** + Projects each element of an observable sequence into a new form. + + - seealso: [map operator on reactivex.io](http://reactivex.io/documentation/operators/map.html) + + - parameter transform: A transform function to apply to each source element. + - returns: An observable sequence whose elements are the result of invoking the transform function on each element of source. + + */ + public func map(_ transform: @escaping (Element) throws -> Result) + -> Observable { + Map(source: self.asObservable(), transform: transform) + } +} + +final private class MapSink: Sink, ObserverType { + typealias Transform = (SourceType) throws -> ResultType + + typealias ResultType = Observer.Element + typealias Element = SourceType + + private let transform: Transform + + init(transform: @escaping Transform, observer: Observer, cancel: Cancelable) { + self.transform = transform + super.init(observer: observer, cancel: cancel) + } + + func on(_ event: Event) { + switch event { + case .next(let element): + do { + let mappedElement = try self.transform(element) + self.forwardOn(.next(mappedElement)) + } + catch let e { + self.forwardOn(.error(e)) + self.dispose() + } + case .error(let error): + self.forwardOn(.error(error)) + self.dispose() + case .completed: + self.forwardOn(.completed) + self.dispose() + } + } +} + +final private class Map: Producer { + typealias Transform = (SourceType) throws -> ResultType + + private let source: Observable + + private let transform: Transform + + init(source: Observable, transform: @escaping Transform) { + self.source = source + self.transform = transform + } + + override func run(_ observer: Observer, cancel: Cancelable) -> (sink: Disposable, subscription: Disposable) where Observer.Element == ResultType { + let sink = MapSink(transform: self.transform, observer: observer, cancel: cancel) + let subscription = self.source.subscribe(sink) + return (sink: sink, subscription: subscription) + } +} diff --git a/Pods/RxSwift/RxSwift/Observables/Materialize.swift b/Pods/RxSwift/RxSwift/Observables/Materialize.swift new file mode 100644 index 0000000..e2577be --- /dev/null +++ b/Pods/RxSwift/RxSwift/Observables/Materialize.swift @@ -0,0 +1,44 @@ +// +// Materialize.swift +// RxSwift +// +// Created by sergdort on 08/03/2017. +// Copyright © 2017 Krunoslav Zaher. All rights reserved. +// + +extension ObservableType { + /** + Convert any Observable into an Observable of its events. + - seealso: [materialize operator on reactivex.io](http://reactivex.io/documentation/operators/materialize-dematerialize.html) + - returns: An observable sequence that wraps events in an Event. The returned Observable never errors, but it does complete after observing all of the events of the underlying Observable. + */ + public func materialize() -> Observable> { + Materialize(source: self.asObservable()) + } +} + +private final class MaterializeSink: Sink, ObserverType where Observer.Element == Event { + + func on(_ event: Event) { + self.forwardOn(.next(event)) + if event.isStopEvent { + self.forwardOn(.completed) + self.dispose() + } + } +} + +final private class Materialize: Producer> { + private let source: Observable + + init(source: Observable) { + self.source = source + } + + override func run(_ observer: Observer, cancel: Cancelable) -> (sink: Disposable, subscription: Disposable) where Observer.Element == Element { + let sink = MaterializeSink(observer: observer, cancel: cancel) + let subscription = self.source.subscribe(sink) + + return (sink: sink, subscription: subscription) + } +} diff --git a/Pods/RxSwift/RxSwift/Observables/Merge.swift b/Pods/RxSwift/RxSwift/Observables/Merge.swift new file mode 100644 index 0000000..51a6462 --- /dev/null +++ b/Pods/RxSwift/RxSwift/Observables/Merge.swift @@ -0,0 +1,600 @@ +// +// Merge.swift +// RxSwift +// +// Created by Krunoslav Zaher on 3/28/15. +// Copyright © 2015 Krunoslav Zaher. All rights reserved. +// + +extension ObservableType { + + /** + Projects each element of an observable sequence to an observable sequence and merges the resulting observable sequences into one observable sequence. + + - seealso: [flatMap operator on reactivex.io](http://reactivex.io/documentation/operators/flatmap.html) + + - parameter selector: A transform function to apply to each element. + - returns: An observable sequence whose elements are the result of invoking the one-to-many transform function on each element of the input sequence. + */ + public func flatMap(_ selector: @escaping (Element) throws -> Source) + -> Observable { + return FlatMap(source: self.asObservable(), selector: selector) + } + +} + +extension ObservableType { + + /** + Projects each element of an observable sequence to an observable sequence and merges the resulting observable sequences into one observable sequence. + If element is received while there is some projected observable sequence being merged it will simply be ignored. + + - seealso: [flatMapFirst operator on reactivex.io](http://reactivex.io/documentation/operators/flatmap.html) + + - parameter selector: A transform function to apply to element that was observed while no observable is executing in parallel. + - returns: An observable sequence whose elements are the result of invoking the one-to-many transform function on each element of the input sequence that was received while no other sequence was being calculated. + */ + public func flatMapFirst(_ selector: @escaping (Element) throws -> Source) + -> Observable { + return FlatMapFirst(source: self.asObservable(), selector: selector) + } +} + +extension ObservableType where Element: ObservableConvertibleType { + + /** + Merges elements from all observable sequences in the given enumerable sequence into a single observable sequence. + + - seealso: [merge operator on reactivex.io](http://reactivex.io/documentation/operators/merge.html) + + - returns: The observable sequence that merges the elements of the observable sequences. + */ + public func merge() -> Observable { + Merge(source: self.asObservable()) + } + + /** + Merges elements from all inner observable sequences into a single observable sequence, limiting the number of concurrent subscriptions to inner sequences. + + - seealso: [merge operator on reactivex.io](http://reactivex.io/documentation/operators/merge.html) + + - parameter maxConcurrent: Maximum number of inner observable sequences being subscribed to concurrently. + - returns: The observable sequence that merges the elements of the inner sequences. + */ + public func merge(maxConcurrent: Int) + -> Observable { + MergeLimited(source: self.asObservable(), maxConcurrent: maxConcurrent) + } +} + +extension ObservableType where Element: ObservableConvertibleType { + + /** + Concatenates all inner observable sequences, as long as the previous observable sequence terminated successfully. + + - seealso: [concat operator on reactivex.io](http://reactivex.io/documentation/operators/concat.html) + + - returns: An observable sequence that contains the elements of each observed inner sequence, in sequential order. + */ + public func concat() -> Observable { + self.merge(maxConcurrent: 1) + } +} + +extension ObservableType { + /** + Merges elements from all observable sequences from collection into a single observable sequence. + + - seealso: [merge operator on reactivex.io](http://reactivex.io/documentation/operators/merge.html) + + - parameter sources: Collection of observable sequences to merge. + - returns: The observable sequence that merges the elements of the observable sequences. + */ + public static func merge(_ sources: Collection) -> Observable where Collection.Element == Observable { + MergeArray(sources: Array(sources)) + } + + /** + Merges elements from all observable sequences from array into a single observable sequence. + + - seealso: [merge operator on reactivex.io](http://reactivex.io/documentation/operators/merge.html) + + - parameter sources: Array of observable sequences to merge. + - returns: The observable sequence that merges the elements of the observable sequences. + */ + public static func merge(_ sources: [Observable]) -> Observable { + MergeArray(sources: sources) + } + + /** + Merges elements from all observable sequences into a single observable sequence. + + - seealso: [merge operator on reactivex.io](http://reactivex.io/documentation/operators/merge.html) + + - parameter sources: Collection of observable sequences to merge. + - returns: The observable sequence that merges the elements of the observable sequences. + */ + public static func merge(_ sources: Observable...) -> Observable { + MergeArray(sources: sources) + } +} + +// MARK: concatMap + +extension ObservableType { + /** + Projects each element of an observable sequence to an observable sequence and concatenates the resulting observable sequences into one observable sequence. + + - seealso: [concat operator on reactivex.io](http://reactivex.io/documentation/operators/concat.html) + + - returns: An observable sequence that contains the elements of each observed inner sequence, in sequential order. + */ + + public func concatMap(_ selector: @escaping (Element) throws -> Source) + -> Observable { + return ConcatMap(source: self.asObservable(), selector: selector) + } +} + +private final class MergeLimitedSinkIter + : ObserverType + , LockOwnerType + , SynchronizedOnType where SourceSequence.Element == Observer.Element { + typealias Element = Observer.Element + typealias DisposeKey = CompositeDisposable.DisposeKey + typealias Parent = MergeLimitedSink + + private let parent: Parent + private let disposeKey: DisposeKey + + var lock: RecursiveLock { + self.parent.lock + } + + init(parent: Parent, disposeKey: DisposeKey) { + self.parent = parent + self.disposeKey = disposeKey + } + + func on(_ event: Event) { + self.synchronizedOn(event) + } + + func synchronized_on(_ event: Event) { + switch event { + case .next: + self.parent.forwardOn(event) + case .error: + self.parent.forwardOn(event) + self.parent.dispose() + case .completed: + self.parent.group.remove(for: self.disposeKey) + if let next = self.parent.queue.dequeue() { + self.parent.subscribe(next, group: self.parent.group) + } + else { + self.parent.activeCount -= 1 + + if self.parent.stopped && self.parent.activeCount == 0 { + self.parent.forwardOn(.completed) + self.parent.dispose() + } + } + } + } +} + +private final class ConcatMapSink: MergeLimitedSink where Observer.Element == SourceSequence.Element { + typealias Selector = (SourceElement) throws -> SourceSequence + + private let selector: Selector + + init(selector: @escaping Selector, observer: Observer, cancel: Cancelable) { + self.selector = selector + super.init(maxConcurrent: 1, observer: observer, cancel: cancel) + } + + override func performMap(_ element: SourceElement) throws -> SourceSequence { + try self.selector(element) + } +} + +private final class MergeLimitedBasicSink: MergeLimitedSink where Observer.Element == SourceSequence.Element { + + override func performMap(_ element: SourceSequence) throws -> SourceSequence { + element + } +} + +private class MergeLimitedSink + : Sink + , ObserverType where Observer.Element == SourceSequence.Element { + typealias QueueType = Queue + + let maxConcurrent: Int + + let lock = RecursiveLock() + + // state + var stopped = false + var activeCount = 0 + var queue = QueueType(capacity: 2) + + let sourceSubscription = SingleAssignmentDisposable() + let group = CompositeDisposable() + + init(maxConcurrent: Int, observer: Observer, cancel: Cancelable) { + self.maxConcurrent = maxConcurrent + super.init(observer: observer, cancel: cancel) + } + + func run(_ source: Observable) -> Disposable { + _ = self.group.insert(self.sourceSubscription) + + let disposable = source.subscribe(self) + self.sourceSubscription.setDisposable(disposable) + return self.group + } + + func subscribe(_ innerSource: SourceSequence, group: CompositeDisposable) { + let subscription = SingleAssignmentDisposable() + + let key = group.insert(subscription) + + if let key = key { + let observer = MergeLimitedSinkIter(parent: self, disposeKey: key) + + let disposable = innerSource.asObservable().subscribe(observer) + subscription.setDisposable(disposable) + } + } + + func performMap(_ element: SourceElement) throws -> SourceSequence { + rxAbstractMethod() + } + + @inline(__always) + final private func nextElementArrived(element: SourceElement) -> SourceSequence? { + self.lock.performLocked { + let subscribe: Bool + if self.activeCount < self.maxConcurrent { + self.activeCount += 1 + subscribe = true + } + else { + do { + let value = try self.performMap(element) + self.queue.enqueue(value) + } catch { + self.forwardOn(.error(error)) + self.dispose() + } + subscribe = false + } + + if subscribe { + do { + return try self.performMap(element) + } catch { + self.forwardOn(.error(error)) + self.dispose() + } + } + + return nil + } + } + + func on(_ event: Event) { + switch event { + case .next(let element): + if let sequence = self.nextElementArrived(element: element) { + self.subscribe(sequence, group: self.group) + } + case .error(let error): + self.lock.performLocked { + self.forwardOn(.error(error)) + self.dispose() + } + case .completed: + self.lock.performLocked { + if self.activeCount == 0 { + self.forwardOn(.completed) + self.dispose() + } + else { + self.sourceSubscription.dispose() + } + + self.stopped = true + } + } + } +} + +final private class MergeLimited: Producer { + private let source: Observable + private let maxConcurrent: Int + + init(source: Observable, maxConcurrent: Int) { + self.source = source + self.maxConcurrent = maxConcurrent + } + + override func run(_ observer: Observer, cancel: Cancelable) -> (sink: Disposable, subscription: Disposable) where Observer.Element == SourceSequence.Element { + let sink = MergeLimitedBasicSink(maxConcurrent: self.maxConcurrent, observer: observer, cancel: cancel) + let subscription = sink.run(self.source) + return (sink: sink, subscription: subscription) + } +} + +// MARK: Merge + +private final class MergeBasicSink : MergeSink where Observer.Element == Source.Element { + override func performMap(_ element: Source) throws -> Source { + element + } +} + +// MARK: flatMap + +private final class FlatMapSink : MergeSink where Observer.Element == SourceSequence.Element { + typealias Selector = (SourceElement) throws -> SourceSequence + + private let selector: Selector + + init(selector: @escaping Selector, observer: Observer, cancel: Cancelable) { + self.selector = selector + super.init(observer: observer, cancel: cancel) + } + + override func performMap(_ element: SourceElement) throws -> SourceSequence { + try self.selector(element) + } +} + +// MARK: FlatMapFirst + +private final class FlatMapFirstSink : MergeSink where Observer.Element == SourceSequence.Element { + typealias Selector = (SourceElement) throws -> SourceSequence + + private let selector: Selector + + override var subscribeNext: Bool { + self.activeCount == 0 + } + + init(selector: @escaping Selector, observer: Observer, cancel: Cancelable) { + self.selector = selector + super.init(observer: observer, cancel: cancel) + } + + override func performMap(_ element: SourceElement) throws -> SourceSequence { + try self.selector(element) + } +} + +private final class MergeSinkIter : ObserverType where Observer.Element == SourceSequence.Element { + typealias Parent = MergeSink + typealias DisposeKey = CompositeDisposable.DisposeKey + typealias Element = Observer.Element + + private let parent: Parent + private let disposeKey: DisposeKey + + init(parent: Parent, disposeKey: DisposeKey) { + self.parent = parent + self.disposeKey = disposeKey + } + + func on(_ event: Event) { + self.parent.lock.performLocked { + switch event { + case .next(let value): + self.parent.forwardOn(.next(value)) + case .error(let error): + self.parent.forwardOn(.error(error)) + self.parent.dispose() + case .completed: + self.parent.group.remove(for: self.disposeKey) + self.parent.activeCount -= 1 + self.parent.checkCompleted() + } + } + } +} + + +private class MergeSink + : Sink + , ObserverType where Observer.Element == SourceSequence.Element { + typealias ResultType = Observer.Element + typealias Element = SourceElement + + let lock = RecursiveLock() + + var subscribeNext: Bool { + true + } + + // state + let group = CompositeDisposable() + let sourceSubscription = SingleAssignmentDisposable() + + var activeCount = 0 + var stopped = false + + override init(observer: Observer, cancel: Cancelable) { + super.init(observer: observer, cancel: cancel) + } + + func performMap(_ element: SourceElement) throws -> SourceSequence { + rxAbstractMethod() + } + + @inline(__always) + final private func nextElementArrived(element: SourceElement) -> SourceSequence? { + self.lock.performLocked { + if !self.subscribeNext { + return nil + } + + do { + let value = try self.performMap(element) + self.activeCount += 1 + return value + } + catch let e { + self.forwardOn(.error(e)) + self.dispose() + return nil + } + } + } + + func on(_ event: Event) { + switch event { + case .next(let element): + if let value = self.nextElementArrived(element: element) { + self.subscribeInner(value.asObservable()) + } + case .error(let error): + self.lock.performLocked { + self.forwardOn(.error(error)) + self.dispose() + } + case .completed: + self.lock.performLocked { + self.stopped = true + self.sourceSubscription.dispose() + self.checkCompleted() + } + } + } + + func subscribeInner(_ source: Observable) { + let iterDisposable = SingleAssignmentDisposable() + if let disposeKey = self.group.insert(iterDisposable) { + let iter = MergeSinkIter(parent: self, disposeKey: disposeKey) + let subscription = source.subscribe(iter) + iterDisposable.setDisposable(subscription) + } + } + + func run(_ sources: [Observable]) -> Disposable { + self.activeCount += sources.count + + for source in sources { + self.subscribeInner(source) + } + + self.stopped = true + + self.checkCompleted() + + return self.group + } + + @inline(__always) + func checkCompleted() { + if self.stopped && self.activeCount == 0 { + self.forwardOn(.completed) + self.dispose() + } + } + + func run(_ source: Observable) -> Disposable { + _ = self.group.insert(self.sourceSubscription) + + let subscription = source.subscribe(self) + self.sourceSubscription.setDisposable(subscription) + + return self.group + } +} + +// MARK: Producers + +final private class FlatMap: Producer { + typealias Selector = (SourceElement) throws -> SourceSequence + + private let source: Observable + + private let selector: Selector + + init(source: Observable, selector: @escaping Selector) { + self.source = source + self.selector = selector + } + + override func run(_ observer: Observer, cancel: Cancelable) -> (sink: Disposable, subscription: Disposable) where Observer.Element == SourceSequence.Element { + let sink = FlatMapSink(selector: self.selector, observer: observer, cancel: cancel) + let subscription = sink.run(self.source) + return (sink: sink, subscription: subscription) + } +} + +final private class FlatMapFirst: Producer { + typealias Selector = (SourceElement) throws -> SourceSequence + + private let source: Observable + + private let selector: Selector + + init(source: Observable, selector: @escaping Selector) { + self.source = source + self.selector = selector + } + + override func run(_ observer: Observer, cancel: Cancelable) -> (sink: Disposable, subscription: Disposable) where Observer.Element == SourceSequence.Element { + let sink = FlatMapFirstSink(selector: self.selector, observer: observer, cancel: cancel) + let subscription = sink.run(self.source) + return (sink: sink, subscription: subscription) + } +} + +final class ConcatMap: Producer { + typealias Selector = (SourceElement) throws -> SourceSequence + + private let source: Observable + private let selector: Selector + + init(source: Observable, selector: @escaping Selector) { + self.source = source + self.selector = selector + } + + override func run(_ observer: Observer, cancel: Cancelable) -> (sink: Disposable, subscription: Disposable) where Observer.Element == SourceSequence.Element { + let sink = ConcatMapSink(selector: self.selector, observer: observer, cancel: cancel) + let subscription = sink.run(self.source) + return (sink: sink, subscription: subscription) + } +} + +final class Merge : Producer { + private let source: Observable + + init(source: Observable) { + self.source = source + } + + override func run(_ observer: Observer, cancel: Cancelable) -> (sink: Disposable, subscription: Disposable) where Observer.Element == SourceSequence.Element { + let sink = MergeBasicSink(observer: observer, cancel: cancel) + let subscription = sink.run(self.source) + return (sink: sink, subscription: subscription) + } +} + +final private class MergeArray: Producer { + private let sources: [Observable] + + init(sources: [Observable]) { + self.sources = sources + } + + override func run(_ observer: Observer, cancel: Cancelable) -> (sink: Disposable, subscription: Disposable) where Observer.Element == Element { + let sink = MergeBasicSink, Observer>(observer: observer, cancel: cancel) + let subscription = sink.run(self.sources) + return (sink: sink, subscription: subscription) + } +} diff --git a/Pods/RxSwift/RxSwift/Observables/Multicast.swift b/Pods/RxSwift/RxSwift/Observables/Multicast.swift new file mode 100644 index 0000000..1ebcf02 --- /dev/null +++ b/Pods/RxSwift/RxSwift/Observables/Multicast.swift @@ -0,0 +1,405 @@ +// +// Multicast.swift +// RxSwift +// +// Created by Krunoslav Zaher on 2/27/15. +// Copyright © 2015 Krunoslav Zaher. All rights reserved. +// + +/** + Represents an observable wrapper that can be connected and disconnected from its underlying observable sequence. + */ +public class ConnectableObservable + : Observable + , ConnectableObservableType { + + /** + Connects the observable wrapper to its source. All subscribed observers will receive values from the underlying observable sequence as long as the connection is established. + + - returns: Disposable used to disconnect the observable wrapper from its source, causing subscribed observer to stop receiving values from the underlying observable sequence. + */ + public func connect() -> Disposable { + rxAbstractMethod() + } +} + +extension ObservableType { + + /** + Multicasts the source sequence notifications through an instantiated subject into all uses of the sequence within a selector function. + + Each subscription to the resulting sequence causes a separate multicast invocation, exposing the sequence resulting from the selector function's invocation. + + For specializations with fixed subject types, see `publish` and `replay`. + + - seealso: [multicast operator on reactivex.io](http://reactivex.io/documentation/operators/publish.html) + + - parameter subjectSelector: Factory function to create an intermediate subject through which the source sequence's elements will be multicast to the selector function. + - parameter selector: Selector function which can use the multicasted source sequence subject to the policies enforced by the created subject. + - returns: An observable sequence that contains the elements of a sequence produced by multicasting the source sequence within a selector function. + */ + public func multicast(_ subjectSelector: @escaping () throws -> Subject, selector: @escaping (Observable) throws -> Observable) + -> Observable where Subject.Observer.Element == Element { + return Multicast( + source: self.asObservable(), + subjectSelector: subjectSelector, + selector: selector + ) + } +} + +extension ObservableType { + + /** + Returns a connectable observable sequence that shares a single subscription to the underlying sequence. + + This operator is a specialization of `multicast` using a `PublishSubject`. + + - seealso: [publish operator on reactivex.io](http://reactivex.io/documentation/operators/publish.html) + + - returns: A connectable observable sequence that shares a single subscription to the underlying sequence. + */ + public func publish() -> ConnectableObservable { + self.multicast { PublishSubject() } + } +} + +extension ObservableType { + + /** + Returns a connectable observable sequence that shares a single subscription to the underlying sequence replaying bufferSize elements. + + This operator is a specialization of `multicast` using a `ReplaySubject`. + + - seealso: [replay operator on reactivex.io](http://reactivex.io/documentation/operators/replay.html) + + - parameter bufferSize: Maximum element count of the replay buffer. + - returns: A connectable observable sequence that shares a single subscription to the underlying sequence. + */ + public func replay(_ bufferSize: Int) + -> ConnectableObservable { + self.multicast { ReplaySubject.create(bufferSize: bufferSize) } + } + + /** + Returns a connectable observable sequence that shares a single subscription to the underlying sequence replaying all elements. + + This operator is a specialization of `multicast` using a `ReplaySubject`. + + - seealso: [replay operator on reactivex.io](http://reactivex.io/documentation/operators/replay.html) + + - returns: A connectable observable sequence that shares a single subscription to the underlying sequence. + */ + public func replayAll() + -> ConnectableObservable { + self.multicast { ReplaySubject.createUnbounded() } + } +} + +extension ConnectableObservableType { + + /** + Returns an observable sequence that stays connected to the source as long as there is at least one subscription to the observable sequence. + + - seealso: [refCount operator on reactivex.io](http://reactivex.io/documentation/operators/refcount.html) + + - returns: An observable sequence that stays connected to the source as long as there is at least one subscription to the observable sequence. + */ + public func refCount() -> Observable { + RefCount(source: self) + } +} + +extension ObservableType { + + /** + Multicasts the source sequence notifications through the specified subject to the resulting connectable observable. + + Upon connection of the connectable observable, the subject is subscribed to the source exactly one, and messages are forwarded to the observers registered with the connectable observable. + + For specializations with fixed subject types, see `publish` and `replay`. + + - seealso: [multicast operator on reactivex.io](http://reactivex.io/documentation/operators/publish.html) + + - parameter subject: Subject to push source elements into. + - returns: A connectable observable sequence that upon connection causes the source sequence to push results into the specified subject. + */ + public func multicast(_ subject: Subject) + -> ConnectableObservable where Subject.Observer.Element == Element { + ConnectableObservableAdapter(source: self.asObservable(), makeSubject: { subject }) + } + + /** + Multicasts the source sequence notifications through an instantiated subject to the resulting connectable observable. + + Upon connection of the connectable observable, the subject is subscribed to the source exactly one, and messages are forwarded to the observers registered with the connectable observable. + + Subject is cleared on connection disposal or in case source sequence produces terminal event. + + - seealso: [multicast operator on reactivex.io](http://reactivex.io/documentation/operators/publish.html) + + - parameter makeSubject: Factory function used to instantiate a subject for each connection. + - returns: A connectable observable sequence that upon connection causes the source sequence to push results into the specified subject. + */ + public func multicast(makeSubject: @escaping () -> Subject) + -> ConnectableObservable where Subject.Observer.Element == Element { + ConnectableObservableAdapter(source: self.asObservable(), makeSubject: makeSubject) + } +} + +final private class Connection: ObserverType, Disposable { + typealias Element = Subject.Observer.Element + + private var lock: RecursiveLock + // state + private var parent: ConnectableObservableAdapter? + private var subscription : Disposable? + private var subjectObserver: Subject.Observer + + private let disposed = AtomicInt(0) + + init(parent: ConnectableObservableAdapter, subjectObserver: Subject.Observer, lock: RecursiveLock, subscription: Disposable) { + self.parent = parent + self.subscription = subscription + self.lock = lock + self.subjectObserver = subjectObserver + } + + func on(_ event: Event) { + if isFlagSet(self.disposed, 1) { + return + } + if event.isStopEvent { + self.dispose() + } + self.subjectObserver.on(event) + } + + func dispose() { + lock.lock(); defer { lock.unlock() } + fetchOr(self.disposed, 1) + guard let parent = self.parent else { + return + } + + if parent.connection === self { + parent.connection = nil + parent.subject = nil + } + self.parent = nil + + self.subscription?.dispose() + self.subscription = nil + } +} + +final private class ConnectableObservableAdapter + : ConnectableObservable { + typealias ConnectionType = Connection + + private let source: Observable + private let makeSubject: () -> Subject + + fileprivate let lock = RecursiveLock() + fileprivate var subject: Subject? + + // state + fileprivate var connection: ConnectionType? + + init(source: Observable, makeSubject: @escaping () -> Subject) { + self.source = source + self.makeSubject = makeSubject + self.subject = nil + self.connection = nil + } + + override func connect() -> Disposable { + return self.lock.performLocked { + if let connection = self.connection { + return connection + } + + let singleAssignmentDisposable = SingleAssignmentDisposable() + let connection = Connection(parent: self, subjectObserver: self.lazySubject.asObserver(), lock: self.lock, subscription: singleAssignmentDisposable) + self.connection = connection + let subscription = self.source.subscribe(connection) + singleAssignmentDisposable.setDisposable(subscription) + return connection + } + } + + private var lazySubject: Subject { + if let subject = self.subject { + return subject + } + + let subject = self.makeSubject() + self.subject = subject + return subject + } + + override func subscribe(_ observer: Observer) -> Disposable where Observer.Element == Subject.Element { + self.lazySubject.subscribe(observer) + } +} + +final private class RefCountSink + : Sink + , ObserverType where ConnectableSource.Element == Observer.Element { + typealias Element = Observer.Element + typealias Parent = RefCount + + private let parent: Parent + + private var connectionIdSnapshot: Int64 = -1 + + init(parent: Parent, observer: Observer, cancel: Cancelable) { + self.parent = parent + super.init(observer: observer, cancel: cancel) + } + + func run() -> Disposable { + let subscription = self.parent.source.subscribe(self) + self.parent.lock.lock(); defer { self.parent.lock.unlock() } + + self.connectionIdSnapshot = self.parent.connectionId + + if self.isDisposed { + return Disposables.create() + } + + if self.parent.count == 0 { + self.parent.count = 1 + self.parent.connectableSubscription = self.parent.source.connect() + } + else { + self.parent.count += 1 + } + + return Disposables.create { + subscription.dispose() + self.parent.lock.lock(); defer { self.parent.lock.unlock() } + if self.parent.connectionId != self.connectionIdSnapshot { + return + } + if self.parent.count == 1 { + self.parent.count = 0 + guard let connectableSubscription = self.parent.connectableSubscription else { + return + } + + connectableSubscription.dispose() + self.parent.connectableSubscription = nil + } + else if self.parent.count > 1 { + self.parent.count -= 1 + } + else { + rxFatalError("Something went wrong with RefCount disposing mechanism") + } + } + } + + func on(_ event: Event) { + switch event { + case .next: + self.forwardOn(event) + case .error, .completed: + self.parent.lock.lock() + if self.parent.connectionId == self.connectionIdSnapshot { + let connection = self.parent.connectableSubscription + defer { connection?.dispose() } + self.parent.count = 0 + self.parent.connectionId = self.parent.connectionId &+ 1 + self.parent.connectableSubscription = nil + } + self.parent.lock.unlock() + self.forwardOn(event) + self.dispose() + } + } +} + +final private class RefCount: Producer { + fileprivate let lock = RecursiveLock() + + // state + fileprivate var count = 0 + fileprivate var connectionId: Int64 = 0 + fileprivate var connectableSubscription = nil as Disposable? + + fileprivate let source: ConnectableSource + + init(source: ConnectableSource) { + self.source = source + } + + override func run(_ observer: Observer, cancel: Cancelable) -> (sink: Disposable, subscription: Disposable) + where Observer.Element == ConnectableSource.Element { + let sink = RefCountSink(parent: self, observer: observer, cancel: cancel) + let subscription = sink.run() + return (sink: sink, subscription: subscription) + } +} + +final private class MulticastSink: Sink, ObserverType { + typealias Element = Observer.Element + typealias ResultType = Element + typealias MutlicastType = Multicast + + private let parent: MutlicastType + + init(parent: MutlicastType, observer: Observer, cancel: Cancelable) { + self.parent = parent + super.init(observer: observer, cancel: cancel) + } + + func run() -> Disposable { + do { + let subject = try self.parent.subjectSelector() + let connectable = ConnectableObservableAdapter(source: self.parent.source, makeSubject: { subject }) + + let observable = try self.parent.selector(connectable) + + let subscription = observable.subscribe(self) + let connection = connectable.connect() + + return Disposables.create(subscription, connection) + } + catch let e { + self.forwardOn(.error(e)) + self.dispose() + return Disposables.create() + } + } + + func on(_ event: Event) { + self.forwardOn(event) + switch event { + case .next: break + case .error, .completed: + self.dispose() + } + } +} + +final private class Multicast: Producer { + typealias SubjectSelectorType = () throws -> Subject + typealias SelectorType = (Observable) throws -> Observable + + fileprivate let source: Observable + fileprivate let subjectSelector: SubjectSelectorType + fileprivate let selector: SelectorType + + init(source: Observable, subjectSelector: @escaping SubjectSelectorType, selector: @escaping SelectorType) { + self.source = source + self.subjectSelector = subjectSelector + self.selector = selector + } + + override func run(_ observer: Observer, cancel: Cancelable) -> (sink: Disposable, subscription: Disposable) where Observer.Element == Result { + let sink = MulticastSink(parent: self, observer: observer, cancel: cancel) + let subscription = sink.run() + return (sink: sink, subscription: subscription) + } +} diff --git a/Pods/RxSwift/RxSwift/Observables/Never.swift b/Pods/RxSwift/RxSwift/Observables/Never.swift new file mode 100644 index 0000000..7b456ee --- /dev/null +++ b/Pods/RxSwift/RxSwift/Observables/Never.swift @@ -0,0 +1,27 @@ +// +// Never.swift +// RxSwift +// +// Created by Krunoslav Zaher on 8/30/15. +// Copyright © 2015 Krunoslav Zaher. All rights reserved. +// + +extension ObservableType { + + /** + Returns a non-terminating observable sequence, which can be used to denote an infinite duration. + + - seealso: [never operator on reactivex.io](http://reactivex.io/documentation/operators/empty-never-throw.html) + + - returns: An observable sequence whose observers will never get called. + */ + public static func never() -> Observable { + NeverProducer() + } +} + +final private class NeverProducer: Producer { + override func subscribe(_ observer: Observer) -> Disposable where Observer.Element == Element { + Disposables.create() + } +} diff --git a/Pods/RxSwift/RxSwift/Observables/ObserveOn.swift b/Pods/RxSwift/RxSwift/Observables/ObserveOn.swift new file mode 100644 index 0000000..6b8689e --- /dev/null +++ b/Pods/RxSwift/RxSwift/Observables/ObserveOn.swift @@ -0,0 +1,243 @@ +// +// ObserveOn.swift +// RxSwift +// +// Created by Krunoslav Zaher on 7/25/15. +// Copyright © 2015 Krunoslav Zaher. All rights reserved. +// + +extension ObservableType { + /** + Wraps the source sequence in order to run its observer callbacks on the specified scheduler. + + This only invokes observer callbacks on a `scheduler`. In case the subscription and/or unsubscription + actions have side-effects that require to be run on a scheduler, use `subscribeOn`. + + - seealso: [observeOn operator on reactivex.io](http://reactivex.io/documentation/operators/observeon.html) + + - parameter scheduler: Scheduler to notify observers on. + - returns: The source sequence whose observations happen on the specified scheduler. + */ + public func observe(on scheduler: ImmediateSchedulerType) + -> Observable { + guard let serialScheduler = scheduler as? SerialDispatchQueueScheduler else { + return ObserveOn(source: self.asObservable(), scheduler: scheduler) + } + + return ObserveOnSerialDispatchQueue(source: self.asObservable(), + scheduler: serialScheduler) + } + + /** + Wraps the source sequence in order to run its observer callbacks on the specified scheduler. + + This only invokes observer callbacks on a `scheduler`. In case the subscription and/or unsubscription + actions have side-effects that require to be run on a scheduler, use `subscribeOn`. + + - seealso: [observeOn operator on reactivex.io](http://reactivex.io/documentation/operators/observeon.html) + + - parameter scheduler: Scheduler to notify observers on. + - returns: The source sequence whose observations happen on the specified scheduler. + */ + @available(*, deprecated, renamed: "observe(on:)") + public func observeOn(_ scheduler: ImmediateSchedulerType) + -> Observable { + observe(on: scheduler) + } +} + +final private class ObserveOn: Producer { + let scheduler: ImmediateSchedulerType + let source: Observable + + init(source: Observable, scheduler: ImmediateSchedulerType) { + self.scheduler = scheduler + self.source = source + +#if TRACE_RESOURCES + _ = Resources.incrementTotal() +#endif + } + + override func run(_ observer: Observer, cancel: Cancelable) -> (sink: Disposable, subscription: Disposable) where Observer.Element == Element { + let sink = ObserveOnSink(scheduler: self.scheduler, observer: observer, cancel: cancel) + let subscription = self.source.subscribe(sink) + return (sink: sink, subscription: subscription) + } + +#if TRACE_RESOURCES + deinit { + _ = Resources.decrementTotal() + } +#endif +} + +enum ObserveOnState : Int32 { + // pump is not running + case stopped = 0 + // pump is running + case running = 1 +} + +final private class ObserveOnSink: ObserverBase { + typealias Element = Observer.Element + + let scheduler: ImmediateSchedulerType + + var lock = SpinLock() + let observer: Observer + + // state + var state = ObserveOnState.stopped + var queue = Queue>(capacity: 10) + + let scheduleDisposable = SerialDisposable() + let cancel: Cancelable + + init(scheduler: ImmediateSchedulerType, observer: Observer, cancel: Cancelable) { + self.scheduler = scheduler + self.observer = observer + self.cancel = cancel + } + + override func onCore(_ event: Event) { + let shouldStart = self.lock.performLocked { () -> Bool in + self.queue.enqueue(event) + + switch self.state { + case .stopped: + self.state = .running + return true + case .running: + return false + } + } + + if shouldStart { + self.scheduleDisposable.disposable = self.scheduler.scheduleRecursive((), action: self.run) + } + } + + func run(_ state: (), _ recurse: (()) -> Void) { + let (nextEvent, observer) = self.lock.performLocked { () -> (Event?, Observer) in + if !self.queue.isEmpty { + return (self.queue.dequeue(), self.observer) + } + else { + self.state = .stopped + return (nil, self.observer) + } + } + + if let nextEvent = nextEvent, !self.cancel.isDisposed { + observer.on(nextEvent) + if nextEvent.isStopEvent { + self.dispose() + } + } + else { + return + } + + let shouldContinue = self.shouldContinue_synchronized() + + if shouldContinue { + recurse(()) + } + } + + func shouldContinue_synchronized() -> Bool { + self.lock.performLocked { + let isEmpty = self.queue.isEmpty + if isEmpty { self.state = .stopped } + return !isEmpty + } + } + + override func dispose() { + super.dispose() + + self.cancel.dispose() + self.scheduleDisposable.dispose() + } +} + +#if TRACE_RESOURCES + private let numberOfSerialDispatchObservables = AtomicInt(0) + extension Resources { + /** + Counts number of `SerialDispatchQueueObservables`. + + Purposed for unit tests. + */ + public static var numberOfSerialDispatchQueueObservables: Int32 { + return load(numberOfSerialDispatchObservables) + } + } +#endif + +final private class ObserveOnSerialDispatchQueueSink: ObserverBase { + let scheduler: SerialDispatchQueueScheduler + let observer: Observer + + let cancel: Cancelable + + var cachedScheduleLambda: (((sink: ObserveOnSerialDispatchQueueSink, event: Event)) -> Disposable)! + + init(scheduler: SerialDispatchQueueScheduler, observer: Observer, cancel: Cancelable) { + self.scheduler = scheduler + self.observer = observer + self.cancel = cancel + super.init() + + self.cachedScheduleLambda = { pair in + guard !cancel.isDisposed else { return Disposables.create() } + + pair.sink.observer.on(pair.event) + + if pair.event.isStopEvent { + pair.sink.dispose() + } + + return Disposables.create() + } + } + + override func onCore(_ event: Event) { + _ = self.scheduler.schedule((self, event), action: self.cachedScheduleLambda!) + } + + override func dispose() { + super.dispose() + + self.cancel.dispose() + } +} + +final private class ObserveOnSerialDispatchQueue: Producer { + let scheduler: SerialDispatchQueueScheduler + let source: Observable + + init(source: Observable, scheduler: SerialDispatchQueueScheduler) { + self.scheduler = scheduler + self.source = source + + #if TRACE_RESOURCES + _ = Resources.incrementTotal() + _ = increment(numberOfSerialDispatchObservables) + #endif + } + + override func run(_ observer: Observer, cancel: Cancelable) -> (sink: Disposable, subscription: Disposable) where Observer.Element == Element { + let sink = ObserveOnSerialDispatchQueueSink(scheduler: self.scheduler, observer: observer, cancel: cancel) + let subscription = self.source.subscribe(sink) + return (sink: sink, subscription: subscription) + } + + #if TRACE_RESOURCES + deinit { + _ = Resources.decrementTotal() + _ = decrement(numberOfSerialDispatchObservables) + } + #endif +} diff --git a/Pods/RxSwift/RxSwift/Observables/Optional.swift b/Pods/RxSwift/RxSwift/Observables/Optional.swift new file mode 100644 index 0000000..64f8f1f --- /dev/null +++ b/Pods/RxSwift/RxSwift/Observables/Optional.swift @@ -0,0 +1,95 @@ +// +// Optional.swift +// RxSwift +// +// Created by tarunon on 2016/12/13. +// Copyright © 2016 Krunoslav Zaher. All rights reserved. +// + +extension ObservableType { + /** + Converts a optional to an observable sequence. + + - seealso: [from operator on reactivex.io](http://reactivex.io/documentation/operators/from.html) + + - parameter optional: Optional element in the resulting observable sequence. + - returns: An observable sequence containing the wrapped value or not from given optional. + */ + public static func from(optional: Element?) -> Observable { + ObservableOptional(optional: optional) + } + + /** + Converts a optional to an observable sequence. + + - seealso: [from operator on reactivex.io](http://reactivex.io/documentation/operators/from.html) + + - parameter optional: Optional element in the resulting observable sequence. + - parameter scheduler: Scheduler to send the optional element on. + - returns: An observable sequence containing the wrapped value or not from given optional. + */ + public static func from(optional: Element?, scheduler: ImmediateSchedulerType) -> Observable { + ObservableOptionalScheduled(optional: optional, scheduler: scheduler) + } +} + +final private class ObservableOptionalScheduledSink: Sink { + typealias Element = Observer.Element + typealias Parent = ObservableOptionalScheduled + + private let parent: Parent + + init(parent: Parent, observer: Observer, cancel: Cancelable) { + self.parent = parent + super.init(observer: observer, cancel: cancel) + } + + func run() -> Disposable { + return self.parent.scheduler.schedule(self.parent.optional) { (optional: Element?) -> Disposable in + if let next = optional { + self.forwardOn(.next(next)) + return self.parent.scheduler.schedule(()) { _ in + self.forwardOn(.completed) + self.dispose() + return Disposables.create() + } + } else { + self.forwardOn(.completed) + self.dispose() + return Disposables.create() + } + } + } +} + +final private class ObservableOptionalScheduled: Producer { + fileprivate let optional: Element? + fileprivate let scheduler: ImmediateSchedulerType + + init(optional: Element?, scheduler: ImmediateSchedulerType) { + self.optional = optional + self.scheduler = scheduler + } + + override func run(_ observer: Observer, cancel: Cancelable) -> (sink: Disposable, subscription: Disposable) where Observer.Element == Element { + let sink = ObservableOptionalScheduledSink(parent: self, observer: observer, cancel: cancel) + let subscription = sink.run() + return (sink: sink, subscription: subscription) + } +} + +final private class ObservableOptional: Producer { + private let optional: Element? + + init(optional: Element?) { + self.optional = optional + } + + override func subscribe(_ observer: Observer) -> Disposable where Observer.Element == Element { + if let element = self.optional { + observer.on(.next(element)) + } + observer.on(.completed) + return Disposables.create() + } +} diff --git a/Pods/RxSwift/RxSwift/Observables/Producer.swift b/Pods/RxSwift/RxSwift/Observables/Producer.swift new file mode 100644 index 0000000..e611930 --- /dev/null +++ b/Pods/RxSwift/RxSwift/Observables/Producer.swift @@ -0,0 +1,92 @@ +// +// Producer.swift +// RxSwift +// +// Created by Krunoslav Zaher on 2/20/15. +// Copyright © 2015 Krunoslav Zaher. All rights reserved. +// + +class Producer: Observable { + override init() { + super.init() + } + + override func subscribe(_ observer: Observer) -> Disposable where Observer.Element == Element { + if !CurrentThreadScheduler.isScheduleRequired { + // The returned disposable needs to release all references once it was disposed. + let disposer = SinkDisposer() + let sinkAndSubscription = self.run(observer, cancel: disposer) + disposer.setSinkAndSubscription(sink: sinkAndSubscription.sink, subscription: sinkAndSubscription.subscription) + + return disposer + } + else { + return CurrentThreadScheduler.instance.schedule(()) { _ in + let disposer = SinkDisposer() + let sinkAndSubscription = self.run(observer, cancel: disposer) + disposer.setSinkAndSubscription(sink: sinkAndSubscription.sink, subscription: sinkAndSubscription.subscription) + + return disposer + } + } + } + + func run(_ observer: Observer, cancel: Cancelable) -> (sink: Disposable, subscription: Disposable) where Observer.Element == Element { + rxAbstractMethod() + } +} + +private final class SinkDisposer: Cancelable { + private enum DisposeState: Int32 { + case disposed = 1 + case sinkAndSubscriptionSet = 2 + } + + private let state = AtomicInt(0) + private var sink: Disposable? + private var subscription: Disposable? + + var isDisposed: Bool { + isFlagSet(self.state, DisposeState.disposed.rawValue) + } + + func setSinkAndSubscription(sink: Disposable, subscription: Disposable) { + self.sink = sink + self.subscription = subscription + + let previousState = fetchOr(self.state, DisposeState.sinkAndSubscriptionSet.rawValue) + if (previousState & DisposeState.sinkAndSubscriptionSet.rawValue) != 0 { + rxFatalError("Sink and subscription were already set") + } + + if (previousState & DisposeState.disposed.rawValue) != 0 { + sink.dispose() + subscription.dispose() + self.sink = nil + self.subscription = nil + } + } + + func dispose() { + let previousState = fetchOr(self.state, DisposeState.disposed.rawValue) + + if (previousState & DisposeState.disposed.rawValue) != 0 { + return + } + + if (previousState & DisposeState.sinkAndSubscriptionSet.rawValue) != 0 { + guard let sink = self.sink else { + rxFatalError("Sink not set") + } + guard let subscription = self.subscription else { + rxFatalError("Subscription not set") + } + + sink.dispose() + subscription.dispose() + + self.sink = nil + self.subscription = nil + } + } +} diff --git a/Pods/RxSwift/RxSwift/Observables/Range.swift b/Pods/RxSwift/RxSwift/Observables/Range.swift new file mode 100644 index 0000000..2453532 --- /dev/null +++ b/Pods/RxSwift/RxSwift/Observables/Range.swift @@ -0,0 +1,73 @@ +// +// Range.swift +// RxSwift +// +// Created by Krunoslav Zaher on 9/13/15. +// Copyright © 2015 Krunoslav Zaher. All rights reserved. +// + +extension ObservableType where Element: RxAbstractInteger { + /** + Generates an observable sequence of integral numbers within a specified range, using the specified scheduler to generate and send out observer messages. + + - seealso: [range operator on reactivex.io](http://reactivex.io/documentation/operators/range.html) + + - parameter start: The value of the first integer in the sequence. + - parameter count: The number of sequential integers to generate. + - parameter scheduler: Scheduler to run the generator loop on. + - returns: An observable sequence that contains a range of sequential integral numbers. + */ + public static func range(start: Element, count: Element, scheduler: ImmediateSchedulerType = CurrentThreadScheduler.instance) -> Observable { + RangeProducer(start: start, count: count, scheduler: scheduler) + } +} + +final private class RangeProducer: Producer { + fileprivate let start: Element + fileprivate let count: Element + fileprivate let scheduler: ImmediateSchedulerType + + init(start: Element, count: Element, scheduler: ImmediateSchedulerType) { + guard count >= 0 else { + rxFatalError("count can't be negative") + } + + guard start &+ (count - 1) >= start || count == 0 else { + rxFatalError("overflow of count") + } + + self.start = start + self.count = count + self.scheduler = scheduler + } + + override func run(_ observer: Observer, cancel: Cancelable) -> (sink: Disposable, subscription: Disposable) where Observer.Element == Element { + let sink = RangeSink(parent: self, observer: observer, cancel: cancel) + let subscription = sink.run() + return (sink: sink, subscription: subscription) + } +} + +final private class RangeSink: Sink where Observer.Element: RxAbstractInteger { + typealias Parent = RangeProducer + + private let parent: Parent + + init(parent: Parent, observer: Observer, cancel: Cancelable) { + self.parent = parent + super.init(observer: observer, cancel: cancel) + } + + func run() -> Disposable { + return self.parent.scheduler.scheduleRecursive(0 as Observer.Element) { i, recurse in + if i < self.parent.count { + self.forwardOn(.next(self.parent.start + i)) + recurse(i + 1) + } + else { + self.forwardOn(.completed) + self.dispose() + } + } + } +} diff --git a/Pods/RxSwift/RxSwift/Observables/Reduce.swift b/Pods/RxSwift/RxSwift/Observables/Reduce.swift new file mode 100644 index 0000000..d5fab34 --- /dev/null +++ b/Pods/RxSwift/RxSwift/Observables/Reduce.swift @@ -0,0 +1,109 @@ +// +// Reduce.swift +// RxSwift +// +// Created by Krunoslav Zaher on 4/1/15. +// Copyright © 2015 Krunoslav Zaher. All rights reserved. +// + + +extension ObservableType { + /** + Applies an `accumulator` function over an observable sequence, returning the result of the aggregation as a single element in the result sequence. The specified `seed` value is used as the initial accumulator value. + + For aggregation behavior with incremental intermediate results, see `scan`. + + - seealso: [reduce operator on reactivex.io](http://reactivex.io/documentation/operators/reduce.html) + + - parameter seed: The initial accumulator value. + - parameter accumulator: A accumulator function to be invoked on each element. + - parameter mapResult: A function to transform the final accumulator value into the result value. + - returns: An observable sequence containing a single element with the final accumulator value. + */ + public func reduce(_ seed: A, accumulator: @escaping (A, Element) throws -> A, mapResult: @escaping (A) throws -> Result) + -> Observable { + Reduce(source: self.asObservable(), seed: seed, accumulator: accumulator, mapResult: mapResult) + } + + /** + Applies an `accumulator` function over an observable sequence, returning the result of the aggregation as a single element in the result sequence. The specified `seed` value is used as the initial accumulator value. + + For aggregation behavior with incremental intermediate results, see `scan`. + + - seealso: [reduce operator on reactivex.io](http://reactivex.io/documentation/operators/reduce.html) + + - parameter seed: The initial accumulator value. + - parameter accumulator: A accumulator function to be invoked on each element. + - returns: An observable sequence containing a single element with the final accumulator value. + */ + public func reduce(_ seed: A, accumulator: @escaping (A, Element) throws -> A) + -> Observable { + Reduce(source: self.asObservable(), seed: seed, accumulator: accumulator, mapResult: { $0 }) + } +} + +final private class ReduceSink: Sink, ObserverType { + typealias ResultType = Observer.Element + typealias Parent = Reduce + + private let parent: Parent + private var accumulation: AccumulateType + + init(parent: Parent, observer: Observer, cancel: Cancelable) { + self.parent = parent + self.accumulation = parent.seed + + super.init(observer: observer, cancel: cancel) + } + + func on(_ event: Event) { + switch event { + case .next(let value): + do { + self.accumulation = try self.parent.accumulator(self.accumulation, value) + } + catch let e { + self.forwardOn(.error(e)) + self.dispose() + } + case .error(let e): + self.forwardOn(.error(e)) + self.dispose() + case .completed: + do { + let result = try self.parent.mapResult(self.accumulation) + self.forwardOn(.next(result)) + self.forwardOn(.completed) + self.dispose() + } + catch let e { + self.forwardOn(.error(e)) + self.dispose() + } + } + } +} + +final private class Reduce: Producer { + typealias AccumulatorType = (AccumulateType, SourceType) throws -> AccumulateType + typealias ResultSelectorType = (AccumulateType) throws -> ResultType + + private let source: Observable + fileprivate let seed: AccumulateType + fileprivate let accumulator: AccumulatorType + fileprivate let mapResult: ResultSelectorType + + init(source: Observable, seed: AccumulateType, accumulator: @escaping AccumulatorType, mapResult: @escaping ResultSelectorType) { + self.source = source + self.seed = seed + self.accumulator = accumulator + self.mapResult = mapResult + } + + override func run(_ observer: Observer, cancel: Cancelable) -> (sink: Disposable, subscription: Disposable) where Observer.Element == ResultType { + let sink = ReduceSink(parent: self, observer: observer, cancel: cancel) + let subscription = self.source.subscribe(sink) + return (sink: sink, subscription: subscription) + } +} + diff --git a/Pods/RxSwift/RxSwift/Observables/Repeat.swift b/Pods/RxSwift/RxSwift/Observables/Repeat.swift new file mode 100644 index 0000000..69a3ba0 --- /dev/null +++ b/Pods/RxSwift/RxSwift/Observables/Repeat.swift @@ -0,0 +1,57 @@ +// +// Repeat.swift +// RxSwift +// +// Created by Krunoslav Zaher on 9/13/15. +// Copyright © 2015 Krunoslav Zaher. All rights reserved. +// + +extension ObservableType { + /** + Generates an observable sequence that repeats the given element infinitely, using the specified scheduler to send out observer messages. + + - seealso: [repeat operator on reactivex.io](http://reactivex.io/documentation/operators/repeat.html) + + - parameter element: Element to repeat. + - parameter scheduler: Scheduler to run the producer loop on. + - returns: An observable sequence that repeats the given element infinitely. + */ + public static func repeatElement(_ element: Element, scheduler: ImmediateSchedulerType = CurrentThreadScheduler.instance) -> Observable { + RepeatElement(element: element, scheduler: scheduler) + } +} + +final private class RepeatElement: Producer { + fileprivate let element: Element + fileprivate let scheduler: ImmediateSchedulerType + + init(element: Element, scheduler: ImmediateSchedulerType) { + self.element = element + self.scheduler = scheduler + } + + override func run(_ observer: Observer, cancel: Cancelable) -> (sink: Disposable, subscription: Disposable) where Observer.Element == Element { + let sink = RepeatElementSink(parent: self, observer: observer, cancel: cancel) + let subscription = sink.run() + + return (sink: sink, subscription: subscription) + } +} + +final private class RepeatElementSink: Sink { + typealias Parent = RepeatElement + + private let parent: Parent + + init(parent: Parent, observer: Observer, cancel: Cancelable) { + self.parent = parent + super.init(observer: observer, cancel: cancel) + } + + func run() -> Disposable { + return self.parent.scheduler.scheduleRecursive(self.parent.element) { e, recurse in + self.forwardOn(.next(e)) + recurse(e) + } + } +} diff --git a/Pods/RxSwift/RxSwift/Observables/RetryWhen.swift b/Pods/RxSwift/RxSwift/Observables/RetryWhen.swift new file mode 100644 index 0000000..1b2a6f1 --- /dev/null +++ b/Pods/RxSwift/RxSwift/Observables/RetryWhen.swift @@ -0,0 +1,211 @@ +// +// RetryWhen.swift +// RxSwift +// +// Created by Junior B. on 06/10/15. +// Copyright © 2015 Krunoslav Zaher. All rights reserved. +// + +extension ObservableType { + /** + Repeats the source observable sequence on error when the notifier emits a next value. + If the source observable errors and the notifier completes, it will complete the source sequence. + + - seealso: [retry operator on reactivex.io](http://reactivex.io/documentation/operators/retry.html) + + - parameter notificationHandler: A handler that is passed an observable sequence of errors raised by the source observable and returns and observable that either continues, completes or errors. This behavior is then applied to the source observable. + - returns: An observable sequence producing the elements of the given sequence repeatedly until it terminates successfully or is notified to error or complete. + */ + public func retry(when notificationHandler: @escaping (Observable) -> TriggerObservable) + -> Observable { + RetryWhenSequence(sources: InfiniteSequence(repeatedValue: self.asObservable()), notificationHandler: notificationHandler) + } + + /** + Repeats the source observable sequence on error when the notifier emits a next value. + If the source observable errors and the notifier completes, it will complete the source sequence. + + - seealso: [retry operator on reactivex.io](http://reactivex.io/documentation/operators/retry.html) + + - parameter notificationHandler: A handler that is passed an observable sequence of errors raised by the source observable and returns and observable that either continues, completes or errors. This behavior is then applied to the source observable. + - returns: An observable sequence producing the elements of the given sequence repeatedly until it terminates successfully or is notified to error or complete. + */ + @available(*, deprecated, renamed: "retry(when:)") + public func retryWhen(_ notificationHandler: @escaping (Observable) -> TriggerObservable) + -> Observable { + retry(when: notificationHandler) + } + + /** + Repeats the source observable sequence on error when the notifier emits a next value. + If the source observable errors and the notifier completes, it will complete the source sequence. + + - seealso: [retry operator on reactivex.io](http://reactivex.io/documentation/operators/retry.html) + + - parameter notificationHandler: A handler that is passed an observable sequence of errors raised by the source observable and returns and observable that either continues, completes or errors. This behavior is then applied to the source observable. + - returns: An observable sequence producing the elements of the given sequence repeatedly until it terminates successfully or is notified to error or complete. + */ + public func retry(when notificationHandler: @escaping (Observable) -> TriggerObservable) + -> Observable { + RetryWhenSequence(sources: InfiniteSequence(repeatedValue: self.asObservable()), notificationHandler: notificationHandler) + } + + /** + Repeats the source observable sequence on error when the notifier emits a next value. + If the source observable errors and the notifier completes, it will complete the source sequence. + + - seealso: [retry operator on reactivex.io](http://reactivex.io/documentation/operators/retry.html) + + - parameter notificationHandler: A handler that is passed an observable sequence of errors raised by the source observable and returns and observable that either continues, completes or errors. This behavior is then applied to the source observable. + - returns: An observable sequence producing the elements of the given sequence repeatedly until it terminates successfully or is notified to error or complete. + */ + @available(*, deprecated, renamed: "retry(when:)") + public func retryWhen(_ notificationHandler: @escaping (Observable) -> TriggerObservable) + -> Observable { + RetryWhenSequence(sources: InfiniteSequence(repeatedValue: self.asObservable()), notificationHandler: notificationHandler) + } +} + +final private class RetryTriggerSink + : ObserverType where Sequence.Element: ObservableType, Sequence.Element.Element == Observer.Element { + typealias Element = TriggerObservable.Element + + typealias Parent = RetryWhenSequenceSinkIter + + private let parent: Parent + + init(parent: Parent) { + self.parent = parent + } + + func on(_ event: Event) { + switch event { + case .next: + self.parent.parent.lastError = nil + self.parent.parent.schedule(.moveNext) + case .error(let e): + self.parent.parent.forwardOn(.error(e)) + self.parent.parent.dispose() + case .completed: + self.parent.parent.forwardOn(.completed) + self.parent.parent.dispose() + } + } +} + +final private class RetryWhenSequenceSinkIter + : ObserverType + , Disposable where Sequence.Element: ObservableType, Sequence.Element.Element == Observer.Element { + typealias Element = Observer.Element + typealias Parent = RetryWhenSequenceSink + + fileprivate let parent: Parent + private let errorHandlerSubscription = SingleAssignmentDisposable() + private let subscription: Disposable + + init(parent: Parent, subscription: Disposable) { + self.parent = parent + self.subscription = subscription + } + + func on(_ event: Event) { + switch event { + case .next: + self.parent.forwardOn(event) + case .error(let error): + self.parent.lastError = error + + if let failedWith = error as? Error { + // dispose current subscription + self.subscription.dispose() + + let errorHandlerSubscription = self.parent.notifier.subscribe(RetryTriggerSink(parent: self)) + self.errorHandlerSubscription.setDisposable(errorHandlerSubscription) + self.parent.errorSubject.on(.next(failedWith)) + } + else { + self.parent.forwardOn(.error(error)) + self.parent.dispose() + } + case .completed: + self.parent.forwardOn(event) + self.parent.dispose() + } + } + + final func dispose() { + self.subscription.dispose() + self.errorHandlerSubscription.dispose() + } +} + +final private class RetryWhenSequenceSink + : TailRecursiveSink where Sequence.Element: ObservableType, Sequence.Element.Element == Observer.Element { + typealias Element = Observer.Element + typealias Parent = RetryWhenSequence + + let lock = RecursiveLock() + + private let parent: Parent + + fileprivate var lastError: Swift.Error? + fileprivate let errorSubject = PublishSubject() + private let handler: Observable + fileprivate let notifier = PublishSubject() + + init(parent: Parent, observer: Observer, cancel: Cancelable) { + self.parent = parent + self.handler = parent.notificationHandler(self.errorSubject).asObservable() + super.init(observer: observer, cancel: cancel) + } + + override func done() { + if let lastError = self.lastError { + self.forwardOn(.error(lastError)) + self.lastError = nil + } + else { + self.forwardOn(.completed) + } + + self.dispose() + } + + override func extract(_ observable: Observable) -> SequenceGenerator? { + // It is important to always return `nil` here because there are side effects in the `run` method + // that are dependant on particular `retryWhen` operator so single operator stack can't be reused in this + // case. + return nil + } + + override func subscribeToNext(_ source: Observable) -> Disposable { + let subscription = SingleAssignmentDisposable() + let iter = RetryWhenSequenceSinkIter(parent: self, subscription: subscription) + subscription.setDisposable(source.subscribe(iter)) + return iter + } + + override func run(_ sources: SequenceGenerator) -> Disposable { + let triggerSubscription = self.handler.subscribe(self.notifier.asObserver()) + let superSubscription = super.run(sources) + return Disposables.create(superSubscription, triggerSubscription) + } +} + +final private class RetryWhenSequence: Producer where Sequence.Element: ObservableType { + typealias Element = Sequence.Element.Element + + private let sources: Sequence + fileprivate let notificationHandler: (Observable) -> TriggerObservable + + init(sources: Sequence, notificationHandler: @escaping (Observable) -> TriggerObservable) { + self.sources = sources + self.notificationHandler = notificationHandler + } + + override func run(_ observer: Observer, cancel: Cancelable) -> (sink: Disposable, subscription: Disposable) where Observer.Element == Element { + let sink = RetryWhenSequenceSink(parent: self, observer: observer, cancel: cancel) + let subscription = sink.run((self.sources.makeIterator(), nil)) + return (sink: sink, subscription: subscription) + } +} diff --git a/Pods/RxSwift/RxSwift/Observables/Sample.swift b/Pods/RxSwift/RxSwift/Observables/Sample.swift new file mode 100644 index 0000000..9301c9a --- /dev/null +++ b/Pods/RxSwift/RxSwift/Observables/Sample.swift @@ -0,0 +1,139 @@ +// +// Sample.swift +// RxSwift +// +// Created by Krunoslav Zaher on 5/1/15. +// Copyright © 2015 Krunoslav Zaher. All rights reserved. +// + +extension ObservableType { + + /** + Samples the source observable sequence using a sampler observable sequence producing sampling ticks. + + Upon each sampling tick, the latest element (if any) in the source sequence during the last sampling interval is sent to the resulting sequence. + + **In case there were no new elements between sampler ticks, you may provide a default value to be emitted, instead + to the resulting sequence otherwise no element is sent.** + + - seealso: [sample operator on reactivex.io](http://reactivex.io/documentation/operators/sample.html) + + - parameter sampler: Sampling tick sequence. + - parameter defaultValue: a value to return if there are no new elements between sampler ticks + - returns: Sampled observable sequence. + */ + public func sample(_ sampler: Source, defaultValue: Element? = nil) + -> Observable { + return Sample(source: self.asObservable(), sampler: sampler.asObservable(), defaultValue: defaultValue) + } +} + +final private class SamplerSink + : ObserverType + , LockOwnerType + , SynchronizedOnType { + typealias Element = SampleType + + typealias Parent = SampleSequenceSink + + private let parent: Parent + + var lock: RecursiveLock { + self.parent.lock + } + + init(parent: Parent) { + self.parent = parent + } + + func on(_ event: Event) { + self.synchronizedOn(event) + } + + func synchronized_on(_ event: Event) { + switch event { + case .next, .completed: + if let element = parent.element ?? self.parent.defaultValue { + self.parent.element = nil + self.parent.forwardOn(.next(element)) + } + + if self.parent.atEnd { + self.parent.forwardOn(.completed) + self.parent.dispose() + } + case .error(let e): + self.parent.forwardOn(.error(e)) + self.parent.dispose() + } + } +} + +final private class SampleSequenceSink + : Sink + , ObserverType + , LockOwnerType + , SynchronizedOnType { + typealias Element = Observer.Element + typealias Parent = Sample + + fileprivate let parent: Parent + fileprivate let defaultValue: Element? + + let lock = RecursiveLock() + + // state + fileprivate var element = nil as Element? + fileprivate var atEnd = false + + private let sourceSubscription = SingleAssignmentDisposable() + + init(parent: Parent, observer: Observer, cancel: Cancelable, defaultValue: Element? = nil) { + self.parent = parent + self.defaultValue = defaultValue + super.init(observer: observer, cancel: cancel) + } + + func run() -> Disposable { + self.sourceSubscription.setDisposable(self.parent.source.subscribe(self)) + let samplerSubscription = self.parent.sampler.subscribe(SamplerSink(parent: self)) + + return Disposables.create(sourceSubscription, samplerSubscription) + } + + func on(_ event: Event) { + self.synchronizedOn(event) + } + + func synchronized_on(_ event: Event) { + switch event { + case .next(let element): + self.element = element + case .error: + self.forwardOn(event) + self.dispose() + case .completed: + self.atEnd = true + self.sourceSubscription.dispose() + } + } + +} + +final private class Sample: Producer { + fileprivate let source: Observable + fileprivate let sampler: Observable + fileprivate let defaultValue: Element? + + init(source: Observable, sampler: Observable, defaultValue: Element? = nil) { + self.source = source + self.sampler = sampler + self.defaultValue = defaultValue + } + + override func run(_ observer: Observer, cancel: Cancelable) -> (sink: Disposable, subscription: Disposable) where Observer.Element == Element { + let sink = SampleSequenceSink(parent: self, observer: observer, cancel: cancel, defaultValue: self.defaultValue) + let subscription = sink.run() + return (sink: sink, subscription: subscription) + } +} diff --git a/Pods/RxSwift/RxSwift/Observables/Scan.swift b/Pods/RxSwift/RxSwift/Observables/Scan.swift new file mode 100644 index 0000000..ecf69c8 --- /dev/null +++ b/Pods/RxSwift/RxSwift/Observables/Scan.swift @@ -0,0 +1,100 @@ +// +// Scan.swift +// RxSwift +// +// Created by Krunoslav Zaher on 6/14/15. +// Copyright © 2015 Krunoslav Zaher. All rights reserved. +// + +extension ObservableType { + + /** + Applies an accumulator function over an observable sequence and returns each intermediate result. The specified seed value is used as the initial accumulator value. + + For aggregation behavior with no intermediate results, see `reduce`. + + - seealso: [scan operator on reactivex.io](http://reactivex.io/documentation/operators/scan.html) + + - parameter seed: The initial accumulator value. + - parameter accumulator: An accumulator function to be invoked on each element. + - returns: An observable sequence containing the accumulated values. + */ + public func scan(into seed: A, accumulator: @escaping (inout A, Element) throws -> Void) + -> Observable { + Scan(source: self.asObservable(), seed: seed, accumulator: accumulator) + } + + /** + Applies an accumulator function over an observable sequence and returns each intermediate result. The specified seed value is used as the initial accumulator value. + + For aggregation behavior with no intermediate results, see `reduce`. + + - seealso: [scan operator on reactivex.io](http://reactivex.io/documentation/operators/scan.html) + + - parameter seed: The initial accumulator value. + - parameter accumulator: An accumulator function to be invoked on each element. + - returns: An observable sequence containing the accumulated values. + */ + public func scan(_ seed: A, accumulator: @escaping (A, Element) throws -> A) + -> Observable { + return Scan(source: self.asObservable(), seed: seed) { acc, element in + let currentAcc = acc + acc = try accumulator(currentAcc, element) + } + } +} + +final private class ScanSink: Sink, ObserverType { + typealias Accumulate = Observer.Element + typealias Parent = Scan + + private let parent: Parent + private var accumulate: Accumulate + + init(parent: Parent, observer: Observer, cancel: Cancelable) { + self.parent = parent + self.accumulate = parent.seed + super.init(observer: observer, cancel: cancel) + } + + func on(_ event: Event) { + switch event { + case .next(let element): + do { + try self.parent.accumulator(&self.accumulate, element) + self.forwardOn(.next(self.accumulate)) + } + catch let error { + self.forwardOn(.error(error)) + self.dispose() + } + case .error(let error): + self.forwardOn(.error(error)) + self.dispose() + case .completed: + self.forwardOn(.completed) + self.dispose() + } + } + +} + +final private class Scan: Producer { + typealias Accumulator = (inout Accumulate, Element) throws -> Void + + private let source: Observable + fileprivate let seed: Accumulate + fileprivate let accumulator: Accumulator + + init(source: Observable, seed: Accumulate, accumulator: @escaping Accumulator) { + self.source = source + self.seed = seed + self.accumulator = accumulator + } + + override func run(_ observer: Observer, cancel: Cancelable) -> (sink: Disposable, subscription: Disposable) where Observer.Element == Accumulate { + let sink = ScanSink(parent: self, observer: observer, cancel: cancel) + let subscription = self.source.subscribe(sink) + return (sink: sink, subscription: subscription) + } +} diff --git a/Pods/RxSwift/RxSwift/Observables/Sequence.swift b/Pods/RxSwift/RxSwift/Observables/Sequence.swift new file mode 100644 index 0000000..c6d1089 --- /dev/null +++ b/Pods/RxSwift/RxSwift/Observables/Sequence.swift @@ -0,0 +1,89 @@ +// +// Sequence.swift +// RxSwift +// +// Created by Krunoslav Zaher on 11/14/15. +// Copyright © 2015 Krunoslav Zaher. All rights reserved. +// + +extension ObservableType { + // MARK: of + + /** + This method creates a new Observable instance with a variable number of elements. + + - seealso: [from operator on reactivex.io](http://reactivex.io/documentation/operators/from.html) + + - parameter elements: Elements to generate. + - parameter scheduler: Scheduler to send elements on. If `nil`, elements are sent immediately on subscription. + - returns: The observable sequence whose elements are pulled from the given arguments. + */ + public static func of(_ elements: Element ..., scheduler: ImmediateSchedulerType = CurrentThreadScheduler.instance) -> Observable { + ObservableSequence(elements: elements, scheduler: scheduler) + } +} + +extension ObservableType { + /** + Converts an array to an observable sequence. + + - seealso: [from operator on reactivex.io](http://reactivex.io/documentation/operators/from.html) + + - returns: The observable sequence whose elements are pulled from the given enumerable sequence. + */ + public static func from(_ array: [Element], scheduler: ImmediateSchedulerType = CurrentThreadScheduler.instance) -> Observable { + ObservableSequence(elements: array, scheduler: scheduler) + } + + /** + Converts a sequence to an observable sequence. + + - seealso: [from operator on reactivex.io](http://reactivex.io/documentation/operators/from.html) + + - returns: The observable sequence whose elements are pulled from the given enumerable sequence. + */ + public static func from(_ sequence: Sequence, scheduler: ImmediateSchedulerType = CurrentThreadScheduler.instance) -> Observable where Sequence.Element == Element { + ObservableSequence(elements: sequence, scheduler: scheduler) + } +} + +final private class ObservableSequenceSink: Sink where Sequence.Element == Observer.Element { + typealias Parent = ObservableSequence + + private let parent: Parent + + init(parent: Parent, observer: Observer, cancel: Cancelable) { + self.parent = parent + super.init(observer: observer, cancel: cancel) + } + + func run() -> Disposable { + return self.parent.scheduler.scheduleRecursive(self.parent.elements.makeIterator()) { iterator, recurse in + var mutableIterator = iterator + if let next = mutableIterator.next() { + self.forwardOn(.next(next)) + recurse(mutableIterator) + } + else { + self.forwardOn(.completed) + self.dispose() + } + } + } +} + +final private class ObservableSequence: Producer { + fileprivate let elements: Sequence + fileprivate let scheduler: ImmediateSchedulerType + + init(elements: Sequence, scheduler: ImmediateSchedulerType) { + self.elements = elements + self.scheduler = scheduler + } + + override func run(_ observer: Observer, cancel: Cancelable) -> (sink: Disposable, subscription: Disposable) where Observer.Element == Element { + let sink = ObservableSequenceSink(parent: self, observer: observer, cancel: cancel) + let subscription = sink.run() + return (sink: sink, subscription: subscription) + } +} diff --git a/Pods/RxSwift/RxSwift/Observables/ShareReplayScope.swift b/Pods/RxSwift/RxSwift/Observables/ShareReplayScope.swift new file mode 100644 index 0000000..59d440d --- /dev/null +++ b/Pods/RxSwift/RxSwift/Observables/ShareReplayScope.swift @@ -0,0 +1,443 @@ +// +// ShareReplayScope.swift +// RxSwift +// +// Created by Krunoslav Zaher on 5/28/17. +// Copyright © 2017 Krunoslav Zaher. All rights reserved. +// + +/// Subject lifetime scope +public enum SubjectLifetimeScope { + /** + **Each connection will have it's own subject instance to store replay events.** + **Connections will be isolated from each another.** + + Configures the underlying implementation to behave equivalent to. + + ``` + source.multicast(makeSubject: { MySubject() }).refCount() + ``` + + **This is the recommended default.** + + This has the following consequences: + * `retry` or `concat` operators will function as expected because terminating the sequence will clear internal state. + * Each connection to source observable sequence will use it's own subject. + * When the number of subscribers drops from 1 to 0 and connection to source sequence is disposed, subject will be cleared. + + + ``` + let xs = Observable.deferred { () -> Observable in + print("Performing work ...") + return Observable.just(Date().timeIntervalSince1970) + } + .share(replay: 1, scope: .whileConnected) + + _ = xs.subscribe(onNext: { print("next \($0)") }, onCompleted: { print("completed\n") }) + _ = xs.subscribe(onNext: { print("next \($0)") }, onCompleted: { print("completed\n") }) + _ = xs.subscribe(onNext: { print("next \($0)") }, onCompleted: { print("completed\n") }) + + ``` + + Notice how time interval is different and `Performing work ...` is printed each time) + + ``` + Performing work ... + next 1495998900.82141 + completed + + Performing work ... + next 1495998900.82359 + completed + + Performing work ... + next 1495998900.82444 + completed + + + ``` + + */ + case whileConnected + + /** + **One subject will store replay events for all connections to source.** + **Connections won't be isolated from each another.** + + Configures the underlying implementation behave equivalent to. + + ``` + source.multicast(MySubject()).refCount() + ``` + + This has the following consequences: + * Using `retry` or `concat` operators after this operator usually isn't advised. + * Each connection to source observable sequence will share the same subject. + * After number of subscribers drops from 1 to 0 and connection to source observable sequence is dispose, this operator will + continue holding a reference to the same subject. + If at some later moment a new observer initiates a new connection to source it can potentially receive + some of the stale events received during previous connection. + * After source sequence terminates any new observer will always immediately receive replayed elements and terminal event. + No new subscriptions to source observable sequence will be attempted. + + ``` + let xs = Observable.deferred { () -> Observable in + print("Performing work ...") + return Observable.just(Date().timeIntervalSince1970) + } + .share(replay: 1, scope: .forever) + + _ = xs.subscribe(onNext: { print("next \($0)") }, onCompleted: { print("completed\n") }) + _ = xs.subscribe(onNext: { print("next \($0)") }, onCompleted: { print("completed\n") }) + _ = xs.subscribe(onNext: { print("next \($0)") }, onCompleted: { print("completed\n") }) + ``` + + Notice how time interval is the same, replayed, and `Performing work ...` is printed only once + + ``` + Performing work ... + next 1495999013.76356 + completed + + next 1495999013.76356 + completed + + next 1495999013.76356 + completed + ``` + + */ + case forever +} + +extension ObservableType { + + /** + Returns an observable sequence that **shares a single subscription to the underlying sequence**, and immediately upon subscription replays elements in buffer. + + This operator is equivalent to: + * `.whileConnected` + ``` + // Each connection will have it's own subject instance to store replay events. + // Connections will be isolated from each another. + source.multicast(makeSubject: { Replay.create(bufferSize: replay) }).refCount() + ``` + * `.forever` + ``` + // One subject will store replay events for all connections to source. + // Connections won't be isolated from each another. + source.multicast(Replay.create(bufferSize: replay)).refCount() + ``` + + It uses optimized versions of the operators for most common operations. + + - parameter replay: Maximum element count of the replay buffer. + - parameter scope: Lifetime scope of sharing subject. For more information see `SubjectLifetimeScope` enum. + + - seealso: [shareReplay operator on reactivex.io](http://reactivex.io/documentation/operators/replay.html) + + - returns: An observable sequence that contains the elements of a sequence produced by multicasting the source sequence. + */ + public func share(replay: Int = 0, scope: SubjectLifetimeScope = .whileConnected) + -> Observable { + switch scope { + case .forever: + switch replay { + case 0: return self.multicast(PublishSubject()).refCount() + default: return self.multicast(ReplaySubject.create(bufferSize: replay)).refCount() + } + case .whileConnected: + switch replay { + case 0: return ShareWhileConnected(source: self.asObservable()) + case 1: return ShareReplay1WhileConnected(source: self.asObservable()) + default: return self.multicast(makeSubject: { ReplaySubject.create(bufferSize: replay) }).refCount() + } + } + } +} + +private final class ShareReplay1WhileConnectedConnection + : ObserverType + , SynchronizedUnsubscribeType { + typealias Observers = AnyObserver.s + typealias DisposeKey = Observers.KeyType + + typealias Parent = ShareReplay1WhileConnected + private let parent: Parent + private let subscription = SingleAssignmentDisposable() + + private let lock: RecursiveLock + private var disposed: Bool = false + fileprivate var observers = Observers() + private var element: Element? + + init(parent: Parent, lock: RecursiveLock) { + self.parent = parent + self.lock = lock + + #if TRACE_RESOURCES + _ = Resources.incrementTotal() + #endif + } + + final func on(_ event: Event) { + let observers = self.lock.performLocked { self.synchronized_on(event) } + dispatch(observers, event) + } + + final private func synchronized_on(_ event: Event) -> Observers { + if self.disposed { + return Observers() + } + + switch event { + case .next(let element): + self.element = element + return self.observers + case .error, .completed: + let observers = self.observers + self.synchronized_dispose() + return observers + } + } + + final func connect() { + self.subscription.setDisposable(self.parent.source.subscribe(self)) + } + + final func synchronized_subscribe(_ observer: Observer) -> Disposable where Observer.Element == Element { + self.lock.performLocked { + if let element = self.element { + observer.on(.next(element)) + } + + let disposeKey = self.observers.insert(observer.on) + + return SubscriptionDisposable(owner: self, key: disposeKey) + } + } + + final private func synchronized_dispose() { + self.disposed = true + if self.parent.connection === self { + self.parent.connection = nil + } + self.observers = Observers() + } + + final func synchronizedUnsubscribe(_ disposeKey: DisposeKey) { + if self.lock.performLocked({ self.synchronized_unsubscribe(disposeKey) }) { + self.subscription.dispose() + } + } + + @inline(__always) + final private func synchronized_unsubscribe(_ disposeKey: DisposeKey) -> Bool { + // if already unsubscribed, just return + if self.observers.removeKey(disposeKey) == nil { + return false + } + + if self.observers.count == 0 { + self.synchronized_dispose() + return true + } + + return false + } + + #if TRACE_RESOURCES + deinit { + _ = Resources.decrementTotal() + } + #endif +} + +// optimized version of share replay for most common case +final private class ShareReplay1WhileConnected + : Observable { + + fileprivate typealias Connection = ShareReplay1WhileConnectedConnection + + fileprivate let source: Observable + + private let lock = RecursiveLock() + + fileprivate var connection: Connection? + + init(source: Observable) { + self.source = source + } + + override func subscribe(_ observer: Observer) -> Disposable where Observer.Element == Element { + self.lock.lock() + let connection = self.synchronized_subscribe(observer) + let count = connection.observers.count + + let disposable = connection.synchronized_subscribe(observer) + self.lock.unlock() + + if count == 0 { + connection.connect() + } + + return disposable + } + + @inline(__always) + private func synchronized_subscribe(_ observer: Observer) -> Connection where Observer.Element == Element { + let connection: Connection + + if let existingConnection = self.connection { + connection = existingConnection + } + else { + connection = ShareReplay1WhileConnectedConnection( + parent: self, + lock: self.lock) + self.connection = connection + } + + return connection + } +} + +private final class ShareWhileConnectedConnection + : ObserverType + , SynchronizedUnsubscribeType { + typealias Observers = AnyObserver.s + typealias DisposeKey = Observers.KeyType + + typealias Parent = ShareWhileConnected + private let parent: Parent + private let subscription = SingleAssignmentDisposable() + + private let lock: RecursiveLock + private var disposed: Bool = false + fileprivate var observers = Observers() + + init(parent: Parent, lock: RecursiveLock) { + self.parent = parent + self.lock = lock + + #if TRACE_RESOURCES + _ = Resources.incrementTotal() + #endif + } + + final func on(_ event: Event) { + let observers = self.lock.performLocked { self.synchronized_on(event) } + dispatch(observers, event) + } + + final private func synchronized_on(_ event: Event) -> Observers { + if self.disposed { + return Observers() + } + + switch event { + case .next: + return self.observers + case .error, .completed: + let observers = self.observers + self.synchronized_dispose() + return observers + } + } + + final func connect() { + self.subscription.setDisposable(self.parent.source.subscribe(self)) + } + + final func synchronized_subscribe(_ observer: Observer) -> Disposable where Observer.Element == Element { + self.lock.performLocked { + let disposeKey = self.observers.insert(observer.on) + + return SubscriptionDisposable(owner: self, key: disposeKey) + } + } + + final private func synchronized_dispose() { + self.disposed = true + if self.parent.connection === self { + self.parent.connection = nil + } + self.observers = Observers() + } + + final func synchronizedUnsubscribe(_ disposeKey: DisposeKey) { + if self.lock.performLocked({ self.synchronized_unsubscribe(disposeKey) }) { + self.subscription.dispose() + } + } + + @inline(__always) + final private func synchronized_unsubscribe(_ disposeKey: DisposeKey) -> Bool { + // if already unsubscribed, just return + if self.observers.removeKey(disposeKey) == nil { + return false + } + + if self.observers.count == 0 { + self.synchronized_dispose() + return true + } + + return false + } + + #if TRACE_RESOURCES + deinit { + _ = Resources.decrementTotal() + } + #endif +} + +// optimized version of share replay for most common case +final private class ShareWhileConnected + : Observable { + + fileprivate typealias Connection = ShareWhileConnectedConnection + + fileprivate let source: Observable + + private let lock = RecursiveLock() + + fileprivate var connection: Connection? + + init(source: Observable) { + self.source = source + } + + override func subscribe(_ observer: Observer) -> Disposable where Observer.Element == Element { + self.lock.lock() + let connection = self.synchronized_subscribe(observer) + let count = connection.observers.count + + let disposable = connection.synchronized_subscribe(observer) + self.lock.unlock() + + if count == 0 { + connection.connect() + } + + return disposable + } + + @inline(__always) + private func synchronized_subscribe(_ observer: Observer) -> Connection where Observer.Element == Element { + let connection: Connection + + if let existingConnection = self.connection { + connection = existingConnection + } + else { + connection = ShareWhileConnectedConnection( + parent: self, + lock: self.lock) + self.connection = connection + } + + return connection + } +} diff --git a/Pods/RxSwift/RxSwift/Observables/SingleAsync.swift b/Pods/RxSwift/RxSwift/Observables/SingleAsync.swift new file mode 100644 index 0000000..04e2217 --- /dev/null +++ b/Pods/RxSwift/RxSwift/Observables/SingleAsync.swift @@ -0,0 +1,104 @@ +// +// SingleAsync.swift +// RxSwift +// +// Created by Junior B. on 09/11/15. +// Copyright © 2015 Krunoslav Zaher. All rights reserved. +// + +extension ObservableType { + + /** + The single operator is similar to first, but throws a `RxError.noElements` or `RxError.moreThanOneElement` + if the source Observable does not emit exactly one element before successfully completing. + + - seealso: [single operator on reactivex.io](http://reactivex.io/documentation/operators/first.html) + + - returns: An observable sequence that emits a single element or throws an exception if more (or none) of them are emitted. + */ + public func single() + -> Observable { + SingleAsync(source: self.asObservable()) + } + + /** + The single operator is similar to first, but throws a `RxError.NoElements` or `RxError.MoreThanOneElement` + if the source Observable does not emit exactly one element before successfully completing. + + - seealso: [single operator on reactivex.io](http://reactivex.io/documentation/operators/first.html) + + - parameter predicate: A function to test each source element for a condition. + - returns: An observable sequence that emits a single element or throws an exception if more (or none) of them are emitted. + */ + public func single(_ predicate: @escaping (Element) throws -> Bool) + -> Observable { + SingleAsync(source: self.asObservable(), predicate: predicate) + } +} + +private final class SingleAsyncSink : Sink, ObserverType { + typealias Element = Observer.Element + typealias Parent = SingleAsync + + private let parent: Parent + private var seenValue: Bool = false + + init(parent: Parent, observer: Observer, cancel: Cancelable) { + self.parent = parent + super.init(observer: observer, cancel: cancel) + } + + func on(_ event: Event) { + switch event { + case .next(let value): + do { + let forward = try self.parent.predicate?(value) ?? true + if !forward { + return + } + } + catch let error { + self.forwardOn(.error(error as Swift.Error)) + self.dispose() + return + } + + if self.seenValue { + self.forwardOn(.error(RxError.moreThanOneElement)) + self.dispose() + return + } + + self.seenValue = true + self.forwardOn(.next(value)) + case .error: + self.forwardOn(event) + self.dispose() + case .completed: + if self.seenValue { + self.forwardOn(.completed) + } else { + self.forwardOn(.error(RxError.noElements)) + } + self.dispose() + } + } +} + +final class SingleAsync: Producer { + typealias Predicate = (Element) throws -> Bool + + private let source: Observable + fileprivate let predicate: Predicate? + + init(source: Observable, predicate: Predicate? = nil) { + self.source = source + self.predicate = predicate + } + + override func run(_ observer: Observer, cancel: Cancelable) -> (sink: Disposable, subscription: Disposable) where Observer.Element == Element { + let sink = SingleAsyncSink(parent: self, observer: observer, cancel: cancel) + let subscription = self.source.subscribe(sink) + return (sink: sink, subscription: subscription) + } +} diff --git a/Pods/RxSwift/RxSwift/Observables/Sink.swift b/Pods/RxSwift/RxSwift/Observables/Sink.swift new file mode 100644 index 0000000..ed4fec0 --- /dev/null +++ b/Pods/RxSwift/RxSwift/Observables/Sink.swift @@ -0,0 +1,75 @@ +// +// Sink.swift +// RxSwift +// +// Created by Krunoslav Zaher on 2/19/15. +// Copyright © 2015 Krunoslav Zaher. All rights reserved. +// + +class Sink: Disposable { + fileprivate let observer: Observer + fileprivate let cancel: Cancelable + private let disposed = AtomicInt(0) + + #if DEBUG + private let synchronizationTracker = SynchronizationTracker() + #endif + + init(observer: Observer, cancel: Cancelable) { +#if TRACE_RESOURCES + _ = Resources.incrementTotal() +#endif + self.observer = observer + self.cancel = cancel + } + + final func forwardOn(_ event: Event) { + #if DEBUG + self.synchronizationTracker.register(synchronizationErrorMessage: .default) + defer { self.synchronizationTracker.unregister() } + #endif + if isFlagSet(self.disposed, 1) { + return + } + self.observer.on(event) + } + + final func forwarder() -> SinkForward { + SinkForward(forward: self) + } + + final var isDisposed: Bool { + isFlagSet(self.disposed, 1) + } + + func dispose() { + fetchOr(self.disposed, 1) + self.cancel.dispose() + } + + deinit { +#if TRACE_RESOURCES + _ = Resources.decrementTotal() +#endif + } +} + +final class SinkForward: ObserverType { + typealias Element = Observer.Element + + private let forward: Sink + + init(forward: Sink) { + self.forward = forward + } + + final func on(_ event: Event) { + switch event { + case .next: + self.forward.observer.on(event) + case .error, .completed: + self.forward.observer.on(event) + self.forward.cancel.dispose() + } + } +} diff --git a/Pods/RxSwift/RxSwift/Observables/Skip.swift b/Pods/RxSwift/RxSwift/Observables/Skip.swift new file mode 100644 index 0000000..5856f37 --- /dev/null +++ b/Pods/RxSwift/RxSwift/Observables/Skip.swift @@ -0,0 +1,158 @@ +// +// Skip.swift +// RxSwift +// +// Created by Krunoslav Zaher on 6/25/15. +// Copyright © 2015 Krunoslav Zaher. All rights reserved. +// + +extension ObservableType { + + /** + Bypasses a specified number of elements in an observable sequence and then returns the remaining elements. + + - seealso: [skip operator on reactivex.io](http://reactivex.io/documentation/operators/skip.html) + + - parameter count: The number of elements to skip before returning the remaining elements. + - returns: An observable sequence that contains the elements that occur after the specified index in the input sequence. + */ + public func skip(_ count: Int) + -> Observable { + SkipCount(source: self.asObservable(), count: count) + } +} + +extension ObservableType { + + /** + Skips elements for the specified duration from the start of the observable source sequence, using the specified scheduler to run timers. + + - seealso: [skip operator on reactivex.io](http://reactivex.io/documentation/operators/skip.html) + + - parameter duration: Duration for skipping elements from the start of the sequence. + - parameter scheduler: Scheduler to run the timer on. + - returns: An observable sequence with the elements skipped during the specified duration from the start of the source sequence. + */ + public func skip(_ duration: RxTimeInterval, scheduler: SchedulerType) + -> Observable { + SkipTime(source: self.asObservable(), duration: duration, scheduler: scheduler) + } +} + +// count version + +final private class SkipCountSink: Sink, ObserverType { + typealias Element = Observer.Element + typealias Parent = SkipCount + + let parent: Parent + + var remaining: Int + + init(parent: Parent, observer: Observer, cancel: Cancelable) { + self.parent = parent + self.remaining = parent.count + super.init(observer: observer, cancel: cancel) + } + + func on(_ event: Event) { + switch event { + case .next(let value): + + if self.remaining <= 0 { + self.forwardOn(.next(value)) + } + else { + self.remaining -= 1 + } + case .error: + self.forwardOn(event) + self.dispose() + case .completed: + self.forwardOn(event) + self.dispose() + } + } + +} + +final private class SkipCount: Producer { + let source: Observable + let count: Int + + init(source: Observable, count: Int) { + self.source = source + self.count = count + } + + override func run(_ observer: Observer, cancel: Cancelable) -> (sink: Disposable, subscription: Disposable) where Observer.Element == Element { + let sink = SkipCountSink(parent: self, observer: observer, cancel: cancel) + let subscription = self.source.subscribe(sink) + + return (sink: sink, subscription: subscription) + } +} + +// time version + +final private class SkipTimeSink: Sink, ObserverType where Observer.Element == Element { + typealias Parent = SkipTime + + let parent: Parent + + // state + var open = false + + init(parent: Parent, observer: Observer, cancel: Cancelable) { + self.parent = parent + super.init(observer: observer, cancel: cancel) + } + + func on(_ event: Event) { + switch event { + case .next(let value): + if self.open { + self.forwardOn(.next(value)) + } + case .error: + self.forwardOn(event) + self.dispose() + case .completed: + self.forwardOn(event) + self.dispose() + } + } + + func tick() { + self.open = true + } + + func run() -> Disposable { + let disposeTimer = self.parent.scheduler.scheduleRelative((), dueTime: self.parent.duration) { _ in + self.tick() + return Disposables.create() + } + + let disposeSubscription = self.parent.source.subscribe(self) + + return Disposables.create(disposeTimer, disposeSubscription) + } +} + +final private class SkipTime: Producer { + let source: Observable + let duration: RxTimeInterval + let scheduler: SchedulerType + + init(source: Observable, duration: RxTimeInterval, scheduler: SchedulerType) { + self.source = source + self.scheduler = scheduler + self.duration = duration + } + + override func run(_ observer: Observer, cancel: Cancelable) -> (sink: Disposable, subscription: Disposable) where Observer.Element == Element { + let sink = SkipTimeSink(parent: self, observer: observer, cancel: cancel) + let subscription = sink.run() + return (sink: sink, subscription: subscription) + } +} diff --git a/Pods/RxSwift/RxSwift/Observables/SkipUntil.swift b/Pods/RxSwift/RxSwift/Observables/SkipUntil.swift new file mode 100644 index 0000000..c8fe193 --- /dev/null +++ b/Pods/RxSwift/RxSwift/Observables/SkipUntil.swift @@ -0,0 +1,152 @@ +// +// SkipUntil.swift +// RxSwift +// +// Created by Yury Korolev on 10/3/15. +// Copyright © 2015 Krunoslav Zaher. All rights reserved. +// + +extension ObservableType { + /** + Returns the elements from the source observable sequence that are emitted after the other observable sequence produces an element. + + - seealso: [skipUntil operator on reactivex.io](http://reactivex.io/documentation/operators/skipuntil.html) + + - parameter other: Observable sequence that starts propagation of elements of the source sequence. + - returns: An observable sequence containing the elements of the source sequence that are emitted after the other sequence emits an item. + */ + public func skip(until other: Source) + -> Observable { + SkipUntil(source: self.asObservable(), other: other.asObservable()) + } + + /** + Returns the elements from the source observable sequence that are emitted after the other observable sequence produces an element. + + - seealso: [skipUntil operator on reactivex.io](http://reactivex.io/documentation/operators/skipuntil.html) + + - parameter other: Observable sequence that starts propagation of elements of the source sequence. + - returns: An observable sequence containing the elements of the source sequence that are emitted after the other sequence emits an item. + */ + @available(*, deprecated, renamed: "skip(until:)") + public func skipUntil(_ other: Source) + -> Observable { + skip(until: other) + } +} + +final private class SkipUntilSinkOther + : ObserverType + , LockOwnerType + , SynchronizedOnType { + typealias Parent = SkipUntilSink + typealias Element = Other + + private let parent: Parent + + var lock: RecursiveLock { + self.parent.lock + } + + let subscription = SingleAssignmentDisposable() + + init(parent: Parent) { + self.parent = parent + #if TRACE_RESOURCES + _ = Resources.incrementTotal() + #endif + } + + func on(_ event: Event) { + self.synchronizedOn(event) + } + + func synchronized_on(_ event: Event) { + switch event { + case .next: + self.parent.forwardElements = true + self.subscription.dispose() + case .error(let e): + self.parent.forwardOn(.error(e)) + self.parent.dispose() + case .completed: + self.subscription.dispose() + } + } + + #if TRACE_RESOURCES + deinit { + _ = Resources.decrementTotal() + } + #endif + +} + + +final private class SkipUntilSink + : Sink + , ObserverType + , LockOwnerType + , SynchronizedOnType { + typealias Element = Observer.Element + typealias Parent = SkipUntil + + let lock = RecursiveLock() + private let parent: Parent + fileprivate var forwardElements = false + + private let sourceSubscription = SingleAssignmentDisposable() + + init(parent: Parent, observer: Observer, cancel: Cancelable) { + self.parent = parent + super.init(observer: observer, cancel: cancel) + } + + func on(_ event: Event) { + self.synchronizedOn(event) + } + + func synchronized_on(_ event: Event) { + switch event { + case .next: + if self.forwardElements { + self.forwardOn(event) + } + case .error: + self.forwardOn(event) + self.dispose() + case .completed: + if self.forwardElements { + self.forwardOn(event) + } + self.dispose() + } + } + + func run() -> Disposable { + let sourceSubscription = self.parent.source.subscribe(self) + let otherObserver = SkipUntilSinkOther(parent: self) + let otherSubscription = self.parent.other.subscribe(otherObserver) + self.sourceSubscription.setDisposable(sourceSubscription) + otherObserver.subscription.setDisposable(otherSubscription) + + return Disposables.create(sourceSubscription, otherObserver.subscription) + } +} + +final private class SkipUntil: Producer { + + fileprivate let source: Observable + fileprivate let other: Observable + + init(source: Observable, other: Observable) { + self.source = source + self.other = other + } + + override func run(_ observer: Observer, cancel: Cancelable) -> (sink: Disposable, subscription: Disposable) where Observer.Element == Element { + let sink = SkipUntilSink(parent: self, observer: observer, cancel: cancel) + let subscription = sink.run() + return (sink: sink, subscription: subscription) + } +} diff --git a/Pods/RxSwift/RxSwift/Observables/SkipWhile.swift b/Pods/RxSwift/RxSwift/Observables/SkipWhile.swift new file mode 100644 index 0000000..a62f88d --- /dev/null +++ b/Pods/RxSwift/RxSwift/Observables/SkipWhile.swift @@ -0,0 +1,87 @@ +// +// SkipWhile.swift +// RxSwift +// +// Created by Yury Korolev on 10/9/15. +// Copyright © 2015 Krunoslav Zaher. All rights reserved. +// + +extension ObservableType { + /** + Bypasses elements in an observable sequence as long as a specified condition is true and then returns the remaining elements. + + - seealso: [skipWhile operator on reactivex.io](http://reactivex.io/documentation/operators/skipwhile.html) + + - parameter predicate: A function to test each element for a condition. + - returns: An observable sequence that contains the elements from the input sequence starting at the first element in the linear series that does not pass the test specified by predicate. + */ + public func skip(while predicate: @escaping (Element) throws -> Bool) -> Observable { + SkipWhile(source: self.asObservable(), predicate: predicate) + } + + /** + Bypasses elements in an observable sequence as long as a specified condition is true and then returns the remaining elements. + + - seealso: [skipWhile operator on reactivex.io](http://reactivex.io/documentation/operators/skipwhile.html) + + - parameter predicate: A function to test each element for a condition. + - returns: An observable sequence that contains the elements from the input sequence starting at the first element in the linear series that does not pass the test specified by predicate. + */ + @available(*, deprecated, renamed: "skip(while:)") + public func skipWhile(_ predicate: @escaping (Element) throws -> Bool) -> Observable { + SkipWhile(source: self.asObservable(), predicate: predicate) + } +} + +final private class SkipWhileSink: Sink, ObserverType { + typealias Element = Observer.Element + typealias Parent = SkipWhile + + private let parent: Parent + private var running = false + + init(parent: Parent, observer: Observer, cancel: Cancelable) { + self.parent = parent + super.init(observer: observer, cancel: cancel) + } + + func on(_ event: Event) { + switch event { + case .next(let value): + if !self.running { + do { + self.running = try !self.parent.predicate(value) + } catch let e { + self.forwardOn(.error(e)) + self.dispose() + return + } + } + + if self.running { + self.forwardOn(.next(value)) + } + case .error, .completed: + self.forwardOn(event) + self.dispose() + } + } +} + +final private class SkipWhile: Producer { + typealias Predicate = (Element) throws -> Bool + + private let source: Observable + fileprivate let predicate: Predicate + + init(source: Observable, predicate: @escaping Predicate) { + self.source = source + self.predicate = predicate + } + + override func run(_ observer: Observer, cancel: Cancelable) -> (sink: Disposable, subscription: Disposable) where Observer.Element == Element { + let sink = SkipWhileSink(parent: self, observer: observer, cancel: cancel) + let subscription = self.source.subscribe(sink) + return (sink: sink, subscription: subscription) + } +} diff --git a/Pods/RxSwift/RxSwift/Observables/StartWith.swift b/Pods/RxSwift/RxSwift/Observables/StartWith.swift new file mode 100644 index 0000000..13fb31d --- /dev/null +++ b/Pods/RxSwift/RxSwift/Observables/StartWith.swift @@ -0,0 +1,42 @@ +// +// StartWith.swift +// RxSwift +// +// Created by Krunoslav Zaher on 4/6/15. +// Copyright © 2015 Krunoslav Zaher. All rights reserved. +// + +extension ObservableType { + + /** + Prepends a sequence of values to an observable sequence. + + - seealso: [startWith operator on reactivex.io](http://reactivex.io/documentation/operators/startwith.html) + + - parameter elements: Elements to prepend to the specified sequence. + - returns: The source sequence prepended with the specified values. + */ + public func startWith(_ elements: Element ...) + -> Observable { + return StartWith(source: self.asObservable(), elements: elements) + } +} + +final private class StartWith: Producer { + let elements: [Element] + let source: Observable + + init(source: Observable, elements: [Element]) { + self.source = source + self.elements = elements + super.init() + } + + override func run(_ observer: Observer, cancel: Cancelable) -> (sink: Disposable, subscription: Disposable) where Observer.Element == Element { + for e in self.elements { + observer.on(.next(e)) + } + + return (sink: Disposables.create(), subscription: self.source.subscribe(observer)) + } +} diff --git a/Pods/RxSwift/RxSwift/Observables/SubscribeOn.swift b/Pods/RxSwift/RxSwift/Observables/SubscribeOn.swift new file mode 100644 index 0000000..e8e41d9 --- /dev/null +++ b/Pods/RxSwift/RxSwift/Observables/SubscribeOn.swift @@ -0,0 +1,103 @@ +// +// SubscribeOn.swift +// RxSwift +// +// Created by Krunoslav Zaher on 6/14/15. +// Copyright © 2015 Krunoslav Zaher. All rights reserved. +// + +extension ObservableType { + /** + Wraps the source sequence in order to run its subscription and unsubscription logic on the specified + scheduler. + + This operation is not commonly used. + + This only performs the side-effects of subscription and unsubscription on the specified scheduler. + + In order to invoke observer callbacks on a `scheduler`, use `observeOn`. + + - seealso: [subscribeOn operator on reactivex.io](http://reactivex.io/documentation/operators/subscribeon.html) + + - parameter scheduler: Scheduler to perform subscription and unsubscription actions on. + - returns: The source sequence whose subscriptions and unsubscriptions happen on the specified scheduler. + */ + public func subscribe(on scheduler: ImmediateSchedulerType) + -> Observable { + SubscribeOn(source: self, scheduler: scheduler) + } + + /** + Wraps the source sequence in order to run its subscription and unsubscription logic on the specified + scheduler. + + This operation is not commonly used. + + This only performs the side-effects of subscription and unsubscription on the specified scheduler. + + In order to invoke observer callbacks on a `scheduler`, use `observeOn`. + + - seealso: [subscribeOn operator on reactivex.io](http://reactivex.io/documentation/operators/subscribeon.html) + + - parameter scheduler: Scheduler to perform subscription and unsubscription actions on. + - returns: The source sequence whose subscriptions and unsubscriptions happen on the specified scheduler. + */ + @available(*, deprecated, renamed: "subscribe(on:)") + public func subscribeOn(_ scheduler: ImmediateSchedulerType) + -> Observable { + subscribe(on: scheduler) + } +} + +final private class SubscribeOnSink: Sink, ObserverType where Ob.Element == Observer.Element { + typealias Element = Observer.Element + typealias Parent = SubscribeOn + + let parent: Parent + + init(parent: Parent, observer: Observer, cancel: Cancelable) { + self.parent = parent + super.init(observer: observer, cancel: cancel) + } + + func on(_ event: Event) { + self.forwardOn(event) + + if event.isStopEvent { + self.dispose() + } + } + + func run() -> Disposable { + let disposeEverything = SerialDisposable() + let cancelSchedule = SingleAssignmentDisposable() + + disposeEverything.disposable = cancelSchedule + + let disposeSchedule = self.parent.scheduler.schedule(()) { _ -> Disposable in + let subscription = self.parent.source.subscribe(self) + disposeEverything.disposable = ScheduledDisposable(scheduler: self.parent.scheduler, disposable: subscription) + return Disposables.create() + } + + cancelSchedule.setDisposable(disposeSchedule) + + return disposeEverything + } +} + +final private class SubscribeOn: Producer { + let source: Ob + let scheduler: ImmediateSchedulerType + + init(source: Ob, scheduler: ImmediateSchedulerType) { + self.source = source + self.scheduler = scheduler + } + + override func run(_ observer: Observer, cancel: Cancelable) -> (sink: Disposable, subscription: Disposable) where Observer.Element == Ob.Element { + let sink = SubscribeOnSink(parent: self, observer: observer, cancel: cancel) + let subscription = sink.run() + return (sink: sink, subscription: subscription) + } +} diff --git a/Pods/RxSwift/RxSwift/Observables/Switch.swift b/Pods/RxSwift/RxSwift/Observables/Switch.swift new file mode 100644 index 0000000..5aa60b9 --- /dev/null +++ b/Pods/RxSwift/RxSwift/Observables/Switch.swift @@ -0,0 +1,251 @@ +// +// Switch.swift +// RxSwift +// +// Created by Krunoslav Zaher on 3/12/15. +// Copyright © 2015 Krunoslav Zaher. All rights reserved. +// + +extension ObservableType { + /** + Projects each element of an observable sequence into a new sequence of observable sequences and then + transforms an observable sequence of observable sequences into an observable sequence producing values only from the most recent observable sequence. + + It is a combination of `map` + `switchLatest` operator + + - seealso: [flatMapLatest operator on reactivex.io](http://reactivex.io/documentation/operators/flatmap.html) + + - parameter selector: A transform function to apply to each element. + - returns: An observable sequence whose elements are the result of invoking the transform function on each element of source producing an + Observable of Observable sequences and that at any point in time produces the elements of the most recent inner observable sequence that has been received. + */ + public func flatMapLatest(_ selector: @escaping (Element) throws -> Source) + -> Observable { + return FlatMapLatest(source: self.asObservable(), selector: selector) + } + + /** + Projects each element of an observable sequence into a new sequence of observable sequences and then + transforms an observable sequence of observable sequences into an observable sequence producing values only from the most recent observable sequence. + + It is a combination of `map` + `switchLatest` operator + + - seealso: [flatMapLatest operator on reactivex.io](http://reactivex.io/documentation/operators/flatmap.html) + + - parameter selector: A transform function to apply to each element. + - returns: An observable sequence whose elements are the result of invoking the transform function on each element of source producing an + Observable of Observable sequences and that at any point in time produces the elements of the most recent inner observable sequence that has been received. + */ + public func flatMapLatest(_ selector: @escaping (Element) throws -> Source) + -> Infallible { + return Infallible(flatMapLatest(selector)) + } +} + +extension ObservableType where Element: ObservableConvertibleType { + + /** + Transforms an observable sequence of observable sequences into an observable sequence + producing values only from the most recent observable sequence. + + Each time a new inner observable sequence is received, unsubscribe from the + previous inner observable sequence. + + - seealso: [switch operator on reactivex.io](http://reactivex.io/documentation/operators/switch.html) + + - returns: The observable sequence that at any point in time produces the elements of the most recent inner observable sequence that has been received. + */ + public func switchLatest() -> Observable { + Switch(source: self.asObservable()) + } +} + +private class SwitchSink + : Sink + , ObserverType where Source.Element == Observer.Element { + typealias Element = SourceType + + private let subscriptions: SingleAssignmentDisposable = SingleAssignmentDisposable() + private let innerSubscription: SerialDisposable = SerialDisposable() + + let lock = RecursiveLock() + + // state + fileprivate var stopped = false + fileprivate var latest = 0 + fileprivate var hasLatest = false + + override init(observer: Observer, cancel: Cancelable) { + super.init(observer: observer, cancel: cancel) + } + + func run(_ source: Observable) -> Disposable { + let subscription = source.subscribe(self) + self.subscriptions.setDisposable(subscription) + return Disposables.create(subscriptions, innerSubscription) + } + + func performMap(_ element: SourceType) throws -> Source { + rxAbstractMethod() + } + + @inline(__always) + final private func nextElementArrived(element: Element) -> (Int, Observable)? { + self.lock.lock(); defer { self.lock.unlock() } + + do { + let observable = try self.performMap(element).asObservable() + self.hasLatest = true + self.latest = self.latest &+ 1 + return (self.latest, observable) + } + catch let error { + self.forwardOn(.error(error)) + self.dispose() + } + + return nil + } + + func on(_ event: Event) { + switch event { + case .next(let element): + if let (latest, observable) = self.nextElementArrived(element: element) { + let d = SingleAssignmentDisposable() + self.innerSubscription.disposable = d + + let observer = SwitchSinkIter(parent: self, id: latest, this: d) + let disposable = observable.subscribe(observer) + d.setDisposable(disposable) + } + case .error(let error): + self.lock.lock(); defer { self.lock.unlock() } + self.forwardOn(.error(error)) + self.dispose() + case .completed: + self.lock.lock(); defer { self.lock.unlock() } + self.stopped = true + + self.subscriptions.dispose() + + if !self.hasLatest { + self.forwardOn(.completed) + self.dispose() + } + } + } +} + +final private class SwitchSinkIter + : ObserverType + , LockOwnerType + , SynchronizedOnType where Source.Element == Observer.Element { + typealias Element = Source.Element + typealias Parent = SwitchSink + + private let parent: Parent + private let id: Int + private let this: Disposable + + var lock: RecursiveLock { + self.parent.lock + } + + init(parent: Parent, id: Int, this: Disposable) { + self.parent = parent + self.id = id + self.this = this + } + + func on(_ event: Event) { + self.synchronizedOn(event) + } + + func synchronized_on(_ event: Event) { + switch event { + case .next: break + case .error, .completed: + self.this.dispose() + } + + if self.parent.latest != self.id { + return + } + + switch event { + case .next: + self.parent.forwardOn(event) + case .error: + self.parent.forwardOn(event) + self.parent.dispose() + case .completed: + self.parent.hasLatest = false + if self.parent.stopped { + self.parent.forwardOn(event) + self.parent.dispose() + } + } + } +} + +// MARK: Specializations + +final private class SwitchIdentitySink: SwitchSink + where Observer.Element == Source.Element { + override init(observer: Observer, cancel: Cancelable) { + super.init(observer: observer, cancel: cancel) + } + + override func performMap(_ element: Source) throws -> Source { + element + } +} + +final private class MapSwitchSink: SwitchSink where Observer.Element == Source.Element { + typealias Selector = (SourceType) throws -> Source + + private let selector: Selector + + init(selector: @escaping Selector, observer: Observer, cancel: Cancelable) { + self.selector = selector + super.init(observer: observer, cancel: cancel) + } + + override func performMap(_ element: SourceType) throws -> Source { + try self.selector(element) + } +} + +// MARK: Producers + +final private class Switch: Producer { + private let source: Observable + + init(source: Observable) { + self.source = source + } + + override func run(_ observer: Observer, cancel: Cancelable) -> (sink: Disposable, subscription: Disposable) where Observer.Element == Source.Element { + let sink = SwitchIdentitySink(observer: observer, cancel: cancel) + let subscription = sink.run(self.source) + return (sink: sink, subscription: subscription) + } +} + +final private class FlatMapLatest: Producer { + typealias Selector = (SourceType) throws -> Source + + private let source: Observable + private let selector: Selector + + init(source: Observable, selector: @escaping Selector) { + self.source = source + self.selector = selector + } + + override func run(_ observer: Observer, cancel: Cancelable) -> (sink: Disposable, subscription: Disposable) where Observer.Element == Source.Element { + let sink = MapSwitchSink(selector: self.selector, observer: observer, cancel: cancel) + let subscription = sink.run(self.source) + return (sink: sink, subscription: subscription) + } +} diff --git a/Pods/RxSwift/RxSwift/Observables/SwitchIfEmpty.swift b/Pods/RxSwift/RxSwift/Observables/SwitchIfEmpty.swift new file mode 100644 index 0000000..037bf69 --- /dev/null +++ b/Pods/RxSwift/RxSwift/Observables/SwitchIfEmpty.swift @@ -0,0 +1,104 @@ +// +// SwitchIfEmpty.swift +// RxSwift +// +// Created by sergdort on 23/12/2016. +// Copyright © 2016 Krunoslav Zaher. All rights reserved. +// + +extension ObservableType { + /** + Returns the elements of the specified sequence or `switchTo` sequence if the sequence is empty. + + - seealso: [DefaultIfEmpty operator on reactivex.io](http://reactivex.io/documentation/operators/defaultifempty.html) + + - parameter other: Observable sequence being returned when source sequence is empty. + - returns: Observable sequence that contains elements from switchTo sequence if source is empty, otherwise returns source sequence elements. + */ + public func ifEmpty(switchTo other: Observable) -> Observable { + SwitchIfEmpty(source: self.asObservable(), ifEmpty: other) + } +} + +final private class SwitchIfEmpty: Producer { + + private let source: Observable + private let ifEmpty: Observable + + init(source: Observable, ifEmpty: Observable) { + self.source = source + self.ifEmpty = ifEmpty + } + + override func run(_ observer: Observer, cancel: Cancelable) -> (sink: Disposable, subscription: Disposable) where Observer.Element == Element { + let sink = SwitchIfEmptySink(ifEmpty: self.ifEmpty, + observer: observer, + cancel: cancel) + let subscription = sink.run(self.source.asObservable()) + + return (sink: sink, subscription: subscription) + } +} + +final private class SwitchIfEmptySink: Sink + , ObserverType { + typealias Element = Observer.Element + + private let ifEmpty: Observable + private var isEmpty = true + private let ifEmptySubscription = SingleAssignmentDisposable() + + init(ifEmpty: Observable, observer: Observer, cancel: Cancelable) { + self.ifEmpty = ifEmpty + super.init(observer: observer, cancel: cancel) + } + + func run(_ source: Observable) -> Disposable { + let subscription = source.subscribe(self) + return Disposables.create(subscription, ifEmptySubscription) + } + + func on(_ event: Event) { + switch event { + case .next: + self.isEmpty = false + self.forwardOn(event) + case .error: + self.forwardOn(event) + self.dispose() + case .completed: + guard self.isEmpty else { + self.forwardOn(.completed) + self.dispose() + return + } + let ifEmptySink = SwitchIfEmptySinkIter(parent: self) + self.ifEmptySubscription.setDisposable(self.ifEmpty.subscribe(ifEmptySink)) + } + } +} + +final private class SwitchIfEmptySinkIter + : ObserverType { + typealias Element = Observer.Element + typealias Parent = SwitchIfEmptySink + + private let parent: Parent + + init(parent: Parent) { + self.parent = parent + } + + func on(_ event: Event) { + switch event { + case .next: + self.parent.forwardOn(event) + case .error: + self.parent.forwardOn(event) + self.parent.dispose() + case .completed: + self.parent.forwardOn(event) + self.parent.dispose() + } + } +} diff --git a/Pods/RxSwift/RxSwift/Observables/Take.swift b/Pods/RxSwift/RxSwift/Observables/Take.swift new file mode 100644 index 0000000..e574688 --- /dev/null +++ b/Pods/RxSwift/RxSwift/Observables/Take.swift @@ -0,0 +1,193 @@ +// +// Take.swift +// RxSwift +// +// Created by Krunoslav Zaher on 6/12/15. +// Copyright © 2015 Krunoslav Zaher. All rights reserved. +// + +extension ObservableType { + + /** + Returns a specified number of contiguous elements from the start of an observable sequence. + + - seealso: [take operator on reactivex.io](http://reactivex.io/documentation/operators/take.html) + + - parameter count: The number of elements to return. + - returns: An observable sequence that contains the specified number of elements from the start of the input sequence. + */ + public func take(_ count: Int) + -> Observable { + if count == 0 { + return Observable.empty() + } + else { + return TakeCount(source: self.asObservable(), count: count) + } + } +} + +extension ObservableType { + /** + Takes elements for the specified duration from the start of the observable source sequence, using the specified scheduler to run timers. + + - seealso: [take operator on reactivex.io](http://reactivex.io/documentation/operators/take.html) + + - parameter duration: Duration for taking elements from the start of the sequence. + - parameter scheduler: Scheduler to run the timer on. + - returns: An observable sequence with the elements taken during the specified duration from the start of the source sequence. + */ + public func take(for duration: RxTimeInterval, scheduler: SchedulerType) + -> Observable { + TakeTime(source: self.asObservable(), duration: duration, scheduler: scheduler) + } + + /** + Takes elements for the specified duration from the start of the observable source sequence, using the specified scheduler to run timers. + + - seealso: [take operator on reactivex.io](http://reactivex.io/documentation/operators/take.html) + + - parameter duration: Duration for taking elements from the start of the sequence. + - parameter scheduler: Scheduler to run the timer on. + - returns: An observable sequence with the elements taken during the specified duration from the start of the source sequence. + */ + @available(*, deprecated, renamed: "take(for:scheduler:)") + public func take(_ duration: RxTimeInterval, scheduler: SchedulerType) + -> Observable { + take(for: duration, scheduler: scheduler) + } +} + +// count version + +final private class TakeCountSink: Sink, ObserverType { + typealias Element = Observer.Element + typealias Parent = TakeCount + + private let parent: Parent + + private var remaining: Int + + init(parent: Parent, observer: Observer, cancel: Cancelable) { + self.parent = parent + self.remaining = parent.count + super.init(observer: observer, cancel: cancel) + } + + func on(_ event: Event) { + switch event { + case .next(let value): + + if self.remaining > 0 { + self.remaining -= 1 + + self.forwardOn(.next(value)) + + if self.remaining == 0 { + self.forwardOn(.completed) + self.dispose() + } + } + case .error: + self.forwardOn(event) + self.dispose() + case .completed: + self.forwardOn(event) + self.dispose() + } + } + +} + +final private class TakeCount: Producer { + private let source: Observable + fileprivate let count: Int + + init(source: Observable, count: Int) { + if count < 0 { + rxFatalError("count can't be negative") + } + self.source = source + self.count = count + } + + override func run(_ observer: Observer, cancel: Cancelable) -> (sink: Disposable, subscription: Disposable) where Observer.Element == Element { + let sink = TakeCountSink(parent: self, observer: observer, cancel: cancel) + let subscription = self.source.subscribe(sink) + return (sink: sink, subscription: subscription) + } +} + +// time version + +final private class TakeTimeSink + : Sink + , LockOwnerType + , ObserverType + , SynchronizedOnType where Observer.Element == Element { + typealias Parent = TakeTime + + private let parent: Parent + + let lock = RecursiveLock() + + init(parent: Parent, observer: Observer, cancel: Cancelable) { + self.parent = parent + super.init(observer: observer, cancel: cancel) + } + + func on(_ event: Event) { + self.synchronizedOn(event) + } + + func synchronized_on(_ event: Event) { + switch event { + case .next(let value): + self.forwardOn(.next(value)) + case .error: + self.forwardOn(event) + self.dispose() + case .completed: + self.forwardOn(event) + self.dispose() + } + } + + func tick() { + self.lock.performLocked { + self.forwardOn(.completed) + self.dispose() + } + } + + func run() -> Disposable { + let disposeTimer = self.parent.scheduler.scheduleRelative((), dueTime: self.parent.duration) { _ in + self.tick() + return Disposables.create() + } + + let disposeSubscription = self.parent.source.subscribe(self) + + return Disposables.create(disposeTimer, disposeSubscription) + } +} + +final private class TakeTime: Producer { + typealias TimeInterval = RxTimeInterval + + fileprivate let source: Observable + fileprivate let duration: TimeInterval + fileprivate let scheduler: SchedulerType + + init(source: Observable, duration: TimeInterval, scheduler: SchedulerType) { + self.source = source + self.scheduler = scheduler + self.duration = duration + } + + override func run(_ observer: Observer, cancel: Cancelable) -> (sink: Disposable, subscription: Disposable) where Observer.Element == Element { + let sink = TakeTimeSink(parent: self, observer: observer, cancel: cancel) + let subscription = sink.run() + return (sink: sink, subscription: subscription) + } +} diff --git a/Pods/RxSwift/RxSwift/Observables/TakeLast.swift b/Pods/RxSwift/RxSwift/Observables/TakeLast.swift new file mode 100644 index 0000000..9183387 --- /dev/null +++ b/Pods/RxSwift/RxSwift/Observables/TakeLast.swift @@ -0,0 +1,78 @@ +// +// TakeLast.swift +// RxSwift +// +// Created by Tomi Koskinen on 25/10/15. +// Copyright © 2015 Krunoslav Zaher. All rights reserved. +// + +extension ObservableType { + + /** + Returns a specified number of contiguous elements from the end of an observable sequence. + + This operator accumulates a buffer with a length enough to store elements count elements. Upon completion of the source sequence, this buffer is drained on the result sequence. This causes the elements to be delayed. + + - seealso: [takeLast operator on reactivex.io](http://reactivex.io/documentation/operators/takelast.html) + + - parameter count: Number of elements to take from the end of the source sequence. + - returns: An observable sequence containing the specified number of elements from the end of the source sequence. + */ + public func takeLast(_ count: Int) + -> Observable { + TakeLast(source: self.asObservable(), count: count) + } +} + +final private class TakeLastSink: Sink, ObserverType { + typealias Element = Observer.Element + typealias Parent = TakeLast + + private let parent: Parent + + private var elements: Queue + + init(parent: Parent, observer: Observer, cancel: Cancelable) { + self.parent = parent + self.elements = Queue(capacity: parent.count + 1) + super.init(observer: observer, cancel: cancel) + } + + func on(_ event: Event) { + switch event { + case .next(let value): + self.elements.enqueue(value) + if self.elements.count > self.parent.count { + _ = self.elements.dequeue() + } + case .error: + self.forwardOn(event) + self.dispose() + case .completed: + for e in self.elements { + self.forwardOn(.next(e)) + } + self.forwardOn(.completed) + self.dispose() + } + } +} + +final private class TakeLast: Producer { + private let source: Observable + fileprivate let count: Int + + init(source: Observable, count: Int) { + if count < 0 { + rxFatalError("count can't be negative") + } + self.source = source + self.count = count + } + + override func run(_ observer: Observer, cancel: Cancelable) -> (sink: Disposable, subscription: Disposable) where Observer.Element == Element { + let sink = TakeLastSink(parent: self, observer: observer, cancel: cancel) + let subscription = self.source.subscribe(sink) + return (sink: sink, subscription: subscription) + } +} diff --git a/Pods/RxSwift/RxSwift/Observables/TakeWithPredicate.swift b/Pods/RxSwift/RxSwift/Observables/TakeWithPredicate.swift new file mode 100644 index 0000000..6c28d19 --- /dev/null +++ b/Pods/RxSwift/RxSwift/Observables/TakeWithPredicate.swift @@ -0,0 +1,285 @@ +// +// TakeWithPredicate.swift +// RxSwift +// +// Created by Krunoslav Zaher on 6/7/15. +// Copyright © 2015 Krunoslav Zaher. All rights reserved. +// + +extension ObservableType { + /** + Returns the elements from the source observable sequence until the other observable sequence produces an element. + + - seealso: [takeUntil operator on reactivex.io](http://reactivex.io/documentation/operators/takeuntil.html) + + - parameter other: Observable sequence that terminates propagation of elements of the source sequence. + - returns: An observable sequence containing the elements of the source sequence up to the point the other sequence interrupted further propagation. + */ + public func take(until other: Source) + -> Observable { + TakeUntil(source: self.asObservable(), other: other.asObservable()) + } + + /** + Returns elements from an observable sequence until the specified condition is true. + + - seealso: [takeUntil operator on reactivex.io](http://reactivex.io/documentation/operators/takeuntil.html) + + - parameter predicate: A function to test each element for a condition. + - parameter behavior: Whether or not to include the last element matching the predicate. Defaults to `exclusive`. + + - returns: An observable sequence that contains the elements from the input sequence that occur before the element at which the test passes. + */ + public func take(until predicate: @escaping (Element) throws -> Bool, + behavior: TakeBehavior = .exclusive) + -> Observable { + TakeUntilPredicate(source: self.asObservable(), + behavior: behavior, + predicate: predicate) + } + + /** + Returns elements from an observable sequence as long as a specified condition is true. + + - seealso: [takeWhile operator on reactivex.io](http://reactivex.io/documentation/operators/takewhile.html) + + - parameter predicate: A function to test each element for a condition. + - returns: An observable sequence that contains the elements from the input sequence that occur before the element at which the test no longer passes. + */ + public func take(while predicate: @escaping (Element) throws -> Bool, + behavior: TakeBehavior = .exclusive) + -> Observable { + take(until: { try !predicate($0) }, behavior: behavior) + } + + /** + Returns the elements from the source observable sequence until the other observable sequence produces an element. + + - seealso: [takeUntil operator on reactivex.io](http://reactivex.io/documentation/operators/takeuntil.html) + + - parameter other: Observable sequence that terminates propagation of elements of the source sequence. + - returns: An observable sequence containing the elements of the source sequence up to the point the other sequence interrupted further propagation. + */ + @available(*, deprecated, renamed: "take(until:)") + public func takeUntil(_ other: Source) + -> Observable { + take(until: other) + } + + /** + Returns elements from an observable sequence until the specified condition is true. + + - seealso: [takeUntil operator on reactivex.io](http://reactivex.io/documentation/operators/takeuntil.html) + + - parameter behavior: Whether or not to include the last element matching the predicate. + - parameter predicate: A function to test each element for a condition. + - returns: An observable sequence that contains the elements from the input sequence that occur before the element at which the test passes. + */ + @available(*, deprecated, renamed: "take(until:behavior:)") + public func takeUntil(_ behavior: TakeBehavior, + predicate: @escaping (Element) throws -> Bool) + -> Observable { + take(until: predicate, behavior: behavior) + } + + /** + Returns elements from an observable sequence as long as a specified condition is true. + + - seealso: [takeWhile operator on reactivex.io](http://reactivex.io/documentation/operators/takewhile.html) + + - parameter predicate: A function to test each element for a condition. + - returns: An observable sequence that contains the elements from the input sequence that occur before the element at which the test no longer passes. + */ + @available(*, deprecated, renamed: "take(while:)") + public func takeWhile(_ predicate: @escaping (Element) throws -> Bool) + -> Observable { + take(until: { try !predicate($0) }, behavior: .exclusive) + } +} + +/// Behaviors for the take operator family. +public enum TakeBehavior { + /// Include the last element matching the predicate. + case inclusive + + /// Exclude the last element matching the predicate. + case exclusive +} + +// MARK: - TakeUntil Observable +final private class TakeUntilSinkOther + : ObserverType + , LockOwnerType + , SynchronizedOnType { + typealias Parent = TakeUntilSink + typealias Element = Other + + private let parent: Parent + + var lock: RecursiveLock { + self.parent.lock + } + + fileprivate let subscription = SingleAssignmentDisposable() + + init(parent: Parent) { + self.parent = parent +#if TRACE_RESOURCES + _ = Resources.incrementTotal() +#endif + } + + func on(_ event: Event) { + self.synchronizedOn(event) + } + + func synchronized_on(_ event: Event) { + switch event { + case .next: + self.parent.forwardOn(.completed) + self.parent.dispose() + case .error(let e): + self.parent.forwardOn(.error(e)) + self.parent.dispose() + case .completed: + self.subscription.dispose() + } + } + +#if TRACE_RESOURCES + deinit { + _ = Resources.decrementTotal() + } +#endif +} + +final private class TakeUntilSink + : Sink + , LockOwnerType + , ObserverType + , SynchronizedOnType { + typealias Element = Observer.Element + typealias Parent = TakeUntil + + private let parent: Parent + + let lock = RecursiveLock() + + + init(parent: Parent, observer: Observer, cancel: Cancelable) { + self.parent = parent + super.init(observer: observer, cancel: cancel) + } + + func on(_ event: Event) { + self.synchronizedOn(event) + } + + func synchronized_on(_ event: Event) { + switch event { + case .next: + self.forwardOn(event) + case .error: + self.forwardOn(event) + self.dispose() + case .completed: + self.forwardOn(event) + self.dispose() + } + } + + func run() -> Disposable { + let otherObserver = TakeUntilSinkOther(parent: self) + let otherSubscription = self.parent.other.subscribe(otherObserver) + otherObserver.subscription.setDisposable(otherSubscription) + let sourceSubscription = self.parent.source.subscribe(self) + + return Disposables.create(sourceSubscription, otherObserver.subscription) + } +} + +final private class TakeUntil: Producer { + + fileprivate let source: Observable + fileprivate let other: Observable + + init(source: Observable, other: Observable) { + self.source = source + self.other = other + } + + override func run(_ observer: Observer, cancel: Cancelable) -> (sink: Disposable, subscription: Disposable) where Observer.Element == Element { + let sink = TakeUntilSink(parent: self, observer: observer, cancel: cancel) + let subscription = sink.run() + return (sink: sink, subscription: subscription) + } +} + +// MARK: - TakeUntil Predicate +final private class TakeUntilPredicateSink + : Sink, ObserverType { + typealias Element = Observer.Element + typealias Parent = TakeUntilPredicate + + private let parent: Parent + private var running = true + + init(parent: Parent, observer: Observer, cancel: Cancelable) { + self.parent = parent + super.init(observer: observer, cancel: cancel) + } + + func on(_ event: Event) { + switch event { + case .next(let value): + if !self.running { + return + } + + do { + self.running = try !self.parent.predicate(value) + } catch let e { + self.forwardOn(.error(e)) + self.dispose() + return + } + + if self.running { + self.forwardOn(.next(value)) + } else { + if self.parent.behavior == .inclusive { + self.forwardOn(.next(value)) + } + + self.forwardOn(.completed) + self.dispose() + } + case .error, .completed: + self.forwardOn(event) + self.dispose() + } + } + +} + +final private class TakeUntilPredicate: Producer { + typealias Predicate = (Element) throws -> Bool + + private let source: Observable + fileprivate let predicate: Predicate + fileprivate let behavior: TakeBehavior + + init(source: Observable, + behavior: TakeBehavior, + predicate: @escaping Predicate) { + self.source = source + self.behavior = behavior + self.predicate = predicate + } + + override func run(_ observer: Observer, cancel: Cancelable) -> (sink: Disposable, subscription: Disposable) where Observer.Element == Element { + let sink = TakeUntilPredicateSink(parent: self, observer: observer, cancel: cancel) + let subscription = self.source.subscribe(sink) + return (sink: sink, subscription: subscription) + } +} diff --git a/Pods/RxSwift/RxSwift/Observables/Throttle.swift b/Pods/RxSwift/RxSwift/Observables/Throttle.swift new file mode 100644 index 0000000..86152a8 --- /dev/null +++ b/Pods/RxSwift/RxSwift/Observables/Throttle.swift @@ -0,0 +1,160 @@ +// +// Throttle.swift +// RxSwift +// +// Created by Krunoslav Zaher on 3/22/15. +// Copyright © 2015 Krunoslav Zaher. All rights reserved. +// + +import Foundation + +extension ObservableType { + + /** + Returns an Observable that emits the first and the latest item emitted by the source Observable during sequential time windows of a specified duration. + + This operator makes sure that no two elements are emitted in less then dueTime. + + - seealso: [debounce operator on reactivex.io](http://reactivex.io/documentation/operators/debounce.html) + + - parameter dueTime: Throttling duration for each element. + - parameter latest: Should latest element received in a dueTime wide time window since last element emission be emitted. + - parameter scheduler: Scheduler to run the throttle timers on. + - returns: The throttled sequence. + */ + public func throttle(_ dueTime: RxTimeInterval, latest: Bool = true, scheduler: SchedulerType) + -> Observable { + Throttle(source: self.asObservable(), dueTime: dueTime, latest: latest, scheduler: scheduler) + } +} + +final private class ThrottleSink + : Sink + , ObserverType + , LockOwnerType + , SynchronizedOnType { + typealias Element = Observer.Element + typealias ParentType = Throttle + + private let parent: ParentType + + let lock = RecursiveLock() + + // state + private var lastUnsentElement: Element? + private var lastSentTime: Date? + private var completed: Bool = false + + let cancellable = SerialDisposable() + + init(parent: ParentType, observer: Observer, cancel: Cancelable) { + self.parent = parent + + super.init(observer: observer, cancel: cancel) + } + + func run() -> Disposable { + let subscription = self.parent.source.subscribe(self) + + return Disposables.create(subscription, cancellable) + } + + func on(_ event: Event) { + self.synchronizedOn(event) + } + + func synchronized_on(_ event: Event) { + switch event { + case .next(let element): + let now = self.parent.scheduler.now + + let reducedScheduledTime: RxTimeInterval + + if let lastSendingTime = self.lastSentTime { + reducedScheduledTime = self.parent.dueTime.reduceWithSpanBetween(earlierDate: lastSendingTime, laterDate: now) + } + else { + reducedScheduledTime = .nanoseconds(0) + } + + if reducedScheduledTime.isNow { + self.sendNow(element: element) + return + } + + if !self.parent.latest { + return + } + + let isThereAlreadyInFlightRequest = self.lastUnsentElement != nil + + self.lastUnsentElement = element + + if isThereAlreadyInFlightRequest { + return + } + + let scheduler = self.parent.scheduler + + let d = SingleAssignmentDisposable() + self.cancellable.disposable = d + + d.setDisposable(scheduler.scheduleRelative(0, dueTime: reducedScheduledTime, action: self.propagate)) + case .error: + self.lastUnsentElement = nil + self.forwardOn(event) + self.dispose() + case .completed: + if self.lastUnsentElement != nil { + self.completed = true + } + else { + self.forwardOn(.completed) + self.dispose() + } + } + } + + private func sendNow(element: Element) { + self.lastUnsentElement = nil + self.forwardOn(.next(element)) + // in case element processing takes a while, this should give some more room + self.lastSentTime = self.parent.scheduler.now + } + + func propagate(_: Int) -> Disposable { + self.lock.performLocked { + if let lastUnsentElement = self.lastUnsentElement { + self.sendNow(element: lastUnsentElement) + } + + if self.completed { + self.forwardOn(.completed) + self.dispose() + } + } + + return Disposables.create() + } +} + +final private class Throttle: Producer { + fileprivate let source: Observable + fileprivate let dueTime: RxTimeInterval + fileprivate let latest: Bool + fileprivate let scheduler: SchedulerType + + init(source: Observable, dueTime: RxTimeInterval, latest: Bool, scheduler: SchedulerType) { + self.source = source + self.dueTime = dueTime + self.latest = latest + self.scheduler = scheduler + } + + override func run(_ observer: Observer, cancel: Cancelable) -> (sink: Disposable, subscription: Disposable) where Observer.Element == Element { + let sink = ThrottleSink(parent: self, observer: observer, cancel: cancel) + let subscription = sink.run() + return (sink: sink, subscription: subscription) + } + +} diff --git a/Pods/RxSwift/RxSwift/Observables/Timeout.swift b/Pods/RxSwift/RxSwift/Observables/Timeout.swift new file mode 100644 index 0000000..efcc791 --- /dev/null +++ b/Pods/RxSwift/RxSwift/Observables/Timeout.swift @@ -0,0 +1,151 @@ +// +// Timeout.swift +// RxSwift +// +// Created by Tomi Koskinen on 13/11/15. +// Copyright © 2015 Krunoslav Zaher. All rights reserved. +// + +extension ObservableType { + + /** + Applies a timeout policy for each element in the observable sequence. If the next element isn't received within the specified timeout duration starting from its predecessor, a TimeoutError is propagated to the observer. + + - seealso: [timeout operator on reactivex.io](http://reactivex.io/documentation/operators/timeout.html) + + - parameter dueTime: Maximum duration between values before a timeout occurs. + - parameter scheduler: Scheduler to run the timeout timer on. + - returns: An observable sequence with a `RxError.timeout` in case of a timeout. + */ + public func timeout(_ dueTime: RxTimeInterval, scheduler: SchedulerType) + -> Observable { + return Timeout(source: self.asObservable(), dueTime: dueTime, other: Observable.error(RxError.timeout), scheduler: scheduler) + } + + /** + Applies a timeout policy for each element in the observable sequence, using the specified scheduler to run timeout timers. If the next element isn't received within the specified timeout duration starting from its predecessor, the other observable sequence is used to produce future messages from that point on. + + - seealso: [timeout operator on reactivex.io](http://reactivex.io/documentation/operators/timeout.html) + + - parameter dueTime: Maximum duration between values before a timeout occurs. + - parameter other: Sequence to return in case of a timeout. + - parameter scheduler: Scheduler to run the timeout timer on. + - returns: The source sequence switching to the other sequence in case of a timeout. + */ + public func timeout(_ dueTime: RxTimeInterval, other: Source, scheduler: SchedulerType) + -> Observable where Element == Source.Element { + return Timeout(source: self.asObservable(), dueTime: dueTime, other: other.asObservable(), scheduler: scheduler) + } +} + +final private class TimeoutSink: Sink, LockOwnerType, ObserverType { + typealias Element = Observer.Element + typealias Parent = Timeout + + private let parent: Parent + + let lock = RecursiveLock() + + private let timerD = SerialDisposable() + private let subscription = SerialDisposable() + + private var id = 0 + private var switched = false + + init(parent: Parent, observer: Observer, cancel: Cancelable) { + self.parent = parent + super.init(observer: observer, cancel: cancel) + } + + func run() -> Disposable { + let original = SingleAssignmentDisposable() + self.subscription.disposable = original + + self.createTimeoutTimer() + + original.setDisposable(self.parent.source.subscribe(self)) + + return Disposables.create(subscription, timerD) + } + + func on(_ event: Event) { + switch event { + case .next: + var onNextWins = false + + self.lock.performLocked { + onNextWins = !self.switched + if onNextWins { + self.id = self.id &+ 1 + } + } + + if onNextWins { + self.forwardOn(event) + self.createTimeoutTimer() + } + case .error, .completed: + var onEventWins = false + + self.lock.performLocked { + onEventWins = !self.switched + if onEventWins { + self.id = self.id &+ 1 + } + } + + if onEventWins { + self.forwardOn(event) + self.dispose() + } + } + } + + private func createTimeoutTimer() { + if self.timerD.isDisposed { + return + } + + let nextTimer = SingleAssignmentDisposable() + self.timerD.disposable = nextTimer + + let disposeSchedule = self.parent.scheduler.scheduleRelative(self.id, dueTime: self.parent.dueTime) { state in + + var timerWins = false + + self.lock.performLocked { + self.switched = (state == self.id) + timerWins = self.switched + } + + if timerWins { + self.subscription.disposable = self.parent.other.subscribe(self.forwarder()) + } + + return Disposables.create() + } + + nextTimer.setDisposable(disposeSchedule) + } +} + + +final private class Timeout: Producer { + fileprivate let source: Observable + fileprivate let dueTime: RxTimeInterval + fileprivate let other: Observable + fileprivate let scheduler: SchedulerType + + init(source: Observable, dueTime: RxTimeInterval, other: Observable, scheduler: SchedulerType) { + self.source = source + self.dueTime = dueTime + self.other = other + self.scheduler = scheduler + } + + override func run(_ observer: Observer, cancel: Cancelable) -> (sink: Disposable, subscription: Disposable) where Observer.Element == Element { + let sink = TimeoutSink(parent: self, observer: observer, cancel: cancel) + let subscription = sink.run() + return (sink: sink, subscription: subscription) + } +} diff --git a/Pods/RxSwift/RxSwift/Observables/Timer.swift b/Pods/RxSwift/RxSwift/Observables/Timer.swift new file mode 100644 index 0000000..30bbdf6 --- /dev/null +++ b/Pods/RxSwift/RxSwift/Observables/Timer.swift @@ -0,0 +1,117 @@ +// +// Timer.swift +// RxSwift +// +// Created by Krunoslav Zaher on 6/7/15. +// Copyright © 2015 Krunoslav Zaher. All rights reserved. +// + +extension ObservableType where Element: RxAbstractInteger { + /** + Returns an observable sequence that produces a value after each period, using the specified scheduler to run timers and to send out observer messages. + + - seealso: [interval operator on reactivex.io](http://reactivex.io/documentation/operators/interval.html) + + - parameter period: Period for producing the values in the resulting sequence. + - parameter scheduler: Scheduler to run the timer on. + - returns: An observable sequence that produces a value after each period. + */ + public static func interval(_ period: RxTimeInterval, scheduler: SchedulerType) + -> Observable { + return Timer( + dueTime: period, + period: period, + scheduler: scheduler + ) + } +} + +extension ObservableType where Element: RxAbstractInteger { + /** + Returns an observable sequence that periodically produces a value after the specified initial relative due time has elapsed, using the specified scheduler to run timers. + + - seealso: [timer operator on reactivex.io](http://reactivex.io/documentation/operators/timer.html) + + - parameter dueTime: Relative time at which to produce the first value. + - parameter period: Period to produce subsequent values. + - parameter scheduler: Scheduler to run timers on. + - returns: An observable sequence that produces a value after due time has elapsed and then each period. + */ + public static func timer(_ dueTime: RxTimeInterval, period: RxTimeInterval? = nil, scheduler: SchedulerType) + -> Observable { + return Timer( + dueTime: dueTime, + period: period, + scheduler: scheduler + ) + } +} + +import Foundation + +final private class TimerSink : Sink where Observer.Element : RxAbstractInteger { + typealias Parent = Timer + + private let parent: Parent + private let lock = RecursiveLock() + + init(parent: Parent, observer: Observer, cancel: Cancelable) { + self.parent = parent + super.init(observer: observer, cancel: cancel) + } + + func run() -> Disposable { + return self.parent.scheduler.schedulePeriodic(0 as Observer.Element, startAfter: self.parent.dueTime, period: self.parent.period!) { state in + self.lock.performLocked { + self.forwardOn(.next(state)) + return state &+ 1 + } + } + } +} + +final private class TimerOneOffSink: Sink where Observer.Element: RxAbstractInteger { + typealias Parent = Timer + + private let parent: Parent + + init(parent: Parent, observer: Observer, cancel: Cancelable) { + self.parent = parent + super.init(observer: observer, cancel: cancel) + } + + func run() -> Disposable { + return self.parent.scheduler.scheduleRelative(self, dueTime: self.parent.dueTime) { [unowned self] _ -> Disposable in + self.forwardOn(.next(0)) + self.forwardOn(.completed) + self.dispose() + + return Disposables.create() + } + } +} + +final private class Timer: Producer { + fileprivate let scheduler: SchedulerType + fileprivate let dueTime: RxTimeInterval + fileprivate let period: RxTimeInterval? + + init(dueTime: RxTimeInterval, period: RxTimeInterval?, scheduler: SchedulerType) { + self.scheduler = scheduler + self.dueTime = dueTime + self.period = period + } + + override func run(_ observer: Observer, cancel: Cancelable) -> (sink: Disposable, subscription: Disposable) where Observer.Element == Element { + if self.period != nil { + let sink = TimerSink(parent: self, observer: observer, cancel: cancel) + let subscription = sink.run() + return (sink: sink, subscription: subscription) + } + else { + let sink = TimerOneOffSink(parent: self, observer: observer, cancel: cancel) + let subscription = sink.run() + return (sink: sink, subscription: subscription) + } + } +} diff --git a/Pods/RxSwift/RxSwift/Observables/ToArray.swift b/Pods/RxSwift/RxSwift/Observables/ToArray.swift new file mode 100644 index 0000000..76c7370 --- /dev/null +++ b/Pods/RxSwift/RxSwift/Observables/ToArray.swift @@ -0,0 +1,64 @@ +// +// ToArray.swift +// RxSwift +// +// Created by Junior B. on 20/10/15. +// Copyright © 2015 Krunoslav Zaher. All rights reserved. +// + +extension ObservableType { + /** + Converts an Observable into a Single that emits the whole sequence as a single array and then terminates. + + For aggregation behavior see `reduce`. + + - seealso: [toArray operator on reactivex.io](http://reactivex.io/documentation/operators/to.html) + + - returns: A Single sequence containing all the emitted elements as array. + */ + public func toArray() + -> Single<[Element]> { + PrimitiveSequence(raw: ToArray(source: self.asObservable())) + } +} + +final private class ToArraySink: Sink, ObserverType where Observer.Element == [SourceType] { + typealias Parent = ToArray + + let parent: Parent + var list = [SourceType]() + + init(parent: Parent, observer: Observer, cancel: Cancelable) { + self.parent = parent + + super.init(observer: observer, cancel: cancel) + } + + func on(_ event: Event) { + switch event { + case .next(let value): + self.list.append(value) + case .error(let e): + self.forwardOn(.error(e)) + self.dispose() + case .completed: + self.forwardOn(.next(self.list)) + self.forwardOn(.completed) + self.dispose() + } + } +} + +final private class ToArray: Producer<[SourceType]> { + let source: Observable + + init(source: Observable) { + self.source = source + } + + override func run(_ observer: Observer, cancel: Cancelable) -> (sink: Disposable, subscription: Disposable) where Observer.Element == [SourceType] { + let sink = ToArraySink(parent: self, observer: observer, cancel: cancel) + let subscription = self.source.subscribe(sink) + return (sink: sink, subscription: subscription) + } +} diff --git a/Pods/RxSwift/RxSwift/Observables/Using.swift b/Pods/RxSwift/RxSwift/Observables/Using.swift new file mode 100644 index 0000000..ca48d2f --- /dev/null +++ b/Pods/RxSwift/RxSwift/Observables/Using.swift @@ -0,0 +1,90 @@ +// +// Using.swift +// RxSwift +// +// Created by Yury Korolev on 10/15/15. +// Copyright © 2015 Krunoslav Zaher. All rights reserved. +// + +extension ObservableType { + /** + Constructs an observable sequence that depends on a resource object, whose lifetime is tied to the resulting observable sequence's lifetime. + + - seealso: [using operator on reactivex.io](http://reactivex.io/documentation/operators/using.html) + + - parameter resourceFactory: Factory function to obtain a resource object. + - parameter observableFactory: Factory function to obtain an observable sequence that depends on the obtained resource. + - returns: An observable sequence whose lifetime controls the lifetime of the dependent resource object. + */ + public static func using(_ resourceFactory: @escaping () throws -> Resource, observableFactory: @escaping (Resource) throws -> Observable) -> Observable { + Using(resourceFactory: resourceFactory, observableFactory: observableFactory) + } +} + +final private class UsingSink: Sink, ObserverType { + typealias SourceType = Observer.Element + typealias Parent = Using + + private let parent: Parent + + init(parent: Parent, observer: Observer, cancel: Cancelable) { + self.parent = parent + super.init(observer: observer, cancel: cancel) + } + + func run() -> Disposable { + var disposable = Disposables.create() + + do { + let resource = try self.parent.resourceFactory() + disposable = resource + let source = try self.parent.observableFactory(resource) + + return Disposables.create( + source.subscribe(self), + disposable + ) + } catch let error { + return Disposables.create( + Observable.error(error).subscribe(self), + disposable + ) + } + } + + func on(_ event: Event) { + switch event { + case let .next(value): + self.forwardOn(.next(value)) + case let .error(error): + self.forwardOn(.error(error)) + self.dispose() + case .completed: + self.forwardOn(.completed) + self.dispose() + } + } +} + +final private class Using: Producer { + + typealias Element = SourceType + + typealias ResourceFactory = () throws -> ResourceType + typealias ObservableFactory = (ResourceType) throws -> Observable + + fileprivate let resourceFactory: ResourceFactory + fileprivate let observableFactory: ObservableFactory + + + init(resourceFactory: @escaping ResourceFactory, observableFactory: @escaping ObservableFactory) { + self.resourceFactory = resourceFactory + self.observableFactory = observableFactory + } + + override func run(_ observer: Observer, cancel: Cancelable) -> (sink: Disposable, subscription: Disposable) where Observer.Element == Element { + let sink = UsingSink(parent: self, observer: observer, cancel: cancel) + let subscription = sink.run() + return (sink: sink, subscription: subscription) + } +} diff --git a/Pods/RxSwift/RxSwift/Observables/Window.swift b/Pods/RxSwift/RxSwift/Observables/Window.swift new file mode 100644 index 0000000..b2a37a5 --- /dev/null +++ b/Pods/RxSwift/RxSwift/Observables/Window.swift @@ -0,0 +1,168 @@ +// +// Window.swift +// RxSwift +// +// Created by Junior B. on 29/10/15. +// Copyright © 2015 Krunoslav Zaher. All rights reserved. +// + +extension ObservableType { + + /** + Projects each element of an observable sequence into a window that is completed when either it’s full or a given amount of time has elapsed. + + - seealso: [window operator on reactivex.io](http://reactivex.io/documentation/operators/window.html) + + - parameter timeSpan: Maximum time length of a window. + - parameter count: Maximum element count of a window. + - parameter scheduler: Scheduler to run windowing timers on. + - returns: An observable sequence of windows (instances of `Observable`). + */ + public func window(timeSpan: RxTimeInterval, count: Int, scheduler: SchedulerType) + -> Observable> { + return WindowTimeCount(source: self.asObservable(), timeSpan: timeSpan, count: count, scheduler: scheduler) + } +} + +final private class WindowTimeCountSink + : Sink + , ObserverType + , LockOwnerType + , SynchronizedOnType where Observer.Element == Observable { + typealias Parent = WindowTimeCount + + private let parent: Parent + + let lock = RecursiveLock() + + private var subject = PublishSubject() + private var count = 0 + private var windowId = 0 + + private let timerD = SerialDisposable() + private let refCountDisposable: RefCountDisposable + private let groupDisposable = CompositeDisposable() + + init(parent: Parent, observer: Observer, cancel: Cancelable) { + self.parent = parent + + _ = self.groupDisposable.insert(self.timerD) + + self.refCountDisposable = RefCountDisposable(disposable: self.groupDisposable) + super.init(observer: observer, cancel: cancel) + } + + func run() -> Disposable { + + self.forwardOn(.next(AddRef(source: self.subject, refCount: self.refCountDisposable).asObservable())) + self.createTimer(self.windowId) + + _ = self.groupDisposable.insert(self.parent.source.subscribe(self)) + return self.refCountDisposable + } + + func startNewWindowAndCompleteCurrentOne() { + self.subject.on(.completed) + self.subject = PublishSubject() + + self.forwardOn(.next(AddRef(source: self.subject, refCount: self.refCountDisposable).asObservable())) + } + + func on(_ event: Event) { + self.synchronizedOn(event) + } + + func synchronized_on(_ event: Event) { + var newWindow = false + var newId = 0 + + switch event { + case .next(let element): + self.subject.on(.next(element)) + + do { + _ = try incrementChecked(&self.count) + } catch let e { + self.subject.on(.error(e as Swift.Error)) + self.dispose() + } + + if self.count == self.parent.count { + newWindow = true + self.count = 0 + self.windowId += 1 + newId = self.windowId + self.startNewWindowAndCompleteCurrentOne() + } + + case .error(let error): + self.subject.on(.error(error)) + self.forwardOn(.error(error)) + self.dispose() + case .completed: + self.subject.on(.completed) + self.forwardOn(.completed) + self.dispose() + } + + if newWindow { + self.createTimer(newId) + } + } + + func createTimer(_ windowId: Int) { + if self.timerD.isDisposed { + return + } + + if self.windowId != windowId { + return + } + + let nextTimer = SingleAssignmentDisposable() + + self.timerD.disposable = nextTimer + + let scheduledRelative = self.parent.scheduler.scheduleRelative(windowId, dueTime: self.parent.timeSpan) { previousWindowId in + + var newId = 0 + + self.lock.performLocked { + if previousWindowId != self.windowId { + return + } + + self.count = 0 + self.windowId = self.windowId &+ 1 + newId = self.windowId + self.startNewWindowAndCompleteCurrentOne() + } + + self.createTimer(newId) + + return Disposables.create() + } + + nextTimer.setDisposable(scheduledRelative) + } +} + +final private class WindowTimeCount: Producer> { + fileprivate let timeSpan: RxTimeInterval + fileprivate let count: Int + fileprivate let scheduler: SchedulerType + fileprivate let source: Observable + + init(source: Observable, timeSpan: RxTimeInterval, count: Int, scheduler: SchedulerType) { + self.source = source + self.timeSpan = timeSpan + self.count = count + self.scheduler = scheduler + } + + override func run(_ observer: Observer, cancel: Cancelable) -> (sink: Disposable, subscription: Disposable) where Observer.Element == Observable { + let sink = WindowTimeCountSink(parent: self, observer: observer, cancel: cancel) + let subscription = sink.run() + return (sink: sink, subscription: subscription) + } +} diff --git a/Pods/RxSwift/RxSwift/Observables/WithLatestFrom.swift b/Pods/RxSwift/RxSwift/Observables/WithLatestFrom.swift new file mode 100644 index 0000000..d286812 --- /dev/null +++ b/Pods/RxSwift/RxSwift/Observables/WithLatestFrom.swift @@ -0,0 +1,151 @@ +// +// WithLatestFrom.swift +// RxSwift +// +// Created by Yury Korolev on 10/19/15. +// Copyright © 2015 Krunoslav Zaher. All rights reserved. +// + +extension ObservableType { + + /** + Merges two observable sequences into one observable sequence by combining each element from self with the latest element from the second source, if any. + + - seealso: [combineLatest operator on reactivex.io](http://reactivex.io/documentation/operators/combinelatest.html) + - note: Elements emitted by self before the second source has emitted any values will be omitted. + + - parameter second: Second observable source. + - parameter resultSelector: Function to invoke for each element from the self combined with the latest element from the second source, if any. + - returns: An observable sequence containing the result of combining each element of the self with the latest element from the second source, if any, using the specified result selector function. + */ + public func withLatestFrom(_ second: Source, resultSelector: @escaping (Element, Source.Element) throws -> ResultType) -> Observable { + WithLatestFrom(first: self.asObservable(), second: second.asObservable(), resultSelector: resultSelector) + } + + /** + Merges two observable sequences into one observable sequence by using latest element from the second sequence every time when `self` emits an element. + + - seealso: [combineLatest operator on reactivex.io](http://reactivex.io/documentation/operators/combinelatest.html) + - note: Elements emitted by self before the second source has emitted any values will be omitted. + + - parameter second: Second observable source. + - returns: An observable sequence containing the result of combining each element of the self with the latest element from the second source, if any, using the specified result selector function. + */ + public func withLatestFrom(_ second: Source) -> Observable { + WithLatestFrom(first: self.asObservable(), second: second.asObservable(), resultSelector: { $1 }) + } +} + +final private class WithLatestFromSink + : Sink + , ObserverType + , LockOwnerType + , SynchronizedOnType { + typealias ResultType = Observer.Element + typealias Parent = WithLatestFrom + typealias Element = FirstType + + private let parent: Parent + + fileprivate var lock = RecursiveLock() + fileprivate var latest: SecondType? + + init(parent: Parent, observer: Observer, cancel: Cancelable) { + self.parent = parent + + super.init(observer: observer, cancel: cancel) + } + + func run() -> Disposable { + let sndSubscription = SingleAssignmentDisposable() + let sndO = WithLatestFromSecond(parent: self, disposable: sndSubscription) + + sndSubscription.setDisposable(self.parent.second.subscribe(sndO)) + let fstSubscription = self.parent.first.subscribe(self) + + return Disposables.create(fstSubscription, sndSubscription) + } + + func on(_ event: Event) { + self.synchronizedOn(event) + } + + func synchronized_on(_ event: Event) { + switch event { + case let .next(value): + guard let latest = self.latest else { return } + do { + let res = try self.parent.resultSelector(value, latest) + + self.forwardOn(.next(res)) + } catch let e { + self.forwardOn(.error(e)) + self.dispose() + } + case .completed: + self.forwardOn(.completed) + self.dispose() + case let .error(error): + self.forwardOn(.error(error)) + self.dispose() + } + } +} + +final private class WithLatestFromSecond + : ObserverType + , LockOwnerType + , SynchronizedOnType { + + typealias ResultType = Observer.Element + typealias Parent = WithLatestFromSink + typealias Element = SecondType + + private let parent: Parent + private let disposable: Disposable + + var lock: RecursiveLock { + self.parent.lock + } + + init(parent: Parent, disposable: Disposable) { + self.parent = parent + self.disposable = disposable + } + + func on(_ event: Event) { + self.synchronizedOn(event) + } + + func synchronized_on(_ event: Event) { + switch event { + case let .next(value): + self.parent.latest = value + case .completed: + self.disposable.dispose() + case let .error(error): + self.parent.forwardOn(.error(error)) + self.parent.dispose() + } + } +} + +final private class WithLatestFrom: Producer { + typealias ResultSelector = (FirstType, SecondType) throws -> ResultType + + fileprivate let first: Observable + fileprivate let second: Observable + fileprivate let resultSelector: ResultSelector + + init(first: Observable, second: Observable, resultSelector: @escaping ResultSelector) { + self.first = first + self.second = second + self.resultSelector = resultSelector + } + + override func run(_ observer: Observer, cancel: Cancelable) -> (sink: Disposable, subscription: Disposable) where Observer.Element == ResultType { + let sink = WithLatestFromSink(parent: self, observer: observer, cancel: cancel) + let subscription = sink.run() + return (sink: sink, subscription: subscription) + } +} diff --git a/Pods/RxSwift/RxSwift/Observables/WithUnretained.swift b/Pods/RxSwift/RxSwift/Observables/WithUnretained.swift new file mode 100644 index 0000000..076f6de --- /dev/null +++ b/Pods/RxSwift/RxSwift/Observables/WithUnretained.swift @@ -0,0 +1,58 @@ +// +// WithUnretained.swift +// RxSwift +// +// Created by Vincent Pradeilles on 01/01/2021. +// Copyright © 2020 Krunoslav Zaher. All rights reserved. +// + +extension ObservableType { + /** + Provides an unretained, safe to use (i.e. not implicitly unwrapped), reference to an object along with the events emitted by the sequence. + + In the case the provided object cannot be retained successfully, the sequence will complete. + + - note: Be careful when using this operator in a sequence that has a buffer or replay, for example `share(replay: 1)`, as the sharing buffer will also include the provided object, which could potentially cause a retain cycle. + + - parameter obj: The object to provide an unretained reference on. + - parameter resultSelector: A function to combine the unretained referenced on `obj` and the value of the observable sequence. + - returns: An observable sequence that contains the result of `resultSelector` being called with an unretained reference on `obj` and the values of the original sequence. + */ + public func withUnretained( + _ obj: Object, + resultSelector: @escaping (Object, Element) -> Out + ) -> Observable { + map { [weak obj] element -> Out in + guard let obj = obj else { throw UnretainedError.failedRetaining } + + return resultSelector(obj, element) + } + .catch{ error -> Observable in + guard let unretainedError = error as? UnretainedError, + unretainedError == .failedRetaining else { + return .error(error) + } + + return .empty() + } + } + + + /** + Provides an unretained, safe to use (i.e. not implicitly unwrapped), reference to an object along with the events emitted by the sequence. + + In the case the provided object cannot be retained successfully, the sequence will complete. + + - note: Be careful when using this operator in a sequence that has a buffer or replay, for example `share(replay: 1)`, as the sharing buffer will also include the provided object, which could potentially cause a retain cycle. + + - parameter obj: The object to provide an unretained reference on. + - returns: An observable sequence of tuples that contains both an unretained reference on `obj` and the values of the original sequence. + */ + public func withUnretained(_ obj: Object) -> Observable<(Object, Element)> { + return withUnretained(obj) { ($0, $1) } + } +} + +private enum UnretainedError: Swift.Error { + case failedRetaining +} diff --git a/Pods/RxSwift/RxSwift/Observables/Zip+Collection.swift b/Pods/RxSwift/RxSwift/Observables/Zip+Collection.swift new file mode 100644 index 0000000..2d7f887 --- /dev/null +++ b/Pods/RxSwift/RxSwift/Observables/Zip+Collection.swift @@ -0,0 +1,168 @@ +// +// Zip+Collection.swift +// RxSwift +// +// Created by Krunoslav Zaher on 8/30/15. +// Copyright © 2015 Krunoslav Zaher. All rights reserved. +// + +extension ObservableType { + /** + Merges the specified observable sequences into one observable sequence by using the selector function whenever all of the observable sequences have produced an element at a corresponding index. + + - seealso: [zip operator on reactivex.io](http://reactivex.io/documentation/operators/zip.html) + + - parameter resultSelector: Function to invoke for each series of elements at corresponding indexes in the sources. + - returns: An observable sequence containing the result of combining elements of the sources using the specified result selector function. + */ + public static func zip(_ collection: Collection, resultSelector: @escaping ([Collection.Element.Element]) throws -> Element) -> Observable + where Collection.Element: ObservableType { + ZipCollectionType(sources: collection, resultSelector: resultSelector) + } + + /** + Merges the specified observable sequences into one observable sequence whenever all of the observable sequences have produced an element at a corresponding index. + + - seealso: [zip operator on reactivex.io](http://reactivex.io/documentation/operators/zip.html) + + - returns: An observable sequence containing the result of combining elements of the sources. + */ + public static func zip(_ collection: Collection) -> Observable<[Element]> + where Collection.Element: ObservableType, Collection.Element.Element == Element { + ZipCollectionType(sources: collection, resultSelector: { $0 }) + } + +} + +final private class ZipCollectionTypeSink + : Sink where Collection.Element: ObservableConvertibleType { + typealias Result = Observer.Element + typealias Parent = ZipCollectionType + typealias SourceElement = Collection.Element.Element + + private let parent: Parent + + private let lock = RecursiveLock() + + // state + private var numberOfValues = 0 + private var values: [Queue] + private var isDone: [Bool] + private var numberOfDone = 0 + private var subscriptions: [SingleAssignmentDisposable] + + init(parent: Parent, observer: Observer, cancel: Cancelable) { + self.parent = parent + self.values = [Queue](repeating: Queue(capacity: 4), count: parent.count) + self.isDone = [Bool](repeating: false, count: parent.count) + self.subscriptions = [SingleAssignmentDisposable]() + self.subscriptions.reserveCapacity(parent.count) + + for _ in 0 ..< parent.count { + self.subscriptions.append(SingleAssignmentDisposable()) + } + + super.init(observer: observer, cancel: cancel) + } + + func on(_ event: Event, atIndex: Int) { + self.lock.lock(); defer { self.lock.unlock() } + switch event { + case .next(let element): + self.values[atIndex].enqueue(element) + + if self.values[atIndex].count == 1 { + self.numberOfValues += 1 + } + + if self.numberOfValues < self.parent.count { + if self.numberOfDone == self.parent.count - 1 { + self.forwardOn(.completed) + self.dispose() + } + return + } + + do { + var arguments = [SourceElement]() + arguments.reserveCapacity(self.parent.count) + + // recalculate number of values + self.numberOfValues = 0 + + for i in 0 ..< self.values.count { + arguments.append(self.values[i].dequeue()!) + if !self.values[i].isEmpty { + self.numberOfValues += 1 + } + } + + let result = try self.parent.resultSelector(arguments) + self.forwardOn(.next(result)) + } + catch let error { + self.forwardOn(.error(error)) + self.dispose() + } + + case .error(let error): + self.forwardOn(.error(error)) + self.dispose() + case .completed: + if self.isDone[atIndex] { + return + } + + self.isDone[atIndex] = true + self.numberOfDone += 1 + + if self.numberOfDone == self.parent.count { + self.forwardOn(.completed) + self.dispose() + } + else { + self.subscriptions[atIndex].dispose() + } + } + } + + func run() -> Disposable { + var j = 0 + for i in self.parent.sources { + let index = j + let source = i.asObservable() + + let disposable = source.subscribe(AnyObserver { event in + self.on(event, atIndex: index) + }) + self.subscriptions[j].setDisposable(disposable) + j += 1 + } + + if self.parent.sources.isEmpty { + self.forwardOn(.completed) + } + + return Disposables.create(subscriptions) + } +} + +final private class ZipCollectionType: Producer where Collection.Element: ObservableConvertibleType { + typealias ResultSelector = ([Collection.Element.Element]) throws -> Result + + let sources: Collection + let resultSelector: ResultSelector + let count: Int + + init(sources: Collection, resultSelector: @escaping ResultSelector) { + self.sources = sources + self.resultSelector = resultSelector + self.count = self.sources.count + } + + override func run(_ observer: Observer, cancel: Cancelable) -> (sink: Disposable, subscription: Disposable) where Observer.Element == Result { + let sink = ZipCollectionTypeSink(parent: self, observer: observer, cancel: cancel) + let subscription = sink.run() + return (sink: sink, subscription: subscription) + } +} diff --git a/Pods/RxSwift/RxSwift/Observables/Zip+arity.swift b/Pods/RxSwift/RxSwift/Observables/Zip+arity.swift new file mode 100644 index 0000000..b6d876d --- /dev/null +++ b/Pods/RxSwift/RxSwift/Observables/Zip+arity.swift @@ -0,0 +1,934 @@ +// This file is autogenerated. Take a look at `Preprocessor` target in RxSwift project +// +// Zip+arity.swift +// RxSwift +// +// Created by Krunoslav Zaher on 5/23/15. +// Copyright © 2015 Krunoslav Zaher. All rights reserved. +// + + + +// 2 + +extension ObservableType { + /** + Merges the specified observable sequences into one observable sequence by using the selector function whenever all of the observable sequences have produced an element at a corresponding index. + + - seealso: [zip operator on reactivex.io](http://reactivex.io/documentation/operators/zip.html) + + - parameter resultSelector: Function to invoke for each series of elements at corresponding indexes in the sources. + - returns: An observable sequence containing the result of combining elements of the sources using the specified result selector function. + */ + public static func zip + (_ source1: O1, _ source2: O2, resultSelector: @escaping (O1.Element, O2.Element) throws -> Element) + -> Observable { + return Zip2( + source1: source1.asObservable(), source2: source2.asObservable(), + resultSelector: resultSelector + ) + } +} + +extension ObservableType where Element == Any { + /** + Merges the specified observable sequences into one observable sequence of tuples whenever all of the observable sequences have produced an element at a corresponding index. + + - seealso: [zip operator on reactivex.io](http://reactivex.io/documentation/operators/zip.html) + + - returns: An observable sequence containing the result of combining elements of the sources. + */ + public static func zip + (_ source1: O1, _ source2: O2) + -> Observable<(O1.Element, O2.Element)> { + return Zip2( + source1: source1.asObservable(), source2: source2.asObservable(), + resultSelector: { ($0, $1) } + ) + } +} + +final class ZipSink2_ : ZipSink { + typealias Result = Observer.Element + typealias Parent = Zip2 + + let parent: Parent + + var values1: Queue = Queue(capacity: 2) + var values2: Queue = Queue(capacity: 2) + + init(parent: Parent, observer: Observer, cancel: Cancelable) { + self.parent = parent + super.init(arity: 2, observer: observer, cancel: cancel) + } + + override func hasElements(_ index: Int) -> Bool { + switch index { + case 0: return !self.values1.isEmpty + case 1: return !self.values2.isEmpty + + default: + rxFatalError("Unhandled case (Function)") + } + } + + func run() -> Disposable { + let subscription1 = SingleAssignmentDisposable() + let subscription2 = SingleAssignmentDisposable() + + let observer1 = ZipObserver(lock: self.lock, parent: self, index: 0, setNextValue: { self.values1.enqueue($0) }, this: subscription1) + let observer2 = ZipObserver(lock: self.lock, parent: self, index: 1, setNextValue: { self.values2.enqueue($0) }, this: subscription2) + + subscription1.setDisposable(self.parent.source1.subscribe(observer1)) + subscription2.setDisposable(self.parent.source2.subscribe(observer2)) + + return Disposables.create([ + subscription1, + subscription2 + ]) + } + + override func getResult() throws -> Result { + try self.parent.resultSelector(self.values1.dequeue()!, self.values2.dequeue()!) + } +} + +final class Zip2 : Producer { + typealias ResultSelector = (E1, E2) throws -> Result + + let source1: Observable + let source2: Observable + + let resultSelector: ResultSelector + + init(source1: Observable, source2: Observable, resultSelector: @escaping ResultSelector) { + self.source1 = source1 + self.source2 = source2 + + self.resultSelector = resultSelector + } + + override func run(_ observer: Observer, cancel: Cancelable) -> (sink: Disposable, subscription: Disposable) where Observer.Element == Result { + let sink = ZipSink2_(parent: self, observer: observer, cancel: cancel) + let subscription = sink.run() + return (sink: sink, subscription: subscription) + } +} + + + +// 3 + +extension ObservableType { + /** + Merges the specified observable sequences into one observable sequence by using the selector function whenever all of the observable sequences have produced an element at a corresponding index. + + - seealso: [zip operator on reactivex.io](http://reactivex.io/documentation/operators/zip.html) + + - parameter resultSelector: Function to invoke for each series of elements at corresponding indexes in the sources. + - returns: An observable sequence containing the result of combining elements of the sources using the specified result selector function. + */ + public static func zip + (_ source1: O1, _ source2: O2, _ source3: O3, resultSelector: @escaping (O1.Element, O2.Element, O3.Element) throws -> Element) + -> Observable { + return Zip3( + source1: source1.asObservable(), source2: source2.asObservable(), source3: source3.asObservable(), + resultSelector: resultSelector + ) + } +} + +extension ObservableType where Element == Any { + /** + Merges the specified observable sequences into one observable sequence of tuples whenever all of the observable sequences have produced an element at a corresponding index. + + - seealso: [zip operator on reactivex.io](http://reactivex.io/documentation/operators/zip.html) + + - returns: An observable sequence containing the result of combining elements of the sources. + */ + public static func zip + (_ source1: O1, _ source2: O2, _ source3: O3) + -> Observable<(O1.Element, O2.Element, O3.Element)> { + return Zip3( + source1: source1.asObservable(), source2: source2.asObservable(), source3: source3.asObservable(), + resultSelector: { ($0, $1, $2) } + ) + } +} + +final class ZipSink3_ : ZipSink { + typealias Result = Observer.Element + typealias Parent = Zip3 + + let parent: Parent + + var values1: Queue = Queue(capacity: 2) + var values2: Queue = Queue(capacity: 2) + var values3: Queue = Queue(capacity: 2) + + init(parent: Parent, observer: Observer, cancel: Cancelable) { + self.parent = parent + super.init(arity: 3, observer: observer, cancel: cancel) + } + + override func hasElements(_ index: Int) -> Bool { + switch index { + case 0: return !self.values1.isEmpty + case 1: return !self.values2.isEmpty + case 2: return !self.values3.isEmpty + + default: + rxFatalError("Unhandled case (Function)") + } + } + + func run() -> Disposable { + let subscription1 = SingleAssignmentDisposable() + let subscription2 = SingleAssignmentDisposable() + let subscription3 = SingleAssignmentDisposable() + + let observer1 = ZipObserver(lock: self.lock, parent: self, index: 0, setNextValue: { self.values1.enqueue($0) }, this: subscription1) + let observer2 = ZipObserver(lock: self.lock, parent: self, index: 1, setNextValue: { self.values2.enqueue($0) }, this: subscription2) + let observer3 = ZipObserver(lock: self.lock, parent: self, index: 2, setNextValue: { self.values3.enqueue($0) }, this: subscription3) + + subscription1.setDisposable(self.parent.source1.subscribe(observer1)) + subscription2.setDisposable(self.parent.source2.subscribe(observer2)) + subscription3.setDisposable(self.parent.source3.subscribe(observer3)) + + return Disposables.create([ + subscription1, + subscription2, + subscription3 + ]) + } + + override func getResult() throws -> Result { + try self.parent.resultSelector(self.values1.dequeue()!, self.values2.dequeue()!, self.values3.dequeue()!) + } +} + +final class Zip3 : Producer { + typealias ResultSelector = (E1, E2, E3) throws -> Result + + let source1: Observable + let source2: Observable + let source3: Observable + + let resultSelector: ResultSelector + + init(source1: Observable, source2: Observable, source3: Observable, resultSelector: @escaping ResultSelector) { + self.source1 = source1 + self.source2 = source2 + self.source3 = source3 + + self.resultSelector = resultSelector + } + + override func run(_ observer: Observer, cancel: Cancelable) -> (sink: Disposable, subscription: Disposable) where Observer.Element == Result { + let sink = ZipSink3_(parent: self, observer: observer, cancel: cancel) + let subscription = sink.run() + return (sink: sink, subscription: subscription) + } +} + + + +// 4 + +extension ObservableType { + /** + Merges the specified observable sequences into one observable sequence by using the selector function whenever all of the observable sequences have produced an element at a corresponding index. + + - seealso: [zip operator on reactivex.io](http://reactivex.io/documentation/operators/zip.html) + + - parameter resultSelector: Function to invoke for each series of elements at corresponding indexes in the sources. + - returns: An observable sequence containing the result of combining elements of the sources using the specified result selector function. + */ + public static func zip + (_ source1: O1, _ source2: O2, _ source3: O3, _ source4: O4, resultSelector: @escaping (O1.Element, O2.Element, O3.Element, O4.Element) throws -> Element) + -> Observable { + return Zip4( + source1: source1.asObservable(), source2: source2.asObservable(), source3: source3.asObservable(), source4: source4.asObservable(), + resultSelector: resultSelector + ) + } +} + +extension ObservableType where Element == Any { + /** + Merges the specified observable sequences into one observable sequence of tuples whenever all of the observable sequences have produced an element at a corresponding index. + + - seealso: [zip operator on reactivex.io](http://reactivex.io/documentation/operators/zip.html) + + - returns: An observable sequence containing the result of combining elements of the sources. + */ + public static func zip + (_ source1: O1, _ source2: O2, _ source3: O3, _ source4: O4) + -> Observable<(O1.Element, O2.Element, O3.Element, O4.Element)> { + return Zip4( + source1: source1.asObservable(), source2: source2.asObservable(), source3: source3.asObservable(), source4: source4.asObservable(), + resultSelector: { ($0, $1, $2, $3) } + ) + } +} + +final class ZipSink4_ : ZipSink { + typealias Result = Observer.Element + typealias Parent = Zip4 + + let parent: Parent + + var values1: Queue = Queue(capacity: 2) + var values2: Queue = Queue(capacity: 2) + var values3: Queue = Queue(capacity: 2) + var values4: Queue = Queue(capacity: 2) + + init(parent: Parent, observer: Observer, cancel: Cancelable) { + self.parent = parent + super.init(arity: 4, observer: observer, cancel: cancel) + } + + override func hasElements(_ index: Int) -> Bool { + switch index { + case 0: return !self.values1.isEmpty + case 1: return !self.values2.isEmpty + case 2: return !self.values3.isEmpty + case 3: return !self.values4.isEmpty + + default: + rxFatalError("Unhandled case (Function)") + } + } + + func run() -> Disposable { + let subscription1 = SingleAssignmentDisposable() + let subscription2 = SingleAssignmentDisposable() + let subscription3 = SingleAssignmentDisposable() + let subscription4 = SingleAssignmentDisposable() + + let observer1 = ZipObserver(lock: self.lock, parent: self, index: 0, setNextValue: { self.values1.enqueue($0) }, this: subscription1) + let observer2 = ZipObserver(lock: self.lock, parent: self, index: 1, setNextValue: { self.values2.enqueue($0) }, this: subscription2) + let observer3 = ZipObserver(lock: self.lock, parent: self, index: 2, setNextValue: { self.values3.enqueue($0) }, this: subscription3) + let observer4 = ZipObserver(lock: self.lock, parent: self, index: 3, setNextValue: { self.values4.enqueue($0) }, this: subscription4) + + subscription1.setDisposable(self.parent.source1.subscribe(observer1)) + subscription2.setDisposable(self.parent.source2.subscribe(observer2)) + subscription3.setDisposable(self.parent.source3.subscribe(observer3)) + subscription4.setDisposable(self.parent.source4.subscribe(observer4)) + + return Disposables.create([ + subscription1, + subscription2, + subscription3, + subscription4 + ]) + } + + override func getResult() throws -> Result { + try self.parent.resultSelector(self.values1.dequeue()!, self.values2.dequeue()!, self.values3.dequeue()!, self.values4.dequeue()!) + } +} + +final class Zip4 : Producer { + typealias ResultSelector = (E1, E2, E3, E4) throws -> Result + + let source1: Observable + let source2: Observable + let source3: Observable + let source4: Observable + + let resultSelector: ResultSelector + + init(source1: Observable, source2: Observable, source3: Observable, source4: Observable, resultSelector: @escaping ResultSelector) { + self.source1 = source1 + self.source2 = source2 + self.source3 = source3 + self.source4 = source4 + + self.resultSelector = resultSelector + } + + override func run(_ observer: Observer, cancel: Cancelable) -> (sink: Disposable, subscription: Disposable) where Observer.Element == Result { + let sink = ZipSink4_(parent: self, observer: observer, cancel: cancel) + let subscription = sink.run() + return (sink: sink, subscription: subscription) + } +} + + + +// 5 + +extension ObservableType { + /** + Merges the specified observable sequences into one observable sequence by using the selector function whenever all of the observable sequences have produced an element at a corresponding index. + + - seealso: [zip operator on reactivex.io](http://reactivex.io/documentation/operators/zip.html) + + - parameter resultSelector: Function to invoke for each series of elements at corresponding indexes in the sources. + - returns: An observable sequence containing the result of combining elements of the sources using the specified result selector function. + */ + public static func zip + (_ source1: O1, _ source2: O2, _ source3: O3, _ source4: O4, _ source5: O5, resultSelector: @escaping (O1.Element, O2.Element, O3.Element, O4.Element, O5.Element) throws -> Element) + -> Observable { + return Zip5( + source1: source1.asObservable(), source2: source2.asObservable(), source3: source3.asObservable(), source4: source4.asObservable(), source5: source5.asObservable(), + resultSelector: resultSelector + ) + } +} + +extension ObservableType where Element == Any { + /** + Merges the specified observable sequences into one observable sequence of tuples whenever all of the observable sequences have produced an element at a corresponding index. + + - seealso: [zip operator on reactivex.io](http://reactivex.io/documentation/operators/zip.html) + + - returns: An observable sequence containing the result of combining elements of the sources. + */ + public static func zip + (_ source1: O1, _ source2: O2, _ source3: O3, _ source4: O4, _ source5: O5) + -> Observable<(O1.Element, O2.Element, O3.Element, O4.Element, O5.Element)> { + return Zip5( + source1: source1.asObservable(), source2: source2.asObservable(), source3: source3.asObservable(), source4: source4.asObservable(), source5: source5.asObservable(), + resultSelector: { ($0, $1, $2, $3, $4) } + ) + } +} + +final class ZipSink5_ : ZipSink { + typealias Result = Observer.Element + typealias Parent = Zip5 + + let parent: Parent + + var values1: Queue = Queue(capacity: 2) + var values2: Queue = Queue(capacity: 2) + var values3: Queue = Queue(capacity: 2) + var values4: Queue = Queue(capacity: 2) + var values5: Queue = Queue(capacity: 2) + + init(parent: Parent, observer: Observer, cancel: Cancelable) { + self.parent = parent + super.init(arity: 5, observer: observer, cancel: cancel) + } + + override func hasElements(_ index: Int) -> Bool { + switch index { + case 0: return !self.values1.isEmpty + case 1: return !self.values2.isEmpty + case 2: return !self.values3.isEmpty + case 3: return !self.values4.isEmpty + case 4: return !self.values5.isEmpty + + default: + rxFatalError("Unhandled case (Function)") + } + } + + func run() -> Disposable { + let subscription1 = SingleAssignmentDisposable() + let subscription2 = SingleAssignmentDisposable() + let subscription3 = SingleAssignmentDisposable() + let subscription4 = SingleAssignmentDisposable() + let subscription5 = SingleAssignmentDisposable() + + let observer1 = ZipObserver(lock: self.lock, parent: self, index: 0, setNextValue: { self.values1.enqueue($0) }, this: subscription1) + let observer2 = ZipObserver(lock: self.lock, parent: self, index: 1, setNextValue: { self.values2.enqueue($0) }, this: subscription2) + let observer3 = ZipObserver(lock: self.lock, parent: self, index: 2, setNextValue: { self.values3.enqueue($0) }, this: subscription3) + let observer4 = ZipObserver(lock: self.lock, parent: self, index: 3, setNextValue: { self.values4.enqueue($0) }, this: subscription4) + let observer5 = ZipObserver(lock: self.lock, parent: self, index: 4, setNextValue: { self.values5.enqueue($0) }, this: subscription5) + + subscription1.setDisposable(self.parent.source1.subscribe(observer1)) + subscription2.setDisposable(self.parent.source2.subscribe(observer2)) + subscription3.setDisposable(self.parent.source3.subscribe(observer3)) + subscription4.setDisposable(self.parent.source4.subscribe(observer4)) + subscription5.setDisposable(self.parent.source5.subscribe(observer5)) + + return Disposables.create([ + subscription1, + subscription2, + subscription3, + subscription4, + subscription5 + ]) + } + + override func getResult() throws -> Result { + try self.parent.resultSelector(self.values1.dequeue()!, self.values2.dequeue()!, self.values3.dequeue()!, self.values4.dequeue()!, self.values5.dequeue()!) + } +} + +final class Zip5 : Producer { + typealias ResultSelector = (E1, E2, E3, E4, E5) throws -> Result + + let source1: Observable + let source2: Observable + let source3: Observable + let source4: Observable + let source5: Observable + + let resultSelector: ResultSelector + + init(source1: Observable, source2: Observable, source3: Observable, source4: Observable, source5: Observable, resultSelector: @escaping ResultSelector) { + self.source1 = source1 + self.source2 = source2 + self.source3 = source3 + self.source4 = source4 + self.source5 = source5 + + self.resultSelector = resultSelector + } + + override func run(_ observer: Observer, cancel: Cancelable) -> (sink: Disposable, subscription: Disposable) where Observer.Element == Result { + let sink = ZipSink5_(parent: self, observer: observer, cancel: cancel) + let subscription = sink.run() + return (sink: sink, subscription: subscription) + } +} + + + +// 6 + +extension ObservableType { + /** + Merges the specified observable sequences into one observable sequence by using the selector function whenever all of the observable sequences have produced an element at a corresponding index. + + - seealso: [zip operator on reactivex.io](http://reactivex.io/documentation/operators/zip.html) + + - parameter resultSelector: Function to invoke for each series of elements at corresponding indexes in the sources. + - returns: An observable sequence containing the result of combining elements of the sources using the specified result selector function. + */ + public static func zip + (_ source1: O1, _ source2: O2, _ source3: O3, _ source4: O4, _ source5: O5, _ source6: O6, resultSelector: @escaping (O1.Element, O2.Element, O3.Element, O4.Element, O5.Element, O6.Element) throws -> Element) + -> Observable { + return Zip6( + source1: source1.asObservable(), source2: source2.asObservable(), source3: source3.asObservable(), source4: source4.asObservable(), source5: source5.asObservable(), source6: source6.asObservable(), + resultSelector: resultSelector + ) + } +} + +extension ObservableType where Element == Any { + /** + Merges the specified observable sequences into one observable sequence of tuples whenever all of the observable sequences have produced an element at a corresponding index. + + - seealso: [zip operator on reactivex.io](http://reactivex.io/documentation/operators/zip.html) + + - returns: An observable sequence containing the result of combining elements of the sources. + */ + public static func zip + (_ source1: O1, _ source2: O2, _ source3: O3, _ source4: O4, _ source5: O5, _ source6: O6) + -> Observable<(O1.Element, O2.Element, O3.Element, O4.Element, O5.Element, O6.Element)> { + return Zip6( + source1: source1.asObservable(), source2: source2.asObservable(), source3: source3.asObservable(), source4: source4.asObservable(), source5: source5.asObservable(), source6: source6.asObservable(), + resultSelector: { ($0, $1, $2, $3, $4, $5) } + ) + } +} + +final class ZipSink6_ : ZipSink { + typealias Result = Observer.Element + typealias Parent = Zip6 + + let parent: Parent + + var values1: Queue = Queue(capacity: 2) + var values2: Queue = Queue(capacity: 2) + var values3: Queue = Queue(capacity: 2) + var values4: Queue = Queue(capacity: 2) + var values5: Queue = Queue(capacity: 2) + var values6: Queue = Queue(capacity: 2) + + init(parent: Parent, observer: Observer, cancel: Cancelable) { + self.parent = parent + super.init(arity: 6, observer: observer, cancel: cancel) + } + + override func hasElements(_ index: Int) -> Bool { + switch index { + case 0: return !self.values1.isEmpty + case 1: return !self.values2.isEmpty + case 2: return !self.values3.isEmpty + case 3: return !self.values4.isEmpty + case 4: return !self.values5.isEmpty + case 5: return !self.values6.isEmpty + + default: + rxFatalError("Unhandled case (Function)") + } + } + + func run() -> Disposable { + let subscription1 = SingleAssignmentDisposable() + let subscription2 = SingleAssignmentDisposable() + let subscription3 = SingleAssignmentDisposable() + let subscription4 = SingleAssignmentDisposable() + let subscription5 = SingleAssignmentDisposable() + let subscription6 = SingleAssignmentDisposable() + + let observer1 = ZipObserver(lock: self.lock, parent: self, index: 0, setNextValue: { self.values1.enqueue($0) }, this: subscription1) + let observer2 = ZipObserver(lock: self.lock, parent: self, index: 1, setNextValue: { self.values2.enqueue($0) }, this: subscription2) + let observer3 = ZipObserver(lock: self.lock, parent: self, index: 2, setNextValue: { self.values3.enqueue($0) }, this: subscription3) + let observer4 = ZipObserver(lock: self.lock, parent: self, index: 3, setNextValue: { self.values4.enqueue($0) }, this: subscription4) + let observer5 = ZipObserver(lock: self.lock, parent: self, index: 4, setNextValue: { self.values5.enqueue($0) }, this: subscription5) + let observer6 = ZipObserver(lock: self.lock, parent: self, index: 5, setNextValue: { self.values6.enqueue($0) }, this: subscription6) + + subscription1.setDisposable(self.parent.source1.subscribe(observer1)) + subscription2.setDisposable(self.parent.source2.subscribe(observer2)) + subscription3.setDisposable(self.parent.source3.subscribe(observer3)) + subscription4.setDisposable(self.parent.source4.subscribe(observer4)) + subscription5.setDisposable(self.parent.source5.subscribe(observer5)) + subscription6.setDisposable(self.parent.source6.subscribe(observer6)) + + return Disposables.create([ + subscription1, + subscription2, + subscription3, + subscription4, + subscription5, + subscription6 + ]) + } + + override func getResult() throws -> Result { + try self.parent.resultSelector(self.values1.dequeue()!, self.values2.dequeue()!, self.values3.dequeue()!, self.values4.dequeue()!, self.values5.dequeue()!, self.values6.dequeue()!) + } +} + +final class Zip6 : Producer { + typealias ResultSelector = (E1, E2, E3, E4, E5, E6) throws -> Result + + let source1: Observable + let source2: Observable + let source3: Observable + let source4: Observable + let source5: Observable + let source6: Observable + + let resultSelector: ResultSelector + + init(source1: Observable, source2: Observable, source3: Observable, source4: Observable, source5: Observable, source6: Observable, resultSelector: @escaping ResultSelector) { + self.source1 = source1 + self.source2 = source2 + self.source3 = source3 + self.source4 = source4 + self.source5 = source5 + self.source6 = source6 + + self.resultSelector = resultSelector + } + + override func run(_ observer: Observer, cancel: Cancelable) -> (sink: Disposable, subscription: Disposable) where Observer.Element == Result { + let sink = ZipSink6_(parent: self, observer: observer, cancel: cancel) + let subscription = sink.run() + return (sink: sink, subscription: subscription) + } +} + + + +// 7 + +extension ObservableType { + /** + Merges the specified observable sequences into one observable sequence by using the selector function whenever all of the observable sequences have produced an element at a corresponding index. + + - seealso: [zip operator on reactivex.io](http://reactivex.io/documentation/operators/zip.html) + + - parameter resultSelector: Function to invoke for each series of elements at corresponding indexes in the sources. + - returns: An observable sequence containing the result of combining elements of the sources using the specified result selector function. + */ + public static func zip + (_ source1: O1, _ source2: O2, _ source3: O3, _ source4: O4, _ source5: O5, _ source6: O6, _ source7: O7, resultSelector: @escaping (O1.Element, O2.Element, O3.Element, O4.Element, O5.Element, O6.Element, O7.Element) throws -> Element) + -> Observable { + return Zip7( + source1: source1.asObservable(), source2: source2.asObservable(), source3: source3.asObservable(), source4: source4.asObservable(), source5: source5.asObservable(), source6: source6.asObservable(), source7: source7.asObservable(), + resultSelector: resultSelector + ) + } +} + +extension ObservableType where Element == Any { + /** + Merges the specified observable sequences into one observable sequence of tuples whenever all of the observable sequences have produced an element at a corresponding index. + + - seealso: [zip operator on reactivex.io](http://reactivex.io/documentation/operators/zip.html) + + - returns: An observable sequence containing the result of combining elements of the sources. + */ + public static func zip + (_ source1: O1, _ source2: O2, _ source3: O3, _ source4: O4, _ source5: O5, _ source6: O6, _ source7: O7) + -> Observable<(O1.Element, O2.Element, O3.Element, O4.Element, O5.Element, O6.Element, O7.Element)> { + return Zip7( + source1: source1.asObservable(), source2: source2.asObservable(), source3: source3.asObservable(), source4: source4.asObservable(), source5: source5.asObservable(), source6: source6.asObservable(), source7: source7.asObservable(), + resultSelector: { ($0, $1, $2, $3, $4, $5, $6) } + ) + } +} + +final class ZipSink7_ : ZipSink { + typealias Result = Observer.Element + typealias Parent = Zip7 + + let parent: Parent + + var values1: Queue = Queue(capacity: 2) + var values2: Queue = Queue(capacity: 2) + var values3: Queue = Queue(capacity: 2) + var values4: Queue = Queue(capacity: 2) + var values5: Queue = Queue(capacity: 2) + var values6: Queue = Queue(capacity: 2) + var values7: Queue = Queue(capacity: 2) + + init(parent: Parent, observer: Observer, cancel: Cancelable) { + self.parent = parent + super.init(arity: 7, observer: observer, cancel: cancel) + } + + override func hasElements(_ index: Int) -> Bool { + switch index { + case 0: return !self.values1.isEmpty + case 1: return !self.values2.isEmpty + case 2: return !self.values3.isEmpty + case 3: return !self.values4.isEmpty + case 4: return !self.values5.isEmpty + case 5: return !self.values6.isEmpty + case 6: return !self.values7.isEmpty + + default: + rxFatalError("Unhandled case (Function)") + } + } + + func run() -> Disposable { + let subscription1 = SingleAssignmentDisposable() + let subscription2 = SingleAssignmentDisposable() + let subscription3 = SingleAssignmentDisposable() + let subscription4 = SingleAssignmentDisposable() + let subscription5 = SingleAssignmentDisposable() + let subscription6 = SingleAssignmentDisposable() + let subscription7 = SingleAssignmentDisposable() + + let observer1 = ZipObserver(lock: self.lock, parent: self, index: 0, setNextValue: { self.values1.enqueue($0) }, this: subscription1) + let observer2 = ZipObserver(lock: self.lock, parent: self, index: 1, setNextValue: { self.values2.enqueue($0) }, this: subscription2) + let observer3 = ZipObserver(lock: self.lock, parent: self, index: 2, setNextValue: { self.values3.enqueue($0) }, this: subscription3) + let observer4 = ZipObserver(lock: self.lock, parent: self, index: 3, setNextValue: { self.values4.enqueue($0) }, this: subscription4) + let observer5 = ZipObserver(lock: self.lock, parent: self, index: 4, setNextValue: { self.values5.enqueue($0) }, this: subscription5) + let observer6 = ZipObserver(lock: self.lock, parent: self, index: 5, setNextValue: { self.values6.enqueue($0) }, this: subscription6) + let observer7 = ZipObserver(lock: self.lock, parent: self, index: 6, setNextValue: { self.values7.enqueue($0) }, this: subscription7) + + subscription1.setDisposable(self.parent.source1.subscribe(observer1)) + subscription2.setDisposable(self.parent.source2.subscribe(observer2)) + subscription3.setDisposable(self.parent.source3.subscribe(observer3)) + subscription4.setDisposable(self.parent.source4.subscribe(observer4)) + subscription5.setDisposable(self.parent.source5.subscribe(observer5)) + subscription6.setDisposable(self.parent.source6.subscribe(observer6)) + subscription7.setDisposable(self.parent.source7.subscribe(observer7)) + + return Disposables.create([ + subscription1, + subscription2, + subscription3, + subscription4, + subscription5, + subscription6, + subscription7 + ]) + } + + override func getResult() throws -> Result { + try self.parent.resultSelector(self.values1.dequeue()!, self.values2.dequeue()!, self.values3.dequeue()!, self.values4.dequeue()!, self.values5.dequeue()!, self.values6.dequeue()!, self.values7.dequeue()!) + } +} + +final class Zip7 : Producer { + typealias ResultSelector = (E1, E2, E3, E4, E5, E6, E7) throws -> Result + + let source1: Observable + let source2: Observable + let source3: Observable + let source4: Observable + let source5: Observable + let source6: Observable + let source7: Observable + + let resultSelector: ResultSelector + + init(source1: Observable, source2: Observable, source3: Observable, source4: Observable, source5: Observable, source6: Observable, source7: Observable, resultSelector: @escaping ResultSelector) { + self.source1 = source1 + self.source2 = source2 + self.source3 = source3 + self.source4 = source4 + self.source5 = source5 + self.source6 = source6 + self.source7 = source7 + + self.resultSelector = resultSelector + } + + override func run(_ observer: Observer, cancel: Cancelable) -> (sink: Disposable, subscription: Disposable) where Observer.Element == Result { + let sink = ZipSink7_(parent: self, observer: observer, cancel: cancel) + let subscription = sink.run() + return (sink: sink, subscription: subscription) + } +} + + + +// 8 + +extension ObservableType { + /** + Merges the specified observable sequences into one observable sequence by using the selector function whenever all of the observable sequences have produced an element at a corresponding index. + + - seealso: [zip operator on reactivex.io](http://reactivex.io/documentation/operators/zip.html) + + - parameter resultSelector: Function to invoke for each series of elements at corresponding indexes in the sources. + - returns: An observable sequence containing the result of combining elements of the sources using the specified result selector function. + */ + public static func zip + (_ source1: O1, _ source2: O2, _ source3: O3, _ source4: O4, _ source5: O5, _ source6: O6, _ source7: O7, _ source8: O8, resultSelector: @escaping (O1.Element, O2.Element, O3.Element, O4.Element, O5.Element, O6.Element, O7.Element, O8.Element) throws -> Element) + -> Observable { + return Zip8( + source1: source1.asObservable(), source2: source2.asObservable(), source3: source3.asObservable(), source4: source4.asObservable(), source5: source5.asObservable(), source6: source6.asObservable(), source7: source7.asObservable(), source8: source8.asObservable(), + resultSelector: resultSelector + ) + } +} + +extension ObservableType where Element == Any { + /** + Merges the specified observable sequences into one observable sequence of tuples whenever all of the observable sequences have produced an element at a corresponding index. + + - seealso: [zip operator on reactivex.io](http://reactivex.io/documentation/operators/zip.html) + + - returns: An observable sequence containing the result of combining elements of the sources. + */ + public static func zip + (_ source1: O1, _ source2: O2, _ source3: O3, _ source4: O4, _ source5: O5, _ source6: O6, _ source7: O7, _ source8: O8) + -> Observable<(O1.Element, O2.Element, O3.Element, O4.Element, O5.Element, O6.Element, O7.Element, O8.Element)> { + return Zip8( + source1: source1.asObservable(), source2: source2.asObservable(), source3: source3.asObservable(), source4: source4.asObservable(), source5: source5.asObservable(), source6: source6.asObservable(), source7: source7.asObservable(), source8: source8.asObservable(), + resultSelector: { ($0, $1, $2, $3, $4, $5, $6, $7) } + ) + } +} + +final class ZipSink8_ : ZipSink { + typealias Result = Observer.Element + typealias Parent = Zip8 + + let parent: Parent + + var values1: Queue = Queue(capacity: 2) + var values2: Queue = Queue(capacity: 2) + var values3: Queue = Queue(capacity: 2) + var values4: Queue = Queue(capacity: 2) + var values5: Queue = Queue(capacity: 2) + var values6: Queue = Queue(capacity: 2) + var values7: Queue = Queue(capacity: 2) + var values8: Queue = Queue(capacity: 2) + + init(parent: Parent, observer: Observer, cancel: Cancelable) { + self.parent = parent + super.init(arity: 8, observer: observer, cancel: cancel) + } + + override func hasElements(_ index: Int) -> Bool { + switch index { + case 0: return !self.values1.isEmpty + case 1: return !self.values2.isEmpty + case 2: return !self.values3.isEmpty + case 3: return !self.values4.isEmpty + case 4: return !self.values5.isEmpty + case 5: return !self.values6.isEmpty + case 6: return !self.values7.isEmpty + case 7: return !self.values8.isEmpty + + default: + rxFatalError("Unhandled case (Function)") + } + } + + func run() -> Disposable { + let subscription1 = SingleAssignmentDisposable() + let subscription2 = SingleAssignmentDisposable() + let subscription3 = SingleAssignmentDisposable() + let subscription4 = SingleAssignmentDisposable() + let subscription5 = SingleAssignmentDisposable() + let subscription6 = SingleAssignmentDisposable() + let subscription7 = SingleAssignmentDisposable() + let subscription8 = SingleAssignmentDisposable() + + let observer1 = ZipObserver(lock: self.lock, parent: self, index: 0, setNextValue: { self.values1.enqueue($0) }, this: subscription1) + let observer2 = ZipObserver(lock: self.lock, parent: self, index: 1, setNextValue: { self.values2.enqueue($0) }, this: subscription2) + let observer3 = ZipObserver(lock: self.lock, parent: self, index: 2, setNextValue: { self.values3.enqueue($0) }, this: subscription3) + let observer4 = ZipObserver(lock: self.lock, parent: self, index: 3, setNextValue: { self.values4.enqueue($0) }, this: subscription4) + let observer5 = ZipObserver(lock: self.lock, parent: self, index: 4, setNextValue: { self.values5.enqueue($0) }, this: subscription5) + let observer6 = ZipObserver(lock: self.lock, parent: self, index: 5, setNextValue: { self.values6.enqueue($0) }, this: subscription6) + let observer7 = ZipObserver(lock: self.lock, parent: self, index: 6, setNextValue: { self.values7.enqueue($0) }, this: subscription7) + let observer8 = ZipObserver(lock: self.lock, parent: self, index: 7, setNextValue: { self.values8.enqueue($0) }, this: subscription8) + + subscription1.setDisposable(self.parent.source1.subscribe(observer1)) + subscription2.setDisposable(self.parent.source2.subscribe(observer2)) + subscription3.setDisposable(self.parent.source3.subscribe(observer3)) + subscription4.setDisposable(self.parent.source4.subscribe(observer4)) + subscription5.setDisposable(self.parent.source5.subscribe(observer5)) + subscription6.setDisposable(self.parent.source6.subscribe(observer6)) + subscription7.setDisposable(self.parent.source7.subscribe(observer7)) + subscription8.setDisposable(self.parent.source8.subscribe(observer8)) + + return Disposables.create([ + subscription1, + subscription2, + subscription3, + subscription4, + subscription5, + subscription6, + subscription7, + subscription8 + ]) + } + + override func getResult() throws -> Result { + try self.parent.resultSelector(self.values1.dequeue()!, self.values2.dequeue()!, self.values3.dequeue()!, self.values4.dequeue()!, self.values5.dequeue()!, self.values6.dequeue()!, self.values7.dequeue()!, self.values8.dequeue()!) + } +} + +final class Zip8 : Producer { + typealias ResultSelector = (E1, E2, E3, E4, E5, E6, E7, E8) throws -> Result + + let source1: Observable + let source2: Observable + let source3: Observable + let source4: Observable + let source5: Observable + let source6: Observable + let source7: Observable + let source8: Observable + + let resultSelector: ResultSelector + + init(source1: Observable, source2: Observable, source3: Observable, source4: Observable, source5: Observable, source6: Observable, source7: Observable, source8: Observable, resultSelector: @escaping ResultSelector) { + self.source1 = source1 + self.source2 = source2 + self.source3 = source3 + self.source4 = source4 + self.source5 = source5 + self.source6 = source6 + self.source7 = source7 + self.source8 = source8 + + self.resultSelector = resultSelector + } + + override func run(_ observer: Observer, cancel: Cancelable) -> (sink: Disposable, subscription: Disposable) where Observer.Element == Result { + let sink = ZipSink8_(parent: self, observer: observer, cancel: cancel) + let subscription = sink.run() + return (sink: sink, subscription: subscription) + } +} + + diff --git a/Pods/RxSwift/RxSwift/Observables/Zip.swift b/Pods/RxSwift/RxSwift/Observables/Zip.swift new file mode 100644 index 0000000..328a40e --- /dev/null +++ b/Pods/RxSwift/RxSwift/Observables/Zip.swift @@ -0,0 +1,135 @@ +// +// Zip.swift +// RxSwift +// +// Created by Krunoslav Zaher on 5/23/15. +// Copyright © 2015 Krunoslav Zaher. All rights reserved. +// + +protocol ZipSinkProtocol: AnyObject { + func next(_ index: Int) + func fail(_ error: Swift.Error) + func done(_ index: Int) +} + +class ZipSink : Sink, ZipSinkProtocol { + typealias Element = Observer.Element + + let arity: Int + + let lock = RecursiveLock() + + // state + private var isDone: [Bool] + + init(arity: Int, observer: Observer, cancel: Cancelable) { + self.isDone = [Bool](repeating: false, count: arity) + self.arity = arity + + super.init(observer: observer, cancel: cancel) + } + + func getResult() throws -> Element { + rxAbstractMethod() + } + + func hasElements(_ index: Int) -> Bool { + rxAbstractMethod() + } + + func next(_ index: Int) { + var hasValueAll = true + + for i in 0 ..< self.arity { + if !self.hasElements(i) { + hasValueAll = false + break + } + } + + if hasValueAll { + do { + let result = try self.getResult() + self.forwardOn(.next(result)) + } + catch let e { + self.forwardOn(.error(e)) + self.dispose() + } + } + } + + func fail(_ error: Swift.Error) { + self.forwardOn(.error(error)) + self.dispose() + } + + func done(_ index: Int) { + self.isDone[index] = true + + var allDone = true + + for done in self.isDone where !done { + allDone = false + break + } + + if allDone { + self.forwardOn(.completed) + self.dispose() + } + } +} + +final class ZipObserver + : ObserverType + , LockOwnerType + , SynchronizedOnType { + typealias ValueSetter = (Element) -> Void + + private var parent: ZipSinkProtocol? + + let lock: RecursiveLock + + // state + private let index: Int + private let this: Disposable + private let setNextValue: ValueSetter + + init(lock: RecursiveLock, parent: ZipSinkProtocol, index: Int, setNextValue: @escaping ValueSetter, this: Disposable) { + self.lock = lock + self.parent = parent + self.index = index + self.this = this + self.setNextValue = setNextValue + } + + func on(_ event: Event) { + self.synchronizedOn(event) + } + + func synchronized_on(_ event: Event) { + if self.parent != nil { + switch event { + case .next: + break + case .error: + self.this.dispose() + case .completed: + self.this.dispose() + } + } + + if let parent = self.parent { + switch event { + case .next(let value): + self.setNextValue(value) + parent.next(self.index) + case .error(let error): + parent.fail(error) + case .completed: + parent.done(self.index) + } + } + } +} diff --git a/Pods/RxSwift/RxSwift/ObserverType.swift b/Pods/RxSwift/RxSwift/ObserverType.swift new file mode 100644 index 0000000..b7a6648 --- /dev/null +++ b/Pods/RxSwift/RxSwift/ObserverType.swift @@ -0,0 +1,40 @@ +// +// ObserverType.swift +// RxSwift +// +// Created by Krunoslav Zaher on 2/8/15. +// Copyright © 2015 Krunoslav Zaher. All rights reserved. +// + +/// Supports push-style iteration over an observable sequence. +public protocol ObserverType { + /// The type of elements in sequence that observer can observe. + associatedtype Element + + /// Notify observer about sequence event. + /// + /// - parameter event: Event that occurred. + func on(_ event: Event) +} + +/// Convenience API extensions to provide alternate next, error, completed events +extension ObserverType { + + /// Convenience method equivalent to `on(.next(element: Element))` + /// + /// - parameter element: Next element to send to observer(s) + public func onNext(_ element: Element) { + self.on(.next(element)) + } + + /// Convenience method equivalent to `on(.completed)` + public func onCompleted() { + self.on(.completed) + } + + /// Convenience method equivalent to `on(.error(Swift.Error))` + /// - parameter error: Swift.Error to send to observer(s) + public func onError(_ error: Swift.Error) { + self.on(.error(error)) + } +} diff --git a/Pods/RxSwift/RxSwift/Observers/AnonymousObserver.swift b/Pods/RxSwift/RxSwift/Observers/AnonymousObserver.swift new file mode 100644 index 0000000..cbb42dc --- /dev/null +++ b/Pods/RxSwift/RxSwift/Observers/AnonymousObserver.swift @@ -0,0 +1,30 @@ +// +// AnonymousObserver.swift +// RxSwift +// +// Created by Krunoslav Zaher on 2/8/15. +// Copyright © 2015 Krunoslav Zaher. All rights reserved. +// + +final class AnonymousObserver: ObserverBase { + typealias EventHandler = (Event) -> Void + + private let eventHandler : EventHandler + + init(_ eventHandler: @escaping EventHandler) { +#if TRACE_RESOURCES + _ = Resources.incrementTotal() +#endif + self.eventHandler = eventHandler + } + + override func onCore(_ event: Event) { + self.eventHandler(event) + } + +#if TRACE_RESOURCES + deinit { + _ = Resources.decrementTotal() + } +#endif +} diff --git a/Pods/RxSwift/RxSwift/Observers/ObserverBase.swift b/Pods/RxSwift/RxSwift/Observers/ObserverBase.swift new file mode 100644 index 0000000..48e0986 --- /dev/null +++ b/Pods/RxSwift/RxSwift/Observers/ObserverBase.swift @@ -0,0 +1,32 @@ +// +// ObserverBase.swift +// RxSwift +// +// Created by Krunoslav Zaher on 2/15/15. +// Copyright © 2015 Krunoslav Zaher. All rights reserved. +// + +class ObserverBase : Disposable, ObserverType { + private let isStopped = AtomicInt(0) + + func on(_ event: Event) { + switch event { + case .next: + if load(self.isStopped) == 0 { + self.onCore(event) + } + case .error, .completed: + if fetchOr(self.isStopped, 1) == 0 { + self.onCore(event) + } + } + } + + func onCore(_ event: Event) { + rxAbstractMethod() + } + + func dispose() { + fetchOr(self.isStopped, 1) + } +} diff --git a/Pods/RxSwift/RxSwift/Observers/TailRecursiveSink.swift b/Pods/RxSwift/RxSwift/Observers/TailRecursiveSink.swift new file mode 100644 index 0000000..fd52700 --- /dev/null +++ b/Pods/RxSwift/RxSwift/Observers/TailRecursiveSink.swift @@ -0,0 +1,151 @@ +// +// TailRecursiveSink.swift +// RxSwift +// +// Created by Krunoslav Zaher on 3/21/15. +// Copyright © 2015 Krunoslav Zaher. All rights reserved. +// + +enum TailRecursiveSinkCommand { + case moveNext + case dispose +} + +#if DEBUG || TRACE_RESOURCES + public var maxTailRecursiveSinkStackSize = 0 +#endif + +/// This class is usually used with `Generator` version of the operators. +class TailRecursiveSink + : Sink + , InvocableWithValueType where Sequence.Element: ObservableConvertibleType, Sequence.Element.Element == Observer.Element { + typealias Value = TailRecursiveSinkCommand + typealias Element = Observer.Element + typealias SequenceGenerator = (generator: Sequence.Iterator, remaining: IntMax?) + + var generators: [SequenceGenerator] = [] + var disposed = false + var subscription = SerialDisposable() + + // this is thread safe object + var gate = AsyncLock>>() + + override init(observer: Observer, cancel: Cancelable) { + super.init(observer: observer, cancel: cancel) + } + + func run(_ sources: SequenceGenerator) -> Disposable { + self.generators.append(sources) + + self.schedule(.moveNext) + + return self.subscription + } + + func invoke(_ command: TailRecursiveSinkCommand) { + switch command { + case .dispose: + self.disposeCommand() + case .moveNext: + self.moveNextCommand() + } + } + + // simple implementation for now + func schedule(_ command: TailRecursiveSinkCommand) { + self.gate.invoke(InvocableScheduledItem(invocable: self, state: command)) + } + + func done() { + self.forwardOn(.completed) + self.dispose() + } + + func extract(_ observable: Observable) -> SequenceGenerator? { + rxAbstractMethod() + } + + // should be done on gate locked + + private func moveNextCommand() { + var next: Observable? + + repeat { + guard let (g, left) = self.generators.last else { + break + } + + if self.isDisposed { + return + } + + self.generators.removeLast() + + var e = g + + guard let nextCandidate = e.next()?.asObservable() else { + continue + } + + // `left` is a hint of how many elements are left in generator. + // In case this is the last element, then there is no need to push + // that generator on stack. + // + // This is an optimization used to make sure in tail recursive case + // there is no memory leak in case this operator is used to generate non terminating + // sequence. + + if let knownOriginalLeft = left { + // `- 1` because generator.next() has just been called + if knownOriginalLeft - 1 >= 1 { + self.generators.append((e, knownOriginalLeft - 1)) + } + } + else { + self.generators.append((e, nil)) + } + + let nextGenerator = self.extract(nextCandidate) + + if let nextGenerator = nextGenerator { + self.generators.append(nextGenerator) + #if DEBUG || TRACE_RESOURCES + if maxTailRecursiveSinkStackSize < self.generators.count { + maxTailRecursiveSinkStackSize = self.generators.count + } + #endif + } + else { + next = nextCandidate + } + } while next == nil + + guard let existingNext = next else { + self.done() + return + } + + let disposable = SingleAssignmentDisposable() + self.subscription.disposable = disposable + disposable.setDisposable(self.subscribeToNext(existingNext)) + } + + func subscribeToNext(_ source: Observable) -> Disposable { + rxAbstractMethod() + } + + func disposeCommand() { + self.disposed = true + self.generators.removeAll(keepingCapacity: false) + } + + override func dispose() { + super.dispose() + + self.subscription.dispose() + self.gate.dispose() + + self.schedule(.dispose) + } +} + diff --git a/Pods/RxSwift/RxSwift/Reactive.swift b/Pods/RxSwift/RxSwift/Reactive.swift new file mode 100644 index 0000000..1bf390d --- /dev/null +++ b/Pods/RxSwift/RxSwift/Reactive.swift @@ -0,0 +1,80 @@ +// +// Reactive.swift +// RxSwift +// +// Created by Yury Korolev on 5/2/16. +// Copyright © 2016 Krunoslav Zaher. All rights reserved. +// + +/** + Use `Reactive` proxy as customization point for constrained protocol extensions. + + General pattern would be: + + // 1. Extend Reactive protocol with constrain on Base + // Read as: Reactive Extension where Base is a SomeType + extension Reactive where Base: SomeType { + // 2. Put any specific reactive extension for SomeType here + } + + With this approach we can have more specialized methods and properties using + `Base` and not just specialized on common base type. + + `Binder`s are also automatically synthesized using `@dynamicMemberLookup` for writable reference properties of the reactive base. + */ + +@dynamicMemberLookup +public struct Reactive { + /// Base object to extend. + public let base: Base + + /// Creates extensions with base object. + /// + /// - parameter base: Base object. + public init(_ base: Base) { + self.base = base + } + + /// Automatically synthesized binder for a key path between the reactive + /// base and one of its properties + public subscript(dynamicMember keyPath: ReferenceWritableKeyPath) -> Binder where Base: AnyObject { + Binder(self.base) { base, value in + base[keyPath: keyPath] = value + } + } +} + +/// A type that has reactive extensions. +public protocol ReactiveCompatible { + /// Extended type + associatedtype ReactiveBase + + /// Reactive extensions. + static var rx: Reactive.Type { get set } + + /// Reactive extensions. + var rx: Reactive { get set } +} + +extension ReactiveCompatible { + /// Reactive extensions. + public static var rx: Reactive.Type { + get { Reactive.self } + // this enables using Reactive to "mutate" base type + // swiftlint:disable:next unused_setter_value + set { } + } + + /// Reactive extensions. + public var rx: Reactive { + get { Reactive(self) } + // this enables using Reactive to "mutate" base object + // swiftlint:disable:next unused_setter_value + set { } + } +} + +import Foundation + +/// Extend NSObject with `rx` proxy. +extension NSObject: ReactiveCompatible { } diff --git a/Pods/RxSwift/RxSwift/Rx.swift b/Pods/RxSwift/RxSwift/Rx.swift new file mode 100644 index 0000000..bcdd279 --- /dev/null +++ b/Pods/RxSwift/RxSwift/Rx.swift @@ -0,0 +1,142 @@ +// +// Rx.swift +// RxSwift +// +// Created by Krunoslav Zaher on 2/14/15. +// Copyright © 2015 Krunoslav Zaher. All rights reserved. +// + +#if TRACE_RESOURCES + private let resourceCount = AtomicInt(0) + + /// Resource utilization information + public struct Resources { + /// Counts internal Rx resource allocations (Observables, Observers, Disposables, etc.). This provides a simple way to detect leaks during development. + public static var total: Int32 { + load(resourceCount) + } + + /// Increments `Resources.total` resource count. + /// + /// - returns: New resource count + public static func incrementTotal() -> Int32 { + increment(resourceCount) + } + + /// Decrements `Resources.total` resource count + /// + /// - returns: New resource count + public static func decrementTotal() -> Int32 { + decrement(resourceCount) + } + } +#endif + +/// Swift does not implement abstract methods. This method is used as a runtime check to ensure that methods which intended to be abstract (i.e., they should be implemented in subclasses) are not called directly on the superclass. +func rxAbstractMethod(file: StaticString = #file, line: UInt = #line) -> Swift.Never { + rxFatalError("Abstract method", file: file, line: line) +} + +func rxFatalError(_ lastMessage: @autoclosure () -> String, file: StaticString = #file, line: UInt = #line) -> Swift.Never { + fatalError(lastMessage(), file: file, line: line) +} + +func rxFatalErrorInDebug(_ lastMessage: @autoclosure () -> String, file: StaticString = #file, line: UInt = #line) { + #if DEBUG + fatalError(lastMessage(), file: file, line: line) + #else + print("\(file):\(line): \(lastMessage())") + #endif +} + +func incrementChecked(_ i: inout Int) throws -> Int { + if i == Int.max { + throw RxError.overflow + } + defer { i += 1 } + return i +} + +func decrementChecked(_ i: inout Int) throws -> Int { + if i == Int.min { + throw RxError.overflow + } + defer { i -= 1 } + return i +} + +#if DEBUG + import Foundation + final class SynchronizationTracker { + private let lock = RecursiveLock() + + public enum SynchronizationErrorMessages: String { + case variable = "Two different threads are trying to assign the same `Variable.value` unsynchronized.\n This is undefined behavior because the end result (variable value) is nondeterministic and depends on the \n operating system thread scheduler. This will cause random behavior of your program.\n" + case `default` = "Two different unsynchronized threads are trying to send some event simultaneously.\n This is undefined behavior because the ordering of the effects caused by these events is nondeterministic and depends on the \n operating system thread scheduler. This will result in a random behavior of your program.\n" + } + + private var threads = [UnsafeMutableRawPointer: Int]() + + private func synchronizationError(_ message: String) { + #if FATAL_SYNCHRONIZATION + rxFatalError(message) + #else + print(message) + #endif + } + + func register(synchronizationErrorMessage: SynchronizationErrorMessages) { + self.lock.lock(); defer { self.lock.unlock() } + let pointer = Unmanaged.passUnretained(Thread.current).toOpaque() + let count = (self.threads[pointer] ?? 0) + 1 + + if count > 1 { + self.synchronizationError( + "⚠️ Reentrancy anomaly was detected.\n" + + " > Debugging: To debug this issue you can set a breakpoint in \(#file):\(#line) and observe the call stack.\n" + + " > Problem: This behavior is breaking the observable sequence grammar. `next (error | completed)?`\n" + + " This behavior breaks the grammar because there is overlapping between sequence events.\n" + + " Observable sequence is trying to send an event before sending of previous event has finished.\n" + + " > Interpretation: This could mean that there is some kind of unexpected cyclic dependency in your code,\n" + + " or that the system is not behaving in the expected way.\n" + + " > Remedy: If this is the expected behavior this message can be suppressed by adding `.observe(on:MainScheduler.asyncInstance)`\n" + + " or by enqueuing sequence events in some other way.\n" + ) + } + + self.threads[pointer] = count + + if self.threads.count > 1 { + self.synchronizationError( + "⚠️ Synchronization anomaly was detected.\n" + + " > Debugging: To debug this issue you can set a breakpoint in \(#file):\(#line) and observe the call stack.\n" + + " > Problem: This behavior is breaking the observable sequence grammar. `next (error | completed)?`\n" + + " This behavior breaks the grammar because there is overlapping between sequence events.\n" + + " Observable sequence is trying to send an event before sending of previous event has finished.\n" + + " > Interpretation: " + synchronizationErrorMessage.rawValue + + " > Remedy: If this is the expected behavior this message can be suppressed by adding `.observe(on:MainScheduler.asyncInstance)`\n" + + " or by synchronizing sequence events in some other way.\n" + ) + } + } + + func unregister() { + self.lock.performLocked { + let pointer = Unmanaged.passUnretained(Thread.current).toOpaque() + self.threads[pointer] = (self.threads[pointer] ?? 1) - 1 + if self.threads[pointer] == 0 { + self.threads[pointer] = nil + } + } + } + } + +#endif + +/// RxSwift global hooks +public enum Hooks { + + // Should capture call stack + public static var recordCallStackOnError: Bool = false + +} diff --git a/Pods/RxSwift/RxSwift/RxMutableBox.swift b/Pods/RxSwift/RxSwift/RxMutableBox.swift new file mode 100644 index 0000000..73476c3 --- /dev/null +++ b/Pods/RxSwift/RxSwift/RxMutableBox.swift @@ -0,0 +1,53 @@ +// +// RxMutableBox.swift +// RxSwift +// +// Created by Krunoslav Zaher on 5/22/15. +// Copyright © 2015 Krunoslav Zaher. All rights reserved. +// + +#if os(Linux) +/// As Swift 5 was released, A patch to `Thread` for Linux +/// changed `threadDictionary` to a `NSMutableDictionary` instead of +/// a `Dictionary`: https://github.com/apple/swift-corelibs-foundation/pull/1762/files +/// +/// This means that on Linux specifically, `RxMutableBox` must be a `NSObject` +/// or it won't be possible to store it in `Thread.threadDictionary`. +/// +/// For more information, read the discussion at: +/// https://github.com/ReactiveX/RxSwift/issues/1911#issuecomment-479723298 +import Foundation + +/// Creates mutable reference wrapper for any type. +final class RxMutableBox: NSObject { + /// Wrapped value + var value: T + + /// Creates reference wrapper for `value`. + /// + /// - parameter value: Value to wrap. + init (_ value: T) { + self.value = value + } +} +#else +/// Creates mutable reference wrapper for any type. +final class RxMutableBox: CustomDebugStringConvertible { + /// Wrapped value + var value: T + + /// Creates reference wrapper for `value`. + /// + /// - parameter value: Value to wrap. + init (_ value: T) { + self.value = value + } +} + +extension RxMutableBox { + /// - returns: Box description. + var debugDescription: String { + "MutatingBox(\(self.value))" + } +} +#endif diff --git a/Pods/RxSwift/RxSwift/SchedulerType.swift b/Pods/RxSwift/RxSwift/SchedulerType.swift new file mode 100644 index 0000000..6c8fe4a --- /dev/null +++ b/Pods/RxSwift/RxSwift/SchedulerType.swift @@ -0,0 +1,71 @@ +// +// SchedulerType.swift +// RxSwift +// +// Created by Krunoslav Zaher on 2/8/15. +// Copyright © 2015 Krunoslav Zaher. All rights reserved. +// + +import Dispatch +import Foundation + +// Type that represents time interval in the context of RxSwift. +public typealias RxTimeInterval = DispatchTimeInterval + +/// Type that represents absolute time in the context of RxSwift. +public typealias RxTime = Date + +/// Represents an object that schedules units of work. +public protocol SchedulerType: ImmediateSchedulerType { + + /// - returns: Current time. + var now : RxTime { + get + } + + /** + Schedules an action to be executed. + + - parameter state: State passed to the action to be executed. + - parameter dueTime: Relative time after which to execute the action. + - parameter action: Action to be executed. + - returns: The disposable object used to cancel the scheduled action (best effort). + */ + func scheduleRelative(_ state: StateType, dueTime: RxTimeInterval, action: @escaping (StateType) -> Disposable) -> Disposable + + /** + Schedules a periodic piece of work. + + - parameter state: State passed to the action to be executed. + - parameter startAfter: Period after which initial work should be run. + - parameter period: Period for running the work periodically. + - parameter action: Action to be executed. + - returns: The disposable object used to cancel the scheduled action (best effort). + */ + func schedulePeriodic(_ state: StateType, startAfter: RxTimeInterval, period: RxTimeInterval, action: @escaping (StateType) -> StateType) -> Disposable +} + +extension SchedulerType { + + /** + Periodic task will be emulated using recursive scheduling. + + - parameter state: Initial state passed to the action upon the first iteration. + - parameter startAfter: Period after which initial work should be run. + - parameter period: Period for running the work periodically. + - returns: The disposable object used to cancel the scheduled recurring action (best effort). + */ + public func schedulePeriodic(_ state: StateType, startAfter: RxTimeInterval, period: RxTimeInterval, action: @escaping (StateType) -> StateType) -> Disposable { + let schedule = SchedulePeriodicRecursive(scheduler: self, startAfter: startAfter, period: period, action: action, state: state) + + return schedule.start() + } + + func scheduleRecursive(_ state: State, dueTime: RxTimeInterval, action: @escaping (State, AnyRecursiveScheduler) -> Void) -> Disposable { + let scheduler = AnyRecursiveScheduler(scheduler: self, action: action) + + scheduler.schedule(state, dueTime: dueTime) + + return Disposables.create(with: scheduler.dispose) + } +} diff --git a/Pods/RxSwift/RxSwift/Schedulers/ConcurrentDispatchQueueScheduler.swift b/Pods/RxSwift/RxSwift/Schedulers/ConcurrentDispatchQueueScheduler.swift new file mode 100644 index 0000000..02c47c9 --- /dev/null +++ b/Pods/RxSwift/RxSwift/Schedulers/ConcurrentDispatchQueueScheduler.swift @@ -0,0 +1,82 @@ +// +// ConcurrentDispatchQueueScheduler.swift +// RxSwift +// +// Created by Krunoslav Zaher on 7/5/15. +// Copyright © 2015 Krunoslav Zaher. All rights reserved. +// + +import Dispatch +import Foundation + +/// Abstracts the work that needs to be performed on a specific `dispatch_queue_t`. You can also pass a serial dispatch queue, it shouldn't cause any problems. +/// +/// This scheduler is suitable when some work needs to be performed in background. +public class ConcurrentDispatchQueueScheduler: SchedulerType { + public typealias TimeInterval = Foundation.TimeInterval + public typealias Time = Date + + public var now : Date { + Date() + } + + let configuration: DispatchQueueConfiguration + + /// Constructs new `ConcurrentDispatchQueueScheduler` that wraps `queue`. + /// + /// - parameter queue: Target dispatch queue. + /// - parameter leeway: The amount of time, in nanoseconds, that the system will defer the timer. + public init(queue: DispatchQueue, leeway: DispatchTimeInterval = DispatchTimeInterval.nanoseconds(0)) { + self.configuration = DispatchQueueConfiguration(queue: queue, leeway: leeway) + } + + /// Convenience init for scheduler that wraps one of the global concurrent dispatch queues. + /// + /// - parameter qos: Target global dispatch queue, by quality of service class. + /// - parameter leeway: The amount of time, in nanoseconds, that the system will defer the timer. + public convenience init(qos: DispatchQoS, leeway: DispatchTimeInterval = DispatchTimeInterval.nanoseconds(0)) { + self.init(queue: DispatchQueue( + label: "rxswift.queue.\(qos)", + qos: qos, + attributes: [DispatchQueue.Attributes.concurrent], + target: nil), + leeway: leeway + ) + } + + /** + Schedules an action to be executed immediately. + + - parameter state: State passed to the action to be executed. + - parameter action: Action to be executed. + - returns: The disposable object used to cancel the scheduled action (best effort). + */ + public final func schedule(_ state: StateType, action: @escaping (StateType) -> Disposable) -> Disposable { + self.configuration.schedule(state, action: action) + } + + /** + Schedules an action to be executed. + + - parameter state: State passed to the action to be executed. + - parameter dueTime: Relative time after which to execute the action. + - parameter action: Action to be executed. + - returns: The disposable object used to cancel the scheduled action (best effort). + */ + public final func scheduleRelative(_ state: StateType, dueTime: RxTimeInterval, action: @escaping (StateType) -> Disposable) -> Disposable { + self.configuration.scheduleRelative(state, dueTime: dueTime, action: action) + } + + /** + Schedules a periodic piece of work. + + - parameter state: State passed to the action to be executed. + - parameter startAfter: Period after which initial work should be run. + - parameter period: Period for running the work periodically. + - parameter action: Action to be executed. + - returns: The disposable object used to cancel the scheduled action (best effort). + */ + public func schedulePeriodic(_ state: StateType, startAfter: RxTimeInterval, period: RxTimeInterval, action: @escaping (StateType) -> StateType) -> Disposable { + self.configuration.schedulePeriodic(state, startAfter: startAfter, period: period, action: action) + } +} diff --git a/Pods/RxSwift/RxSwift/Schedulers/ConcurrentMainScheduler.swift b/Pods/RxSwift/RxSwift/Schedulers/ConcurrentMainScheduler.swift new file mode 100644 index 0000000..c438d7d --- /dev/null +++ b/Pods/RxSwift/RxSwift/Schedulers/ConcurrentMainScheduler.swift @@ -0,0 +1,87 @@ +// +// ConcurrentMainScheduler.swift +// RxSwift +// +// Created by Krunoslav Zaher on 10/17/15. +// Copyright © 2015 Krunoslav Zaher. All rights reserved. +// + +import Dispatch +import Foundation + +/** +Abstracts work that needs to be performed on `MainThread`. In case `schedule` methods are called from main thread, it will perform action immediately without scheduling. + +This scheduler is optimized for `subscribeOn` operator. If you want to observe observable sequence elements on main thread using `observeOn` operator, +`MainScheduler` is more suitable for that purpose. +*/ +public final class ConcurrentMainScheduler : SchedulerType { + public typealias TimeInterval = Foundation.TimeInterval + public typealias Time = Date + + private let mainScheduler: MainScheduler + private let mainQueue: DispatchQueue + + /// - returns: Current time. + public var now: Date { + self.mainScheduler.now as Date + } + + private init(mainScheduler: MainScheduler) { + self.mainQueue = DispatchQueue.main + self.mainScheduler = mainScheduler + } + + /// Singleton instance of `ConcurrentMainScheduler` + public static let instance = ConcurrentMainScheduler(mainScheduler: MainScheduler.instance) + + /** + Schedules an action to be executed immediately. + + - parameter state: State passed to the action to be executed. + - parameter action: Action to be executed. + - returns: The disposable object used to cancel the scheduled action (best effort). + */ + public func schedule(_ state: StateType, action: @escaping (StateType) -> Disposable) -> Disposable { + if DispatchQueue.isMain { + return action(state) + } + + let cancel = SingleAssignmentDisposable() + + self.mainQueue.async { + if cancel.isDisposed { + return + } + + cancel.setDisposable(action(state)) + } + + return cancel + } + + /** + Schedules an action to be executed. + + - parameter state: State passed to the action to be executed. + - parameter dueTime: Relative time after which to execute the action. + - parameter action: Action to be executed. + - returns: The disposable object used to cancel the scheduled action (best effort). + */ + public final func scheduleRelative(_ state: StateType, dueTime: RxTimeInterval, action: @escaping (StateType) -> Disposable) -> Disposable { + self.mainScheduler.scheduleRelative(state, dueTime: dueTime, action: action) + } + + /** + Schedules a periodic piece of work. + + - parameter state: State passed to the action to be executed. + - parameter startAfter: Period after which initial work should be run. + - parameter period: Period for running the work periodically. + - parameter action: Action to be executed. + - returns: The disposable object used to cancel the scheduled action (best effort). + */ + public func schedulePeriodic(_ state: StateType, startAfter: RxTimeInterval, period: RxTimeInterval, action: @escaping (StateType) -> StateType) -> Disposable { + self.mainScheduler.schedulePeriodic(state, startAfter: startAfter, period: period, action: action) + } +} diff --git a/Pods/RxSwift/RxSwift/Schedulers/CurrentThreadScheduler.swift b/Pods/RxSwift/RxSwift/Schedulers/CurrentThreadScheduler.swift new file mode 100644 index 0000000..16a7dd3 --- /dev/null +++ b/Pods/RxSwift/RxSwift/Schedulers/CurrentThreadScheduler.swift @@ -0,0 +1,131 @@ +// +// CurrentThreadScheduler.swift +// RxSwift +// +// Created by Krunoslav Zaher on 8/30/15. +// Copyright © 2015 Krunoslav Zaher. All rights reserved. +// + +import Dispatch +import Foundation + +#if os(Linux) + fileprivate enum CurrentThreadSchedulerQueueKey { + fileprivate static let instance = "RxSwift.CurrentThreadScheduler.Queue" + } +#else + private class CurrentThreadSchedulerQueueKey: NSObject, NSCopying { + static let instance = CurrentThreadSchedulerQueueKey() + private override init() { + super.init() + } + + override var hash: Int { + return 0 + } + + public func copy(with zone: NSZone? = nil) -> Any { + return self + } + } +#endif + +/// Represents an object that schedules units of work on the current thread. +/// +/// This is the default scheduler for operators that generate elements. +/// +/// This scheduler is also sometimes called `trampoline scheduler`. +public class CurrentThreadScheduler : ImmediateSchedulerType { + typealias ScheduleQueue = RxMutableBox> + + /// The singleton instance of the current thread scheduler. + public static let instance = CurrentThreadScheduler() + + private static var isScheduleRequiredKey: pthread_key_t = { () -> pthread_key_t in + let key = UnsafeMutablePointer.allocate(capacity: 1) + defer { key.deallocate() } + + guard pthread_key_create(key, nil) == 0 else { + rxFatalError("isScheduleRequired key creation failed") + } + + return key.pointee + }() + + private static var scheduleInProgressSentinel: UnsafeRawPointer = { () -> UnsafeRawPointer in + return UnsafeRawPointer(UnsafeMutablePointer.allocate(capacity: 1)) + }() + + static var queue : ScheduleQueue? { + get { + return Thread.getThreadLocalStorageValueForKey(CurrentThreadSchedulerQueueKey.instance) + } + set { + Thread.setThreadLocalStorageValue(newValue, forKey: CurrentThreadSchedulerQueueKey.instance) + } + } + + /// Gets a value that indicates whether the caller must call a `schedule` method. + public static private(set) var isScheduleRequired: Bool { + get { + return pthread_getspecific(CurrentThreadScheduler.isScheduleRequiredKey) == nil + } + set(isScheduleRequired) { + if pthread_setspecific(CurrentThreadScheduler.isScheduleRequiredKey, isScheduleRequired ? nil : scheduleInProgressSentinel) != 0 { + rxFatalError("pthread_setspecific failed") + } + } + } + + /** + Schedules an action to be executed as soon as possible on current thread. + + If this method is called on some thread that doesn't have `CurrentThreadScheduler` installed, scheduler will be + automatically installed and uninstalled after all work is performed. + + - parameter state: State passed to the action to be executed. + - parameter action: Action to be executed. + - returns: The disposable object used to cancel the scheduled action (best effort). + */ + public func schedule(_ state: StateType, action: @escaping (StateType) -> Disposable) -> Disposable { + if CurrentThreadScheduler.isScheduleRequired { + CurrentThreadScheduler.isScheduleRequired = false + + let disposable = action(state) + + defer { + CurrentThreadScheduler.isScheduleRequired = true + CurrentThreadScheduler.queue = nil + } + + guard let queue = CurrentThreadScheduler.queue else { + return disposable + } + + while let latest = queue.value.dequeue() { + if latest.isDisposed { + continue + } + latest.invoke() + } + + return disposable + } + + let existingQueue = CurrentThreadScheduler.queue + + let queue: RxMutableBox> + if let existingQueue = existingQueue { + queue = existingQueue + } + else { + queue = RxMutableBox(Queue(capacity: 1)) + CurrentThreadScheduler.queue = queue + } + + let scheduledItem = ScheduledItem(action: action, state: state) + queue.value.enqueue(scheduledItem) + + return scheduledItem + } +} diff --git a/Pods/RxSwift/RxSwift/Schedulers/HistoricalScheduler.swift b/Pods/RxSwift/RxSwift/Schedulers/HistoricalScheduler.swift new file mode 100644 index 0000000..fede60e --- /dev/null +++ b/Pods/RxSwift/RxSwift/Schedulers/HistoricalScheduler.swift @@ -0,0 +1,22 @@ +// +// HistoricalScheduler.swift +// RxSwift +// +// Created by Krunoslav Zaher on 12/27/15. +// Copyright © 2015 Krunoslav Zaher. All rights reserved. +// + +import Foundation + +/// Provides a virtual time scheduler that uses `Date` for absolute time and `NSTimeInterval` for relative time. +public class HistoricalScheduler : VirtualTimeScheduler { + + /** + Creates a new historical scheduler with initial clock value. + + - parameter initialClock: Initial value for virtual clock. + */ + public init(initialClock: RxTime = Date(timeIntervalSince1970: 0)) { + super.init(initialClock: initialClock, converter: HistoricalSchedulerTimeConverter()) + } +} diff --git a/Pods/RxSwift/RxSwift/Schedulers/HistoricalSchedulerTimeConverter.swift b/Pods/RxSwift/RxSwift/Schedulers/HistoricalSchedulerTimeConverter.swift new file mode 100644 index 0000000..a8fae8a --- /dev/null +++ b/Pods/RxSwift/RxSwift/Schedulers/HistoricalSchedulerTimeConverter.swift @@ -0,0 +1,67 @@ +// +// HistoricalSchedulerTimeConverter.swift +// RxSwift +// +// Created by Krunoslav Zaher on 12/27/15. +// Copyright © 2015 Krunoslav Zaher. All rights reserved. +// + +import Foundation + +/// Converts historical virtual time into real time. +/// +/// Since historical virtual time is also measured in `Date`, this converter is identity function. +public struct HistoricalSchedulerTimeConverter : VirtualTimeConverterType { + /// Virtual time unit used that represents ticks of virtual clock. + public typealias VirtualTimeUnit = RxTime + + /// Virtual time unit used to represent differences of virtual times. + public typealias VirtualTimeIntervalUnit = TimeInterval + + /// Returns identical value of argument passed because historical virtual time is equal to real time, just + /// decoupled from local machine clock. + public func convertFromVirtualTime(_ virtualTime: VirtualTimeUnit) -> RxTime { + virtualTime + } + + /// Returns identical value of argument passed because historical virtual time is equal to real time, just + /// decoupled from local machine clock. + public func convertToVirtualTime(_ time: RxTime) -> VirtualTimeUnit { + time + } + + /// Returns identical value of argument passed because historical virtual time is equal to real time, just + /// decoupled from local machine clock. + public func convertFromVirtualTimeInterval(_ virtualTimeInterval: VirtualTimeIntervalUnit) -> TimeInterval { + virtualTimeInterval + } + + /// Returns identical value of argument passed because historical virtual time is equal to real time, just + /// decoupled from local machine clock. + public func convertToVirtualTimeInterval(_ timeInterval: TimeInterval) -> VirtualTimeIntervalUnit { + timeInterval + } + + /** + Offsets `Date` by time interval. + + - parameter time: Time. + - parameter timeInterval: Time interval offset. + - returns: Time offsetted by time interval. + */ + public func offsetVirtualTime(_ time: VirtualTimeUnit, offset: VirtualTimeIntervalUnit) -> VirtualTimeUnit { + time.addingTimeInterval(offset) + } + + /// Compares two `Date`s. + public func compareVirtualTime(_ lhs: VirtualTimeUnit, _ rhs: VirtualTimeUnit) -> VirtualTimeComparison { + switch lhs.compare(rhs as Date) { + case .orderedAscending: + return .lessThan + case .orderedSame: + return .equal + case .orderedDescending: + return .greaterThan + } + } +} diff --git a/Pods/RxSwift/RxSwift/Schedulers/Internal/DispatchQueueConfiguration.swift b/Pods/RxSwift/RxSwift/Schedulers/Internal/DispatchQueueConfiguration.swift new file mode 100644 index 0000000..53f148d --- /dev/null +++ b/Pods/RxSwift/RxSwift/Schedulers/Internal/DispatchQueueConfiguration.swift @@ -0,0 +1,97 @@ +// +// DispatchQueueConfiguration.swift +// RxSwift +// +// Created by Krunoslav Zaher on 7/23/16. +// Copyright © 2016 Krunoslav Zaher. All rights reserved. +// + +import Dispatch +import Foundation + +struct DispatchQueueConfiguration { + let queue: DispatchQueue + let leeway: DispatchTimeInterval +} + +extension DispatchQueueConfiguration { + func schedule(_ state: StateType, action: @escaping (StateType) -> Disposable) -> Disposable { + let cancel = SingleAssignmentDisposable() + + self.queue.async { + if cancel.isDisposed { + return + } + + + cancel.setDisposable(action(state)) + } + + return cancel + } + + func scheduleRelative(_ state: StateType, dueTime: RxTimeInterval, action: @escaping (StateType) -> Disposable) -> Disposable { + let deadline = DispatchTime.now() + dueTime + + let compositeDisposable = CompositeDisposable() + + let timer = DispatchSource.makeTimerSource(queue: self.queue) + timer.schedule(deadline: deadline, leeway: self.leeway) + + // TODO: + // This looks horrible, and yes, it is. + // It looks like Apple has made a conceptual change here, and I'm unsure why. + // Need more info on this. + // It looks like just setting timer to fire and not holding a reference to it + // until deadline causes timer cancellation. + var timerReference: DispatchSourceTimer? = timer + let cancelTimer = Disposables.create { + timerReference?.cancel() + timerReference = nil + } + + timer.setEventHandler(handler: { + if compositeDisposable.isDisposed { + return + } + _ = compositeDisposable.insert(action(state)) + cancelTimer.dispose() + }) + timer.resume() + + _ = compositeDisposable.insert(cancelTimer) + + return compositeDisposable + } + + func schedulePeriodic(_ state: StateType, startAfter: RxTimeInterval, period: RxTimeInterval, action: @escaping (StateType) -> StateType) -> Disposable { + let initial = DispatchTime.now() + startAfter + + var timerState = state + + let timer = DispatchSource.makeTimerSource(queue: self.queue) + timer.schedule(deadline: initial, repeating: period, leeway: self.leeway) + + // TODO: + // This looks horrible, and yes, it is. + // It looks like Apple has made a conceptual change here, and I'm unsure why. + // Need more info on this. + // It looks like just setting timer to fire and not holding a reference to it + // until deadline causes timer cancellation. + var timerReference: DispatchSourceTimer? = timer + let cancelTimer = Disposables.create { + timerReference?.cancel() + timerReference = nil + } + + timer.setEventHandler(handler: { + if cancelTimer.isDisposed { + return + } + timerState = action(timerState) + }) + timer.resume() + + return cancelTimer + } +} diff --git a/Pods/RxSwift/RxSwift/Schedulers/Internal/InvocableScheduledItem.swift b/Pods/RxSwift/RxSwift/Schedulers/Internal/InvocableScheduledItem.swift new file mode 100644 index 0000000..0e15056 --- /dev/null +++ b/Pods/RxSwift/RxSwift/Schedulers/Internal/InvocableScheduledItem.swift @@ -0,0 +1,22 @@ +// +// InvocableScheduledItem.swift +// RxSwift +// +// Created by Krunoslav Zaher on 11/7/15. +// Copyright © 2015 Krunoslav Zaher. All rights reserved. +// + +struct InvocableScheduledItem : InvocableType { + + let invocable: I + let state: I.Value + + init(invocable: I, state: I.Value) { + self.invocable = invocable + self.state = state + } + + func invoke() { + self.invocable.invoke(self.state) + } +} diff --git a/Pods/RxSwift/RxSwift/Schedulers/Internal/InvocableType.swift b/Pods/RxSwift/RxSwift/Schedulers/Internal/InvocableType.swift new file mode 100644 index 0000000..0dba433 --- /dev/null +++ b/Pods/RxSwift/RxSwift/Schedulers/Internal/InvocableType.swift @@ -0,0 +1,17 @@ +// +// InvocableType.swift +// RxSwift +// +// Created by Krunoslav Zaher on 11/7/15. +// Copyright © 2015 Krunoslav Zaher. All rights reserved. +// + +protocol InvocableType { + func invoke() +} + +protocol InvocableWithValueType { + associatedtype Value + + func invoke(_ value: Value) +} diff --git a/Pods/RxSwift/RxSwift/Schedulers/Internal/ScheduledItem.swift b/Pods/RxSwift/RxSwift/Schedulers/Internal/ScheduledItem.swift new file mode 100644 index 0000000..3d790d7 --- /dev/null +++ b/Pods/RxSwift/RxSwift/Schedulers/Internal/ScheduledItem.swift @@ -0,0 +1,35 @@ +// +// ScheduledItem.swift +// RxSwift +// +// Created by Krunoslav Zaher on 9/2/15. +// Copyright © 2015 Krunoslav Zaher. All rights reserved. +// + +struct ScheduledItem + : ScheduledItemType + , InvocableType { + typealias Action = (T) -> Disposable + + private let action: Action + private let state: T + + private let disposable = SingleAssignmentDisposable() + + var isDisposed: Bool { + self.disposable.isDisposed + } + + init(action: @escaping Action, state: T) { + self.action = action + self.state = state + } + + func invoke() { + self.disposable.setDisposable(self.action(self.state)) + } + + func dispose() { + self.disposable.dispose() + } +} diff --git a/Pods/RxSwift/RxSwift/Schedulers/Internal/ScheduledItemType.swift b/Pods/RxSwift/RxSwift/Schedulers/Internal/ScheduledItemType.swift new file mode 100644 index 0000000..d2b16ca --- /dev/null +++ b/Pods/RxSwift/RxSwift/Schedulers/Internal/ScheduledItemType.swift @@ -0,0 +1,13 @@ +// +// ScheduledItemType.swift +// RxSwift +// +// Created by Krunoslav Zaher on 11/7/15. +// Copyright © 2015 Krunoslav Zaher. All rights reserved. +// + +protocol ScheduledItemType + : Cancelable + , InvocableType { + func invoke() +} diff --git a/Pods/RxSwift/RxSwift/Schedulers/MainScheduler.swift b/Pods/RxSwift/RxSwift/Schedulers/MainScheduler.swift new file mode 100644 index 0000000..f6a507f --- /dev/null +++ b/Pods/RxSwift/RxSwift/Schedulers/MainScheduler.swift @@ -0,0 +1,80 @@ +// +// MainScheduler.swift +// RxSwift +// +// Created by Krunoslav Zaher on 2/8/15. +// Copyright © 2015 Krunoslav Zaher. All rights reserved. +// + +import Dispatch +#if !os(Linux) + import Foundation +#endif + +/** +Abstracts work that needs to be performed on `DispatchQueue.main`. In case `schedule` methods are called from `DispatchQueue.main`, it will perform action immediately without scheduling. + +This scheduler is usually used to perform UI work. + +Main scheduler is a specialization of `SerialDispatchQueueScheduler`. + +This scheduler is optimized for `observeOn` operator. To ensure observable sequence is subscribed on main thread using `subscribeOn` +operator please use `ConcurrentMainScheduler` because it is more optimized for that purpose. +*/ +public final class MainScheduler : SerialDispatchQueueScheduler { + + private let mainQueue: DispatchQueue + + let numberEnqueued = AtomicInt(0) + + /// Initializes new instance of `MainScheduler`. + public init() { + self.mainQueue = DispatchQueue.main + super.init(serialQueue: self.mainQueue) + } + + /// Singleton instance of `MainScheduler` + public static let instance = MainScheduler() + + /// Singleton instance of `MainScheduler` that always schedules work asynchronously + /// and doesn't perform optimizations for calls scheduled from main queue. + public static let asyncInstance = SerialDispatchQueueScheduler(serialQueue: DispatchQueue.main) + + /// In case this method is called on a background thread it will throw an exception. + public static func ensureExecutingOnScheduler(errorMessage: String? = nil) { + if !DispatchQueue.isMain { + rxFatalError(errorMessage ?? "Executing on background thread. Please use `MainScheduler.instance.schedule` to schedule work on main thread.") + } + } + + /// In case this method is running on a background thread it will throw an exception. + public static func ensureRunningOnMainThread(errorMessage: String? = nil) { + #if !os(Linux) // isMainThread is not implemented in Linux Foundation + guard Thread.isMainThread else { + rxFatalError(errorMessage ?? "Running on background thread.") + } + #endif + } + + override func scheduleInternal(_ state: StateType, action: @escaping (StateType) -> Disposable) -> Disposable { + let previousNumberEnqueued = increment(self.numberEnqueued) + + if DispatchQueue.isMain && previousNumberEnqueued == 0 { + let disposable = action(state) + decrement(self.numberEnqueued) + return disposable + } + + let cancel = SingleAssignmentDisposable() + + self.mainQueue.async { + if !cancel.isDisposed { + cancel.setDisposable(action(state)) + } + + decrement(self.numberEnqueued) + } + + return cancel + } +} diff --git a/Pods/RxSwift/RxSwift/Schedulers/OperationQueueScheduler.swift b/Pods/RxSwift/RxSwift/Schedulers/OperationQueueScheduler.swift new file mode 100644 index 0000000..f0ad3d3 --- /dev/null +++ b/Pods/RxSwift/RxSwift/Schedulers/OperationQueueScheduler.swift @@ -0,0 +1,54 @@ +// +// OperationQueueScheduler.swift +// RxSwift +// +// Created by Krunoslav Zaher on 4/4/15. +// Copyright © 2015 Krunoslav Zaher. All rights reserved. +// + +import Dispatch +import Foundation + +/// Abstracts the work that needs to be performed on a specific `NSOperationQueue`. +/// +/// This scheduler is suitable for cases when there is some bigger chunk of work that needs to be performed in background and you want to fine tune concurrent processing using `maxConcurrentOperationCount`. +public class OperationQueueScheduler: ImmediateSchedulerType { + public let operationQueue: OperationQueue + public let queuePriority: Operation.QueuePriority + + /// Constructs new instance of `OperationQueueScheduler` that performs work on `operationQueue`. + /// + /// - parameter operationQueue: Operation queue targeted to perform work on. + /// - parameter queuePriority: Queue priority which will be assigned to new operations. + public init(operationQueue: OperationQueue, queuePriority: Operation.QueuePriority = .normal) { + self.operationQueue = operationQueue + self.queuePriority = queuePriority + } + + /** + Schedules an action to be executed recursively. + + - parameter state: State passed to the action to be executed. + - parameter action: Action to execute recursively. The last parameter passed to the action is used to trigger recursive scheduling of the action, passing in recursive invocation state. + - returns: The disposable object used to cancel the scheduled action (best effort). + */ + public func schedule(_ state: StateType, action: @escaping (StateType) -> Disposable) -> Disposable { + let cancel = SingleAssignmentDisposable() + + let operation = BlockOperation { + if cancel.isDisposed { + return + } + + + cancel.setDisposable(action(state)) + } + + operation.queuePriority = self.queuePriority + + self.operationQueue.addOperation(operation) + + return cancel + } + +} diff --git a/Pods/RxSwift/RxSwift/Schedulers/RecursiveScheduler.swift b/Pods/RxSwift/RxSwift/Schedulers/RecursiveScheduler.swift new file mode 100644 index 0000000..0ee78cd --- /dev/null +++ b/Pods/RxSwift/RxSwift/Schedulers/RecursiveScheduler.swift @@ -0,0 +1,220 @@ +// +// RecursiveScheduler.swift +// RxSwift +// +// Created by Krunoslav Zaher on 6/7/15. +// Copyright © 2015 Krunoslav Zaher. All rights reserved. +// + +private enum ScheduleState { + case initial + case added(CompositeDisposable.DisposeKey) + case done +} + +/// Type erased recursive scheduler. +final class AnyRecursiveScheduler { + + typealias Action = (State, AnyRecursiveScheduler) -> Void + + private let lock = RecursiveLock() + + // state + private let group = CompositeDisposable() + + private var scheduler: SchedulerType + private var action: Action? + + init(scheduler: SchedulerType, action: @escaping Action) { + self.action = action + self.scheduler = scheduler + } + + /** + Schedules an action to be executed recursively. + + - parameter state: State passed to the action to be executed. + - parameter dueTime: Relative time after which to execute the recursive action. + */ + func schedule(_ state: State, dueTime: RxTimeInterval) { + var scheduleState: ScheduleState = .initial + + let d = self.scheduler.scheduleRelative(state, dueTime: dueTime) { state -> Disposable in + // best effort + if self.group.isDisposed { + return Disposables.create() + } + + let action = self.lock.performLocked { () -> Action? in + switch scheduleState { + case let .added(removeKey): + self.group.remove(for: removeKey) + case .initial: + break + case .done: + break + } + + scheduleState = .done + + return self.action + } + + if let action = action { + action(state, self) + } + + return Disposables.create() + } + + self.lock.performLocked { + switch scheduleState { + case .added: + rxFatalError("Invalid state") + case .initial: + if let removeKey = self.group.insert(d) { + scheduleState = .added(removeKey) + } + else { + scheduleState = .done + } + case .done: + break + } + } + } + + /// Schedules an action to be executed recursively. + /// + /// - parameter state: State passed to the action to be executed. + func schedule(_ state: State) { + var scheduleState: ScheduleState = .initial + + let d = self.scheduler.schedule(state) { state -> Disposable in + // best effort + if self.group.isDisposed { + return Disposables.create() + } + + let action = self.lock.performLocked { () -> Action? in + switch scheduleState { + case let .added(removeKey): + self.group.remove(for: removeKey) + case .initial: + break + case .done: + break + } + + scheduleState = .done + + return self.action + } + + if let action = action { + action(state, self) + } + + return Disposables.create() + } + + self.lock.performLocked { + switch scheduleState { + case .added: + rxFatalError("Invalid state") + case .initial: + if let removeKey = self.group.insert(d) { + scheduleState = .added(removeKey) + } + else { + scheduleState = .done + } + case .done: + break + } + } + } + + func dispose() { + self.lock.performLocked { + self.action = nil + } + self.group.dispose() + } +} + +/// Type erased recursive scheduler. +final class RecursiveImmediateScheduler { + typealias Action = (_ state: State, _ recurse: (State) -> Void) -> Void + + private var lock = SpinLock() + private let group = CompositeDisposable() + + private var action: Action? + private let scheduler: ImmediateSchedulerType + + init(action: @escaping Action, scheduler: ImmediateSchedulerType) { + self.action = action + self.scheduler = scheduler + } + + // immediate scheduling + + /// Schedules an action to be executed recursively. + /// + /// - parameter state: State passed to the action to be executed. + func schedule(_ state: State) { + var scheduleState: ScheduleState = .initial + + let d = self.scheduler.schedule(state) { state -> Disposable in + // best effort + if self.group.isDisposed { + return Disposables.create() + } + + let action = self.lock.performLocked { () -> Action? in + switch scheduleState { + case let .added(removeKey): + self.group.remove(for: removeKey) + case .initial: + break + case .done: + break + } + + scheduleState = .done + + return self.action + } + + if let action = action { + action(state, self.schedule) + } + + return Disposables.create() + } + + self.lock.performLocked { + switch scheduleState { + case .added: + rxFatalError("Invalid state") + case .initial: + if let removeKey = self.group.insert(d) { + scheduleState = .added(removeKey) + } + else { + scheduleState = .done + } + case .done: + break + } + } + } + + func dispose() { + self.lock.performLocked { + self.action = nil + } + self.group.dispose() + } +} diff --git a/Pods/RxSwift/RxSwift/Schedulers/SchedulerServices+Emulation.swift b/Pods/RxSwift/RxSwift/Schedulers/SchedulerServices+Emulation.swift new file mode 100644 index 0000000..cab2bc8 --- /dev/null +++ b/Pods/RxSwift/RxSwift/Schedulers/SchedulerServices+Emulation.swift @@ -0,0 +1,61 @@ +// +// SchedulerServices+Emulation.swift +// RxSwift +// +// Created by Krunoslav Zaher on 6/6/15. +// Copyright © 2015 Krunoslav Zaher. All rights reserved. +// + +enum SchedulePeriodicRecursiveCommand { + case tick + case dispatchStart +} + +final class SchedulePeriodicRecursive { + typealias RecursiveAction = (State) -> State + typealias RecursiveScheduler = AnyRecursiveScheduler + + private let scheduler: SchedulerType + private let startAfter: RxTimeInterval + private let period: RxTimeInterval + private let action: RecursiveAction + + private var state: State + private let pendingTickCount = AtomicInt(0) + + init(scheduler: SchedulerType, startAfter: RxTimeInterval, period: RxTimeInterval, action: @escaping RecursiveAction, state: State) { + self.scheduler = scheduler + self.startAfter = startAfter + self.period = period + self.action = action + self.state = state + } + + func start() -> Disposable { + self.scheduler.scheduleRecursive(SchedulePeriodicRecursiveCommand.tick, dueTime: self.startAfter, action: self.tick) + } + + func tick(_ command: SchedulePeriodicRecursiveCommand, scheduler: RecursiveScheduler) { + // Tries to emulate periodic scheduling as best as possible. + // The problem that could arise is if handling periodic ticks take too long, or + // tick interval is short. + switch command { + case .tick: + scheduler.schedule(.tick, dueTime: self.period) + + // The idea is that if on tick there wasn't any item enqueued, schedule to perform work immediately. + // Else work will be scheduled after previous enqueued work completes. + if increment(self.pendingTickCount) == 0 { + self.tick(.dispatchStart, scheduler: scheduler) + } + + case .dispatchStart: + self.state = self.action(self.state) + // Start work and schedule check is this last batch of work + if decrement(self.pendingTickCount) > 1 { + // This gives priority to scheduler emulation, it's not perfect, but helps + scheduler.schedule(SchedulePeriodicRecursiveCommand.dispatchStart) + } + } + } +} diff --git a/Pods/RxSwift/RxSwift/Schedulers/SerialDispatchQueueScheduler.swift b/Pods/RxSwift/RxSwift/Schedulers/SerialDispatchQueueScheduler.swift new file mode 100644 index 0000000..bb0013c --- /dev/null +++ b/Pods/RxSwift/RxSwift/Schedulers/SerialDispatchQueueScheduler.swift @@ -0,0 +1,131 @@ +// +// SerialDispatchQueueScheduler.swift +// RxSwift +// +// Created by Krunoslav Zaher on 2/8/15. +// Copyright © 2015 Krunoslav Zaher. All rights reserved. +// + +import Dispatch +import Foundation + +/** +Abstracts the work that needs to be performed on a specific `dispatch_queue_t`. It will make sure +that even if concurrent dispatch queue is passed, it's transformed into a serial one. + +It is extremely important that this scheduler is serial, because +certain operator perform optimizations that rely on that property. + +Because there is no way of detecting is passed dispatch queue serial or +concurrent, for every queue that is being passed, worst case (concurrent) +will be assumed, and internal serial proxy dispatch queue will be created. + +This scheduler can also be used with internal serial queue alone. + +In case some customization need to be made on it before usage, +internal serial queue can be customized using `serialQueueConfiguration` +callback. +*/ +public class SerialDispatchQueueScheduler : SchedulerType { + public typealias TimeInterval = Foundation.TimeInterval + public typealias Time = Date + + /// - returns: Current time. + public var now : Date { + Date() + } + + let configuration: DispatchQueueConfiguration + + /** + Constructs new `SerialDispatchQueueScheduler` that wraps `serialQueue`. + + - parameter serialQueue: Target dispatch queue. + - parameter leeway: The amount of time, in nanoseconds, that the system will defer the timer. + */ + init(serialQueue: DispatchQueue, leeway: DispatchTimeInterval = DispatchTimeInterval.nanoseconds(0)) { + self.configuration = DispatchQueueConfiguration(queue: serialQueue, leeway: leeway) + } + + /** + Constructs new `SerialDispatchQueueScheduler` with internal serial queue named `internalSerialQueueName`. + + Additional dispatch queue properties can be set after dispatch queue is created using `serialQueueConfiguration`. + + - parameter internalSerialQueueName: Name of internal serial dispatch queue. + - parameter serialQueueConfiguration: Additional configuration of internal serial dispatch queue. + - parameter leeway: The amount of time, in nanoseconds, that the system will defer the timer. + */ + public convenience init(internalSerialQueueName: String, serialQueueConfiguration: ((DispatchQueue) -> Void)? = nil, leeway: DispatchTimeInterval = DispatchTimeInterval.nanoseconds(0)) { + let queue = DispatchQueue(label: internalSerialQueueName, attributes: []) + serialQueueConfiguration?(queue) + self.init(serialQueue: queue, leeway: leeway) + } + + /** + Constructs new `SerialDispatchQueueScheduler` named `internalSerialQueueName` that wraps `queue`. + + - parameter queue: Possibly concurrent dispatch queue used to perform work. + - parameter internalSerialQueueName: Name of internal serial dispatch queue proxy. + - parameter leeway: The amount of time, in nanoseconds, that the system will defer the timer. + */ + public convenience init(queue: DispatchQueue, internalSerialQueueName: String, leeway: DispatchTimeInterval = DispatchTimeInterval.nanoseconds(0)) { + // Swift 3.0 IUO + let serialQueue = DispatchQueue(label: internalSerialQueueName, + attributes: [], + target: queue) + self.init(serialQueue: serialQueue, leeway: leeway) + } + + /** + Constructs new `SerialDispatchQueueScheduler` that wraps one of the global concurrent dispatch queues. + + - parameter qos: Identifier for global dispatch queue with specified quality of service class. + - parameter internalSerialQueueName: Custom name for internal serial dispatch queue proxy. + - parameter leeway: The amount of time, in nanoseconds, that the system will defer the timer. + */ + @available(macOS 10.10, *) + public convenience init(qos: DispatchQoS, internalSerialQueueName: String = "rx.global_dispatch_queue.serial", leeway: DispatchTimeInterval = DispatchTimeInterval.nanoseconds(0)) { + self.init(queue: DispatchQueue.global(qos: qos.qosClass), internalSerialQueueName: internalSerialQueueName, leeway: leeway) + } + + /** + Schedules an action to be executed immediately. + + - parameter state: State passed to the action to be executed. + - parameter action: Action to be executed. + - returns: The disposable object used to cancel the scheduled action (best effort). + */ + public final func schedule(_ state: StateType, action: @escaping (StateType) -> Disposable) -> Disposable { + self.scheduleInternal(state, action: action) + } + + func scheduleInternal(_ state: StateType, action: @escaping (StateType) -> Disposable) -> Disposable { + self.configuration.schedule(state, action: action) + } + + /** + Schedules an action to be executed. + + - parameter state: State passed to the action to be executed. + - parameter dueTime: Relative time after which to execute the action. + - parameter action: Action to be executed. + - returns: The disposable object used to cancel the scheduled action (best effort). + */ + public final func scheduleRelative(_ state: StateType, dueTime: RxTimeInterval, action: @escaping (StateType) -> Disposable) -> Disposable { + self.configuration.scheduleRelative(state, dueTime: dueTime, action: action) + } + + /** + Schedules a periodic piece of work. + + - parameter state: State passed to the action to be executed. + - parameter startAfter: Period after which initial work should be run. + - parameter period: Period for running the work periodically. + - parameter action: Action to be executed. + - returns: The disposable object used to cancel the scheduled action (best effort). + */ + public func schedulePeriodic(_ state: StateType, startAfter: RxTimeInterval, period: RxTimeInterval, action: @escaping (StateType) -> StateType) -> Disposable { + self.configuration.schedulePeriodic(state, startAfter: startAfter, period: period, action: action) + } +} diff --git a/Pods/RxSwift/RxSwift/Schedulers/VirtualTimeConverterType.swift b/Pods/RxSwift/RxSwift/Schedulers/VirtualTimeConverterType.swift new file mode 100644 index 0000000..34151f7 --- /dev/null +++ b/Pods/RxSwift/RxSwift/Schedulers/VirtualTimeConverterType.swift @@ -0,0 +1,97 @@ +// +// VirtualTimeConverterType.swift +// RxSwift +// +// Created by Krunoslav Zaher on 12/23/15. +// Copyright © 2015 Krunoslav Zaher. All rights reserved. +// + +import Foundation + +/// Parametrization for virtual time used by `VirtualTimeScheduler`s. +public protocol VirtualTimeConverterType { + /// Virtual time unit used that represents ticks of virtual clock. + associatedtype VirtualTimeUnit + + /// Virtual time unit used to represent differences of virtual times. + associatedtype VirtualTimeIntervalUnit + + /** + Converts virtual time to real time. + + - parameter virtualTime: Virtual time to convert to `Date`. + - returns: `Date` corresponding to virtual time. + */ + func convertFromVirtualTime(_ virtualTime: VirtualTimeUnit) -> RxTime + + /** + Converts real time to virtual time. + + - parameter time: `Date` to convert to virtual time. + - returns: Virtual time corresponding to `Date`. + */ + func convertToVirtualTime(_ time: RxTime) -> VirtualTimeUnit + + /** + Converts from virtual time interval to `NSTimeInterval`. + + - parameter virtualTimeInterval: Virtual time interval to convert to `NSTimeInterval`. + - returns: `NSTimeInterval` corresponding to virtual time interval. + */ + func convertFromVirtualTimeInterval(_ virtualTimeInterval: VirtualTimeIntervalUnit) -> TimeInterval + + /** + Converts from `NSTimeInterval` to virtual time interval. + + - parameter timeInterval: `NSTimeInterval` to convert to virtual time interval. + - returns: Virtual time interval corresponding to time interval. + */ + func convertToVirtualTimeInterval(_ timeInterval: TimeInterval) -> VirtualTimeIntervalUnit + + /** + Offsets virtual time by virtual time interval. + + - parameter time: Virtual time. + - parameter offset: Virtual time interval. + - returns: Time corresponding to time offsetted by virtual time interval. + */ + func offsetVirtualTime(_ time: VirtualTimeUnit, offset: VirtualTimeIntervalUnit) -> VirtualTimeUnit + + /** + This is additional abstraction because `Date` is unfortunately not comparable. + Extending `Date` with `Comparable` would be too risky because of possible collisions with other libraries. + */ + func compareVirtualTime(_ lhs: VirtualTimeUnit, _ rhs: VirtualTimeUnit) -> VirtualTimeComparison +} + +/** + Virtual time comparison result. + + This is additional abstraction because `Date` is unfortunately not comparable. + Extending `Date` with `Comparable` would be too risky because of possible collisions with other libraries. +*/ +public enum VirtualTimeComparison { + /// lhs < rhs. + case lessThan + /// lhs == rhs. + case equal + /// lhs > rhs. + case greaterThan +} + +extension VirtualTimeComparison { + /// lhs < rhs. + var lessThen: Bool { + self == .lessThan + } + + /// lhs > rhs + var greaterThan: Bool { + self == .greaterThan + } + + /// lhs == rhs + var equal: Bool { + self == .equal + } +} diff --git a/Pods/RxSwift/RxSwift/Schedulers/VirtualTimeScheduler.swift b/Pods/RxSwift/RxSwift/Schedulers/VirtualTimeScheduler.swift new file mode 100644 index 0000000..e74d5be --- /dev/null +++ b/Pods/RxSwift/RxSwift/Schedulers/VirtualTimeScheduler.swift @@ -0,0 +1,267 @@ +// +// VirtualTimeScheduler.swift +// RxSwift +// +// Created by Krunoslav Zaher on 2/14/15. +// Copyright © 2015 Krunoslav Zaher. All rights reserved. +// + +/// Base class for virtual time schedulers using a priority queue for scheduled items. +open class VirtualTimeScheduler + : SchedulerType { + + public typealias VirtualTime = Converter.VirtualTimeUnit + public typealias VirtualTimeInterval = Converter.VirtualTimeIntervalUnit + + private var running : Bool + + private var currentClock: VirtualTime + + private var schedulerQueue : PriorityQueue> + private var converter: Converter + + private var nextId = 0 + + /// - returns: Current time. + public var now: RxTime { + self.converter.convertFromVirtualTime(self.clock) + } + + /// - returns: Scheduler's absolute time clock value. + public var clock: VirtualTime { + self.currentClock + } + + /// Creates a new virtual time scheduler. + /// + /// - parameter initialClock: Initial value for the clock. + public init(initialClock: VirtualTime, converter: Converter) { + self.currentClock = initialClock + self.running = false + self.converter = converter + self.schedulerQueue = PriorityQueue(hasHigherPriority: { + switch converter.compareVirtualTime($0.time, $1.time) { + case .lessThan: + return true + case .equal: + return $0.id < $1.id + case .greaterThan: + return false + } + }, isEqual: { $0 === $1 }) + #if TRACE_RESOURCES + _ = Resources.incrementTotal() + #endif + } + + /** + Schedules an action to be executed immediately. + + - parameter state: State passed to the action to be executed. + - parameter action: Action to be executed. + - returns: The disposable object used to cancel the scheduled action (best effort). + */ + public func schedule(_ state: StateType, action: @escaping (StateType) -> Disposable) -> Disposable { + return self.scheduleRelative(state, dueTime: .microseconds(0)) { a in + return action(a) + } + } + + /** + Schedules an action to be executed. + + - parameter state: State passed to the action to be executed. + - parameter dueTime: Relative time after which to execute the action. + - parameter action: Action to be executed. + - returns: The disposable object used to cancel the scheduled action (best effort). + */ + public func scheduleRelative(_ state: StateType, dueTime: RxTimeInterval, action: @escaping (StateType) -> Disposable) -> Disposable { + let time = self.now.addingDispatchInterval(dueTime) + let absoluteTime = self.converter.convertToVirtualTime(time) + let adjustedTime = self.adjustScheduledTime(absoluteTime) + return self.scheduleAbsoluteVirtual(state, time: adjustedTime, action: action) + } + + /** + Schedules an action to be executed after relative time has passed. + + - parameter state: State passed to the action to be executed. + - parameter time: Absolute time when to execute the action. If this is less or equal then `now`, `now + 1` will be used. + - parameter action: Action to be executed. + - returns: The disposable object used to cancel the scheduled action (best effort). + */ + public func scheduleRelativeVirtual(_ state: StateType, dueTime: VirtualTimeInterval, action: @escaping (StateType) -> Disposable) -> Disposable { + let time = self.converter.offsetVirtualTime(self.clock, offset: dueTime) + return self.scheduleAbsoluteVirtual(state, time: time, action: action) + } + + /** + Schedules an action to be executed at absolute virtual time. + + - parameter state: State passed to the action to be executed. + - parameter time: Absolute time when to execute the action. + - parameter action: Action to be executed. + - returns: The disposable object used to cancel the scheduled action (best effort). + */ + public func scheduleAbsoluteVirtual(_ state: StateType, time: VirtualTime, action: @escaping (StateType) -> Disposable) -> Disposable { + MainScheduler.ensureExecutingOnScheduler() + + let compositeDisposable = CompositeDisposable() + + let item = VirtualSchedulerItem(action: { + return action(state) + }, time: time, id: self.nextId) + + self.nextId += 1 + + self.schedulerQueue.enqueue(item) + + _ = compositeDisposable.insert(item) + + return compositeDisposable + } + + /// Adjusts time of scheduling before adding item to schedule queue. + open func adjustScheduledTime(_ time: VirtualTime) -> VirtualTime { + time + } + + /// Starts the virtual time scheduler. + public func start() { + MainScheduler.ensureExecutingOnScheduler() + + if self.running { + return + } + + self.running = true + repeat { + guard let next = self.findNext() else { + break + } + + if self.converter.compareVirtualTime(next.time, self.clock).greaterThan { + self.currentClock = next.time + } + + next.invoke() + self.schedulerQueue.remove(next) + } while self.running + + self.running = false + } + + func findNext() -> VirtualSchedulerItem? { + while let front = self.schedulerQueue.peek() { + if front.isDisposed { + self.schedulerQueue.remove(front) + continue + } + + return front + } + + return nil + } + + /// Advances the scheduler's clock to the specified time, running all work till that point. + /// + /// - parameter virtualTime: Absolute time to advance the scheduler's clock to. + public func advanceTo(_ virtualTime: VirtualTime) { + MainScheduler.ensureExecutingOnScheduler() + + if self.running { + fatalError("Scheduler is already running") + } + + self.running = true + repeat { + guard let next = self.findNext() else { + break + } + + if self.converter.compareVirtualTime(next.time, virtualTime).greaterThan { + break + } + + if self.converter.compareVirtualTime(next.time, self.clock).greaterThan { + self.currentClock = next.time + } + next.invoke() + self.schedulerQueue.remove(next) + } while self.running + + self.currentClock = virtualTime + self.running = false + } + + /// Advances the scheduler's clock by the specified relative time. + public func sleep(_ virtualInterval: VirtualTimeInterval) { + MainScheduler.ensureExecutingOnScheduler() + + let sleepTo = self.converter.offsetVirtualTime(self.clock, offset: virtualInterval) + if self.converter.compareVirtualTime(sleepTo, self.clock).lessThen { + fatalError("Can't sleep to past.") + } + + self.currentClock = sleepTo + } + + /// Stops the virtual time scheduler. + public func stop() { + MainScheduler.ensureExecutingOnScheduler() + + self.running = false + } + + #if TRACE_RESOURCES + deinit { + _ = Resources.decrementTotal() + } + #endif +} + +// MARK: description + +extension VirtualTimeScheduler: CustomDebugStringConvertible { + /// A textual representation of `self`, suitable for debugging. + public var debugDescription: String { + self.schedulerQueue.debugDescription + } +} + +final class VirtualSchedulerItem